コード例 #1
0
ファイル: context.go プロジェクト: yourchanges/go-swagger
// 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
	}

	for _, authenticator := range route.Authenticators {
		applies, usr, err := authenticator.Authenticate(request)
		if !applies || err != nil || usr == nil {
			continue
		}
		context.Set(request, ctxSecurityPrincipal, usr)
		return usr, nil
	}

	return nil, errors.Unauthenticated("invalid credentials")
}
コード例 #2
0
package security

import (
	"net/http"
	"testing"

	"github.com/casualjim/go-swagger/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) {
	ba := BasicAuth(basicAuthHandler)
コード例 #3
0
package security

import (
	"net/http"
	"testing"

	"github.com/casualjim/go-swagger/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)
	assert.NoError(t, err)