Skip to content

Commit d28ea93

Browse files
author
nshmura
committed
Add BasicAuth Realm support
1 parent 70be2c2 commit d28ea93

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

middleware/basic_auth.go

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package middleware
22

33
import (
44
"encoding/base64"
5+
"strconv"
56

67
"github.com/labstack/echo"
78
)
@@ -15,20 +16,25 @@ type (
1516
// Validator is a function to validate BasicAuth credentials.
1617
// Required.
1718
Validator BasicAuthValidator
19+
20+
// Realm is a string to define realm attribute of BasicAuth
21+
Realm string
1822
}
1923

2024
// BasicAuthValidator defines a function to validate BasicAuth credentials.
2125
BasicAuthValidator func(string, string, echo.Context) bool
2226
)
2327

2428
const (
25-
basic = "Basic"
29+
basic = "Basic"
30+
defaultRealm = "Restricted"
2631
)
2732

2833
var (
2934
// DefaultBasicAuthConfig is the default BasicAuth middleware config.
3035
DefaultBasicAuthConfig = BasicAuthConfig{
3136
Skipper: DefaultSkipper,
37+
Realm: defaultRealm,
3238
}
3339
)
3440

@@ -52,6 +58,9 @@ func BasicAuthWithConfig(config BasicAuthConfig) echo.MiddlewareFunc {
5258
if config.Skipper == nil {
5359
config.Skipper = DefaultBasicAuthConfig.Skipper
5460
}
61+
if config.Realm == "" {
62+
config.Realm = defaultRealm
63+
}
5564

5665
return func(next echo.HandlerFunc) echo.HandlerFunc {
5766
return func(c echo.Context) error {
@@ -78,8 +87,15 @@ func BasicAuthWithConfig(config BasicAuthConfig) echo.MiddlewareFunc {
7887
}
7988
}
8089

90+
var realm string
91+
if config.Realm == defaultRealm {
92+
realm = defaultRealm
93+
} else {
94+
realm = strconv.Quote(config.Realm)
95+
}
96+
8197
// Need to return `401` for browsers to pop-up login box.
82-
c.Response().Header().Set(echo.HeaderWWWAuthenticate, basic+" realm=Restricted")
98+
c.Response().Header().Set(echo.HeaderWWWAuthenticate, basic+" realm="+realm)
8399
return echo.ErrUnauthorized
84100
}
85101
}

0 commit comments

Comments
 (0)