BasicAuth
Basic Authentication middleware for Fiber that provides an HTTP basic authentication. It calls the next handler for valid credentials and 401 Unauthorized or a custom response for missing or invalid credentials.

Table of Contents

Signatures

1
func New(config Config) fiber.Handler
Copied!

Examples

Import the middleware package that is part of the Fiber web framework
1
import (
2
"github.com/gofiber/fiber/v2"
3
"github.com/gofiber/fiber/v2/middleware/basicauth"
4
)
Copied!
After you initiate your Fiber app, you can use the following possibilities:
1
// Provide a minimal config
2
app.Use(basicauth.New(basicauth.Config{
3
Users: map[string]string{
4
"john": "doe",
5
"admin": "123456",
6
},
7
}))
8
​
9
// Or extend your config for customization
10
app.Use(basicauth.New(basicauth.Config{
11
Users: map[string]string{
12
"john": "doe",
13
"admin": "123456",
14
},
15
Realm: "Forbidden",
16
Authorizer: func(user, pass string) bool {
17
if user == "john" && pass == "doe" {
18
return true
19
}
20
if user == "admin" && pass == "123456" {
21
return true
22
}
23
return false
24
},
25
Unauthorized: func(c *fiber.Ctx) error {
26
return c.SendFile("./unauthorized.html")
27
},
28
ContextUsername: "_user",
29
ContextPassword: "_pass",
30
}))
Copied!

Config

1
// Config defines the config for middleware.
2
type Config struct {
3
// Next defines a function to skip this middleware when returned true.
4
//
5
// Optional. Default: nil
6
Next func(c *fiber.Ctx) bool
7
​
8
// Users defines the allowed credentials
9
//
10
// Required. Default: map[string]string{}
11
Users map[string]string
12
​
13
// Realm is a string to define realm attribute of BasicAuth.
14
// the realm identifies the system to authenticate against
15
// and can be used by clients to save credentials
16
//
17
// Optional. Default: "Restricted".
18
Realm string
19
​
20
// Authorizer defines a function you can pass
21
// to check the credentials however you want.
22
// It will be called with a username and password
23
// and is expected to return true or false to indicate
24
// that the credentials were approved or not.
25
//
26
// Optional. Default: nil.
27
Authorizer func(string, string) bool
28
​
29
// Unauthorized defines the response body for unauthorized responses.
30
// By default it will return with a 401 Unauthorized and the correct WWW-Auth header
31
//
32
// Optional. Default: nil
33
Unauthorized fiber.Handler
34
​
35
// ContextUser is the key to store the username in Locals
36
//
37
// Optional. Default: "username"
38
ContextUsername string
39
​
40
// ContextPass is the key to store the password in Locals
41
//
42
// Optional. Default: "password"
43
ContextPassword string
44
}
Copied!

Default Config

1
var ConfigDefault = Config{
2
Next: nil,
3
Users: map[string]string{},
4
Realm: "Restricted",
5
Authorizer: nil,
6
Unauthorized: nil,
7
ContextUsername: "username",
8
ContextPassword: "password",
9
}
Copied!
Last modified 7mo ago