Skip to content

Commit d68539e

Browse files
committed
adds some convenience methods to allow configuring a realm for basic auth
Signed-off-by: Ivan Porto Carrero <ivan@flanders.co.nz>
1 parent 3109248 commit d68539e

1 file changed

Lines changed: 19 additions & 2 deletions

File tree

security/authenticator.go

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,11 +91,19 @@ func FailedBasicAuthCtx(ctx context.Context) string {
9191

9292
// BasicAuth creates a basic auth authenticator with the provided authentication function
9393
func BasicAuth(authenticate UserPassAuthentication) runtime.Authenticator {
94+
return BasicAuthRealm(DefaultRealmName, authenticate)
95+
}
96+
97+
// BasicAuthBasicAuthRealm creates a basic auth authenticator with the provided authentication function and realm name
98+
func BasicAuthRealm(realm string, authenticate UserPassAuthentication) runtime.Authenticator {
9499
return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
95100
if usr, pass, ok := r.BasicAuth(); ok {
96101
p, err := authenticate(usr, pass)
97102
if err != nil {
98-
*r = *r.WithContext(context.WithValue(r.Context(), failedBasicAuth, DefaultRealmName))
103+
if realm == "" {
104+
realm = DefaultRealmName
105+
}
106+
*r = *r.WithContext(context.WithValue(r.Context(), failedBasicAuth, realm))
99107
}
100108
return true, p, err
101109
}
@@ -106,11 +114,20 @@ func BasicAuth(authenticate UserPassAuthentication) runtime.Authenticator {
106114

107115
// BasicAuthCtx creates a basic auth authenticator with the provided authentication function with support for context.Context
108116
func BasicAuthCtx(authenticate UserPassAuthenticationCtx) runtime.Authenticator {
117+
return BasicAuthRealmCtx(DefaultRealmName, authenticate)
118+
}
119+
120+
// BasicAuthCtx creates a basic auth authenticator with the provided authentication function and realm name with support for context.Context
121+
func BasicAuthRealmCtx(realm string, authenticate UserPassAuthenticationCtx) runtime.Authenticator {
122+
if realm == "" {
123+
realm = DefaultRealmName
124+
}
125+
109126
return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
110127
if usr, pass, ok := r.BasicAuth(); ok {
111128
ctx, p, err := authenticate(r.Context(), usr, pass)
112129
if err != nil {
113-
ctx = context.WithValue(ctx, failedBasicAuth, DefaultRealmName)
130+
ctx = context.WithValue(ctx, failedBasicAuth, realm)
114131
}
115132
*r = *r.WithContext(ctx)
116133
return true, p, err

0 commit comments

Comments
 (0)