Using Basic Authentication
HTTP Basic Authentication is the simplest technique for enforcing access controls to web resources because it does not require cookies, session identifiers, or login pages; rather, HTTP Basic authentication uses standard fields in the HTTP header.
The Basic Authentication middleware is included with the Iris framework, so you do not need to install it separately.
1. Import the middleware
import "github.com/kataras/iris/v12/middleware/basicauth"
2. Configure the middleware with its Options
struct:
opts := basicauth.Options{
Allow: basicauth.AllowUsers(map[string]string{
"username": "password",
}),
Realm: "Authorization Required",
ErrorHandler: basicauth.DefaultErrorHandler,
// [...more options]
}
3. Initialize the middleware:
auth := basicauth.New(opts)
3.1 The above steps are the same as the Default
function:
auth := basicauth.Default(map[string]string{
"username": "password",
})
3.2 Use a custom slice of Users:
// The struct value MUST contain a Username and Passwords fields
// or GetUsername() string and GetPassword() string methods.
type User struct {
Username string
Password string
}
// [...]
auth := basicauth.Default([]User{...})
3.3 Load users from a file optionally, passwords are encrypted using the golang.org/x/crypto/bcrypt package:
auth := basicauth.Load("users.yml", basicauth.BCRYPT)
3.3.1 The same can be achieved using the Options
(recommended):
opts := basicauth.Options{
Allow: basicauth.AllowUsersFile("users.yml", basicauth.BCRYPT),
Realm: basicauth.DefaultRealm,
// [...more options]
}
auth := basicauth.New(opts)
Where the users.yml
may look like that:
- username: kataras
password: $2a$10$Irg8k8HWkDlvL0YDBKLCYee6j6zzIFTplJcvZYKA.B8/clHPZn2Ey
# encrypted of kataras_pass
role: admin
- username: makis
password: $2a$10$3GXzp3J5GhHThGisbpvpZuftbmzPivDMo94XPnkTnDe7254x7sJ3O
# encrypted of makis_pass
role: member
4. Register the middleware:
// Register to all matched routes
// under a Party and its children.
app.Use(auth)
// OR/and register to all http error routes.
app.UseError(auth)
// OR register under a path prefix of a specific Party,
// including all http errors of this path prefix.
app.UseRouter(auth)
// OR register to a specific Route before its main handler.
app.Post("/protected", auth, routeHandler)
5. Retrieve the username & password:
func routeHandler(ctx iris.Context) {
username, password, _ := ctx.Request().BasicAuth()
// [...]
}
5.1 Retrieve the User value (useful when you register a slice of custom user struct at Options.AllowUsers
):
func routeHandler(ctx iris.Context) {
user := ctx.User().(*iris.SimpleUser)
// user.Username
// user.Password
}
Read more authorization and authentication examples at _examples/auth.