mirror of
https://github.com/labstack/echo.git
synced 2025-07-05 00:58:47 +02:00
Add BasicAuth Realm support
This commit is contained in:
@ -2,6 +2,7 @@ package middleware
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
"github.com/labstack/echo"
|
"github.com/labstack/echo"
|
||||||
)
|
)
|
||||||
@ -15,6 +16,9 @@ type (
|
|||||||
// Validator is a function to validate BasicAuth credentials.
|
// Validator is a function to validate BasicAuth credentials.
|
||||||
// Required.
|
// Required.
|
||||||
Validator BasicAuthValidator
|
Validator BasicAuthValidator
|
||||||
|
|
||||||
|
// Realm is a string to define realm attribute of BasicAuth
|
||||||
|
Realm string
|
||||||
}
|
}
|
||||||
|
|
||||||
// BasicAuthValidator defines a function to validate BasicAuth credentials.
|
// BasicAuthValidator defines a function to validate BasicAuth credentials.
|
||||||
@ -22,13 +26,15 @@ type (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
basic = "Basic"
|
basic = "Basic"
|
||||||
|
defaultRealm = "Restricted"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// DefaultBasicAuthConfig is the default BasicAuth middleware config.
|
// DefaultBasicAuthConfig is the default BasicAuth middleware config.
|
||||||
DefaultBasicAuthConfig = BasicAuthConfig{
|
DefaultBasicAuthConfig = BasicAuthConfig{
|
||||||
Skipper: DefaultSkipper,
|
Skipper: DefaultSkipper,
|
||||||
|
Realm: defaultRealm,
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -52,6 +58,9 @@ func BasicAuthWithConfig(config BasicAuthConfig) echo.MiddlewareFunc {
|
|||||||
if config.Skipper == nil {
|
if config.Skipper == nil {
|
||||||
config.Skipper = DefaultBasicAuthConfig.Skipper
|
config.Skipper = DefaultBasicAuthConfig.Skipper
|
||||||
}
|
}
|
||||||
|
if config.Realm == "" {
|
||||||
|
config.Realm = defaultRealm
|
||||||
|
}
|
||||||
|
|
||||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||||
return func(c echo.Context) error {
|
return func(c echo.Context) error {
|
||||||
@ -78,8 +87,15 @@ func BasicAuthWithConfig(config BasicAuthConfig) echo.MiddlewareFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var realm string
|
||||||
|
if config.Realm == defaultRealm {
|
||||||
|
realm = defaultRealm
|
||||||
|
} else {
|
||||||
|
realm = strconv.Quote(config.Realm)
|
||||||
|
}
|
||||||
|
|
||||||
// Need to return `401` for browsers to pop-up login box.
|
// Need to return `401` for browsers to pop-up login box.
|
||||||
c.Response().Header().Set(echo.HeaderWWWAuthenticate, basic+" realm=Restricted")
|
c.Response().Header().Set(echo.HeaderWWWAuthenticate, basic+" realm="+realm)
|
||||||
return echo.ErrUnauthorized
|
return echo.ErrUnauthorized
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user