// Authorize authorizes the request func (c *Context) Authorize(request *http.Request, route *MatchedRoute) (interface{}, error) { if len(route.Authenticators) == 0 { return nil, nil } if v, ok := context.GetOk(request, ctxSecurityPrincipal); ok { return v, nil } var lastError error for scheme, authenticator := range route.Authenticators { applies, usr, err := authenticator.Authenticate(&security.ScopedAuthRequest{ Request: request, RequiredScopes: route.Scopes[scheme], }) if !applies || err != nil || usr == nil { if err != nil { lastError = err } continue } context.Set(request, ctxSecurityPrincipal, usr) context.Set(request, ctxSecurityScopes, route.Scopes[scheme]) return usr, nil } if lastError != nil { return nil, lastError } return nil, errors.Unauthenticated("invalid credentials") }
"bytes" "mime/multipart" "net/http" "net/url" "strings" "testing" "github.com/go-openapi/errors" "github.com/stretchr/testify/assert" ) var bearerAuth = ScopedTokenAuthentication(func(token string, requiredScopes []string) (interface{}, error) { if token == "token123" { return "admin", nil } return nil, errors.Unauthenticated("bearer") }) func TestValidBearerAuth(t *testing.T) { ba := BearerAuth("owners_auth", bearerAuth) req1, _ := http.NewRequest("GET", "/blah?access_token=token123", nil) ok, usr, err := ba.Authenticate(&ScopedAuthRequest{Request: req1}) assert.True(t, ok) assert.Equal(t, "admin", usr) assert.NoError(t, err) req2, _ := http.NewRequest("GET", "/blah", nil) req2.Header.Set("Authorization", "Bearer token123")
package security import ( "net/http" "testing" "github.com/go-openapi/errors" "github.com/stretchr/testify/assert" ) var tokenAuth = TokenAuthentication(func(token string) (interface{}, error) { if token == "token123" { return "admin", nil } return nil, errors.Unauthenticated("token") }) func TestInvalidApiKeyAuthInitialization(t *testing.T) { assert.Panics(t, func() { APIKeyAuth("api_key", "qery", tokenAuth) }) } func TestValidApiKeyAuth(t *testing.T) { ta := APIKeyAuth("api_key", "query", tokenAuth) ta2 := APIKeyAuth("X-API-KEY", "header", tokenAuth) req1, _ := http.NewRequest("GET", "/blah?api_key=token123", nil) ok, usr, err := ta.Authenticate(req1) assert.True(t, ok) assert.Equal(t, "admin", usr)
package security import ( "net/http" "testing" "github.com/go-openapi/errors" "github.com/stretchr/testify/assert" ) var basicAuthHandler = UserPassAuthentication(func(user, pass string) (interface{}, error) { if user == "admin" && pass == "123456" { return "admin", nil } return "", errors.Unauthenticated("basic") }) func TestValidBasicAuth(t *testing.T) { ba := BasicAuth(basicAuthHandler) req, _ := http.NewRequest("GET", "/blah", nil) req.SetBasicAuth("admin", "123456") ok, usr, err := ba.Authenticate(req) assert.NoError(t, err) assert.True(t, ok) assert.Equal(t, "admin", usr) } func TestInvalidBasicAuth(t *testing.T) {