token

package
v1.5.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 29, 2020 License: MIT Imports: 13 Imported by: 1

Documentation

Index

Examples

Constants

View Source
const CachedStrategyKey = auth.StrategyKey("Token.Cached.Strategy")

CachedStrategyKey export identifier for the cached bearer strategy, commonly used when enable/add strategy to go-guardian authenticator.

View Source
const StatitcStrategyKey = auth.StrategyKey("Token.Static.Strategy")

StatitcStrategyKey export identifier for the static bearer strategy, commonly used when enable/add strategy to go-guardian authenticator.

Variables

View Source
var (
	// ErrInvalidToken indicate a hit of an invalid token format.
	// And it's returned by Token Parser.
	ErrInvalidToken = errors.New("strategies/token: Invalid token")
	// ErrTokenNotFound is returned by authenticating functions for token strategies,
	// when token not found in their store.
	ErrTokenNotFound = errors.New("strategies/token: Token does not exists")
)

Functions

func New

func New(auth AuthenticateFunc, c store.Cache, opts ...auth.Option) auth.Strategy

New return new auth.Strategy. The returned strategy, caches the invocation result of authenticate function, See AuthenticateFunc. Use NoOpAuthenticate to refresh/mangae token directly using cache or Append function, See NoOpAuthenticate.

Example
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

authFunc := AuthenticateFunc(func(ctx context.Context, r *http.Request, token string) (auth.Info, error) {
	fmt.Print("authFunc called ")
	if token == "90d64460d14870c08c81352a05dedd3465940a7" {
		return auth.NewDefaultUser("example", "1", nil, nil), nil
	}
	return nil, fmt.Errorf("Invalid user token")
})

cache := store.NewFIFO(ctx, time.Minute*5)
strategy := New(authFunc, cache)

r, _ := http.NewRequest("GET", "/", nil)
r.Header.Set("Authorization", "Bearer 90d64460d14870c08c81352a05dedd3465940a7")

// first request when authentication decision not cached
info, err := strategy.Authenticate(r.Context(), r)
fmt.Println(err, info.ID())

// second request where authentication decision cached and authFunc will not be called
info, err = strategy.Authenticate(r.Context(), r)
fmt.Println(err, info.ID())
Output:

authFunc called <nil> 1
<nil> 1
Example (Apikey)
r, _ := http.NewRequest("GET", "/something?api_key=token", nil)
parser := QueryParser("api_key")
opt := SetParser(parser)

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

authFunc := AuthenticateFunc(func(ctx context.Context, r *http.Request, token string) (auth.Info, error) {
	if token == "token" {
		return auth.NewDefaultUser("example", "1", nil, nil), nil
	}
	return nil, fmt.Errorf("Invalid user token")
})

cache := store.NewFIFO(ctx, time.Minute*5)
strategy := New(authFunc, cache, opt)

info, err := strategy.Authenticate(r.Context(), r)
fmt.Println(info.UserName(), err)
Output:

example <nil>

func NewStatic

func NewStatic(tokens map[string]auth.Info, opts ...auth.Option) auth.Strategy

NewStatic returns static auth.Strategy, populated from a map.

Example
strategy := NewStatic(map[string]auth.Info{
	"90d64460d14870c08c81352a05dedd3465940a7": auth.NewDefaultUser("example", "1", nil, nil),
})
r, _ := http.NewRequest("GET", "/", nil)
r.Header.Set("Authorization", "Bearer 90d64460d14870c08c81352a05dedd3465940a7")
info, err := strategy.Authenticate(r.Context(), r)
fmt.Println(err, info.ID())
Output:

<nil> 1
Example (Apikey)
r, _ := http.NewRequest("GET", "/something?api_key=token", nil)
parser := QueryParser("api_key")
opt := SetParser(parser)
tokens := map[string]auth.Info{
	"token": auth.NewDefaultUser("example", "1", nil, nil),
}
strategy := NewStatic(tokens, opt)
info, err := strategy.Authenticate(r.Context(), r)
fmt.Println(info.UserName(), err)
Output:

example <nil>

func NewStaticFromFile

func NewStaticFromFile(path string, opts ...auth.Option) (auth.Strategy, error)

NewStaticFromFile returns static auth.Strategy, populated from a CSV file. The CSV file must contain records in one of following formats basic record: `token,username,userid` intermediate record: `token,username,userid,"group1,group2"` full record: `token,username,userid,"group1,group2","extension=1,example=2"`

Example
strategy, _ := NewStaticFromFile("testdata/valid.csv")
r, _ := http.NewRequest("GET", "/", nil)
r.Header.Set("Authorization", "Bearer testUserToken")
info, err := strategy.Authenticate(r.Context(), r)
fmt.Println(err, info.ID())
Output:

<nil> 1

func NoOpAuthenticate

func NoOpAuthenticate(ctx context.Context, r *http.Request, token string) (auth.Info, error)

NoOpAuthenticate implements Authenticate function, it return nil, auth.ErrNOOP, commonly used when token refreshed/mangaed directly using cache or Append function, and there is no need to parse token and authenticate request.

Example
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

cache := store.NewFIFO(ctx, time.Microsecond*500)
strategy := New(NoOpAuthenticate, cache)

// demonstrate a user attempt to login
r, _ := http.NewRequest("GET", "/login", nil)
// user verified and add the user token to strategy using append or cache
cache.Store("token", auth.NewDefaultUser("example", "1", nil, nil), r)

// first request where authentication decision added to cached
r, _ = http.NewRequest("GET", "/login", nil)
r.Header.Set("Authorization", "Bearer token")
info, err := strategy.Authenticate(r.Context(), r)
fmt.Println(err, info.ID())

// second request where authentication decision expired and user must login again
time.Sleep(time.Second)
info, err = strategy.Authenticate(r.Context(), r)
fmt.Println(err, info)
Output:

<nil> 1
NOOP <nil>

func SetParser

func SetParser(p Parser) auth.Option

SetParser sets the strategy token parser.

func SetType

func SetType(t Type) auth.Option

SetType sets the authentication token type or scheme, used for HTTP WWW-Authenticate header.

Types

type AuthenticateFunc

type AuthenticateFunc func(ctx context.Context, r *http.Request, token string) (auth.Info, error)

AuthenticateFunc declare custom function to authenticate request using token. The authenticate function invoked by Authenticate Strategy method when The token does not exist in the cahce and the invocation result will be cached, unless an error returned. Use NoOpAuthenticate instead to refresh/mangae token directly using cache or Append function.

type Parser

type Parser interface {
	Token(r *http.Request) (string, error)
}

Parser parse and extract token from incoming HTTP request.

func AuthorizationParser

func AuthorizationParser(key string) Parser

AuthorizationParser return a token parser, where token extracted form Authorization header.

Example
r, _ := http.NewRequest("GET", "/", nil)
r.Header.Set("Authorization", "Bearer token")
parser := AuthorizationParser("Bearer")
token, err := parser.Token(r)
fmt.Println(token, err)
Output:

token <nil>

func CookieParser

func CookieParser(key string) Parser

CookieParser return a token parser, where token extracted form HTTP Cookie.

Example
name := "api_key"
r, _ := http.NewRequest("GET", "/", nil)
cookie := &http.Cookie{Name: name, Value: "token"}
r.AddCookie(cookie)
parser := CookieParser(name)
token, err := parser.Token(r)
fmt.Println(token, err)
Output:

token <nil>

func QueryParser

func QueryParser(key string) Parser

QueryParser return a token parser, where token extracted form HTTP query string.

Example
r, _ := http.NewRequest("GET", "/something?api_key=token", nil)
parser := QueryParser("api_key")
token, err := parser.Token(r)
fmt.Println(token, err)
Output:

token <nil>

func XHeaderParser

func XHeaderParser(header string) Parser

XHeaderParser return a token parser, where token extracted form "X-" header.

Example
header := "X-API-TOKE"
r, _ := http.NewRequest("GET", "/", nil)
r.Header.Set(header, "token")
parser := XHeaderParser(header)
token, err := parser.Token(r)
fmt.Println(token, err)
Output:

token <nil>

type Static

type Static struct {
	MU     *sync.Mutex
	Tokens map[string]auth.Info
	Type   Type
	Parser Parser
}

Static implements auth.Strategy and define a synchronized map honor all predefined bearer tokens.

func (*Static) Append

func (s *Static) Append(token string, info auth.Info, _ *http.Request) error

Append add new token to static store.

func (*Static) Authenticate

func (s *Static) Authenticate(ctx context.Context, r *http.Request) (auth.Info, error)

Authenticate user request against predefined tokens by verifying request token existence in the static Map. Once token found auth.Info returned with a nil error, Otherwise, a nil auth.Info and ErrTokenNotFound returned.

func (*Static) Challenge

func (s *Static) Challenge(realm string) string

Challenge returns string indicates the authentication scheme. Typically used to adds a HTTP WWW-Authenticate header.

func (*Static) Revoke

func (s *Static) Revoke(token string, _ *http.Request) error

Revoke delete token from static store.

type Type

type Type string

Type is Authentication token type or scheme. A common type is Bearer.

const (
	// Bearer Authentication token type or scheme.
	Bearer Type = "Bearer"
	// APIKey Authentication token type or scheme.
	APIKey Type = "ApiKey"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL