Documentation ¶
Overview ¶
Package bearer provides authentication strategy, to authenticate HTTP requests based on the bearer token.
Index ¶
- Constants
- Variables
- func New(auth AuthenticateFunc, c store.Cache) auth.Strategy
- func NewStatic(tokens map[string]auth.Info) auth.Strategy
- func NewStaticFromFile(path string) (auth.Strategy, error)
- func NoOpAuthenticate(ctx context.Context, r *http.Request, token string) (auth.Info, error)
- func Token(r *http.Request) (string, error)
- type AuthenticateFunc
- type Static
Examples ¶
Constants ¶
const CachedStrategyKey = auth.StrategyKey("Bearer.Cached.Strategy")
CachedStrategyKey export identifier for the cached bearer strategy, commonly used when enable/add strategy to go-guardian authenticator.
const StatitcStrategyKey = auth.StrategyKey("Bearer.Static.Strategy")
StatitcStrategyKey export identifier for the static bearer strategy, commonly used when enable/add strategy to go-guardian authenticator.
Variables ¶
var ( // ErrInvalidToken indicate a hit of an invalid bearer token format. // And it's returned by Token function. ErrInvalidToken = errors.New("bearer: Invalid bearer token") // ErrTokenNotFound is returned by authenticating functions for bearer strategies, // when token not found in their store. ErrTokenNotFound = errors.New("barer: Token does not exists") )
Functions ¶
func New ¶ added in v1.0.0
func New(auth AuthenticateFunc, c store.Cache) auth.Strategy
New return new auth.Strategy. The returned strategy, caches the invocation result of authenticate function, See Authenticate. 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
func NewStatic ¶
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
func NewStaticFromFile ¶
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 ¶
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 Token ¶
Token return bearer token from Authorization header, or ErrInvalidToken, The returned token will not contain "Bearer" keyword
Example ¶
r, _ := http.NewRequest("GET", "/logout", nil) r.Header.Set("Authorization", "Bearer 90d64460d14870c08c81352a05dedd3465940a7") token, err := Token(r) fmt.Println(err, token) r.Header.Set("Authorization", "90d64460d14870c08c81352a05dedd3465940a7") token, err = Token(r) fmt.Println(err, token)
Output: <nil> 90d64460d14870c08c81352a05dedd3465940a7 bearer: Invalid bearer token
Types ¶
type AuthenticateFunc ¶ added in v1.0.0
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 Static ¶
Static implements auth.Strategy and define a synchronized map honor all predefined bearer tokens.
func (*Static) Authenticate ¶
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.