The Basic Authentication middleware with the Iris framework, so you do not need to install it separately.
1. Import the middleware
2. Configure the middleware with its struct:
opts := basicauth.Options{
Allow: basicauth.AllowUsers(map[string]string{
"username": "password",
}),
Realm: "Authorization Required",
ErrorHandler: basicauth.DefaultErrorHandler,
// [...more options]
}
auth := basicauth.New(opts)
3.1 The above steps are the same as the Default
function:
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)
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
// 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) {
user := ctx.User().(*iris.SimpleUser)
// user.Username
Read more authorization and authentication examples at .