Skip to content

Commit

Permalink
adds some convenience methods to allow configuring a realm for basic …
Browse files Browse the repository at this point in the history
…auth

Signed-off-by: Ivan Porto Carrero <[email protected]>
  • Loading branch information
casualjim committed Mar 3, 2019
1 parent 3109248 commit d68539e
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions security/authenticator.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,19 @@ func FailedBasicAuthCtx(ctx context.Context) string {

// BasicAuth creates a basic auth authenticator with the provided authentication function
func BasicAuth(authenticate UserPassAuthentication) runtime.Authenticator {
return BasicAuthRealm(DefaultRealmName, authenticate)
}

// BasicAuthBasicAuthRealm creates a basic auth authenticator with the provided authentication function and realm name
func BasicAuthRealm(realm string, authenticate UserPassAuthentication) runtime.Authenticator {
return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
if usr, pass, ok := r.BasicAuth(); ok {
p, err := authenticate(usr, pass)
if err != nil {
*r = *r.WithContext(context.WithValue(r.Context(), failedBasicAuth, DefaultRealmName))
if realm == "" {
realm = DefaultRealmName
}
*r = *r.WithContext(context.WithValue(r.Context(), failedBasicAuth, realm))
}
return true, p, err
}
Expand All @@ -106,11 +114,20 @@ func BasicAuth(authenticate UserPassAuthentication) runtime.Authenticator {

// BasicAuthCtx creates a basic auth authenticator with the provided authentication function with support for context.Context
func BasicAuthCtx(authenticate UserPassAuthenticationCtx) runtime.Authenticator {
return BasicAuthRealmCtx(DefaultRealmName, authenticate)
}

// BasicAuthCtx creates a basic auth authenticator with the provided authentication function and realm name with support for context.Context
func BasicAuthRealmCtx(realm string, authenticate UserPassAuthenticationCtx) runtime.Authenticator {
if realm == "" {
realm = DefaultRealmName
}

return HttpAuthenticator(func(r *http.Request) (bool, interface{}, error) {
if usr, pass, ok := r.BasicAuth(); ok {
ctx, p, err := authenticate(r.Context(), usr, pass)
if err != nil {
ctx = context.WithValue(ctx, failedBasicAuth, DefaultRealmName)
ctx = context.WithValue(ctx, failedBasicAuth, realm)
}
*r = *r.WithContext(ctx)
return true, p, err
Expand Down

0 comments on commit d68539e

Please sign in to comment.