Skip to content

Latest commit

 

History

History
91 lines (65 loc) · 2.61 KB

basic-authentication.md

File metadata and controls

91 lines (65 loc) · 2.61 KB

Basic Authentication

HTTP Basic authentication (BA) implementation is the simplest technique for enforcing access controls to web resources because it doesn't require cookies, session identifiers, or login pages; rather, HTTP Basic authentication uses standard fields in the HTTP header, obviating the need for handshakes. Read more.

Simple example

package main

import (
	"github.com/kataras/iris"
	"github.com/kataras/iris/middleware/basicauth"
)

func main() {
	authentication := basicauth.Default(map[string]string{"myusername": "mypassword", "mySecondusername": "mySecondpassword"})

	// to global iris.UseFunc(authentication)
	// to party: iris.Party("/secret", authentication) { ... }

	// to routes
	iris.Get("/mysecret", authentication, func(ctx *iris.Context) {
		username := ctx.GetString("auth") // this can be changed, you will see at the middleware_basic_auth_2 folder
		ctx.Write("Hello authenticated user: %s ", username)
	})

	iris.Listen(":8080")
}

Configurable example

package main

import (
	"time"

	"github.com/kataras/iris"
	"github.com/kataras/iris/config"
	"github.com/kataras/iris/middleware/basicauth"
)

func main() {
	authConfig := config.BasicAuth{
		Users:      map[string]string{"myusername": "mypassword", "mySecondusername": "mySecondpassword"},
		Realm:      "Authorization Required", // if you don't set it it's "Authorization Required"
		ContextKey: "user",                   // if you don't set it it's "auth"
		Expires:    time.Duration(30) * time.Minute,
	}

	authentication := basicauth.New(authConfig)

	// to global iris.UseFunc(authentication)
	// to routes
	/*
		iris.Get("/mysecret", authentication, func(ctx *iris.Context) {
			username := ctx.GetString("user") //  the Contextkey from the authConfig
			ctx.Write("Hello authenticated user: %s ", username)
		})
	*/

	// to party

	needAuth := iris.Party("/secret", authentication)
	{
		needAuth.Get("/", func(ctx *iris.Context) {
			username := ctx.GetString("user") //  the Contextkey from the authConfig
			ctx.Write("Hello authenticated user: %s from localhost:8080/secret ", username)
		})

		needAuth.Get("/profile", func(ctx *iris.Context) {
			username := ctx.GetString("user") //  the Contextkey from the authConfig
			ctx.Write("Hello authenticated user: %s from localhost:8080/secret/profile ", username)
		})

		needAuth.Get("/settings", func(ctx *iris.Context) {
			username := ctx.GetString("user") //  the Contextkey from the authConfig
			ctx.Write("Hello authenticated user: %s from localhost:8080/secret/settings ", username)
		})
	}

	iris.Listen(":8080")
}