token

package
v0.0.0-...-5ddb3d2 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2022 License: GPL-3.0 Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// RTCode signals the token response type is 'code'
	RTCode ResponseType = "code"
	// RTToken signals the token response type is 'token'
	RTToken ResponseType = "token"

	// AccessTokenTTL is the lifespan of an access token
	AccessTokenTTL = time.Hour * 2
	// RefreshTokenTTL is the lifespan of a refresh token
	RefreshTokenTTL = time.Hour * 24 * 30
	// AccessCodeTTL is the lifespan of an access code
	AccessCodeTTL = time.Minute * 2
)

Variables

View Source
var (
	// Timestamp is a replacable function for getting the current time,
	// can be overridden for tests
	Timestamp = func() time.Time { return time.Now() }
	// ErrTokenNotFound is returned by stores that cannot find an access token
	// for a given key
	ErrTokenNotFound = errors.New("access token not found")
	// ErrInvalidToken indicates an access token is invalid
	ErrInvalidToken = errors.New("invalid access token")
	// DefaultTokenTTL is the default
	DefaultTokenTTL = time.Hour * 24 * 14
)
View Source
var (
	// ErrInvalidRequest is returned on any parse or void output error
	ErrInvalidRequest = fmt.Errorf("invalid request")
	// ErrInvalidCredentials signals a bad username/password/key error
	ErrInvalidCredentials = fmt.Errorf("invalid user credentials")
	// ErrNotFound is returned when no matching results exist for the provided credentials
	ErrNotFound = fmt.Errorf("user not found")
	// ErrServerError is returned on unexpected errors
	ErrServerError = fmt.Errorf("server error")
	// ErrInvalidAuthorizeCode is returned on parsing an invalid authorization code
	ErrInvalidAuthorizeCode = fmt.Errorf("invalid authorize code")
	// ErrInvalidAccessToken is returned on parsing an invalid access token
	ErrInvalidAccessToken = fmt.Errorf("invalid access token")
	// ErrCodeExpired is returned for expired authorization codes
	ErrCodeExpired = fmt.Errorf("code expired")
	// ErrTokenExpired is returned for expired tokens
	ErrTokenExpired = fmt.Errorf("token expired")
	// ErrInvalidRefreshToken is returned on parsing invalid refresh tokens
	ErrInvalidRefreshToken = fmt.Errorf("invalid refresh token")
)

Functions

func AddContextTokenToRequest

func AddContextTokenToRequest(ctx context.Context, r *http.Request) (*http.Request, bool)

AddContextTokenToRequest checks the supplied context for an auth token and adds it to an http request, returns true if a token is added

func AddToContext

func AddToContext(ctx context.Context, s string) context.Context

AddToContext adds a token string to a context

func FromCtx

func FromCtx(ctx context.Context) string

FromCtx extracts the JWT from a given context if one is set, returning nil otherwise

func NewPrivKeyAuthToken

func NewPrivKeyAuthToken(pk crypto.PrivKey, profileID string, ttl time.Duration) (string, error)

NewPrivKeyAuthToken creates a JWT token string suitable for making requests authenticated as the given private key

func OAuthTokenMiddleware

func OAuthTokenMiddleware(next http.Handler) http.Handler

OAuthTokenMiddleware parses any "authorization" header containing a Bearer token & adds it to the request context

Types

type Claims

type Claims struct {
	*jwt.StandardClaims
	ClientType ClientType `json:"clientType"`
}

Claims is a JWT Claims object

type ClientType

type ClientType string

ClientType is used to enumerate the user types to distingish them later from the token

const (
	// UserClient represents a human user that's authenticated with his own credentials
	UserClient ClientType = "user"
	// NodeClient represents a machine client that's authenticated with api client credentials
	NodeClient ClientType = "node"
)

func (ClientType) String

func (ct ClientType) String() string

type CtxKey

type CtxKey string

CtxKey defines a distinct type for context keys used by the access package

type GrantType

type GrantType string

GrantType authorization model

const (
	AuthorizationCode   GrantType = "authorization_code"
	PasswordCredentials GrantType = "password"
	ClientCredentials   GrantType = "client_credentials"
	Refreshing          GrantType = "refresh_token"
	Implicit            GrantType = "__implicit"
)

define authorization model

func (GrantType) String

func (gt GrantType) String() string

type LocalProvider

type LocalProvider struct {
	// contains filtered or unexported fields
}

LocalProvider implements the Provider interface and provides mechanics for generating tokens for a selected profile

func NewProvider

func NewProvider(p profile.Store, k key.Store) (*LocalProvider, error)

NewProvider instantiates a new LocalProvider

func (*LocalProvider) Token

func (p *LocalProvider) Token(ctx context.Context, req *Request) (*Response, error)

Token handles the OAuth token flow

type Provider

type Provider interface {
	// Token handles the auth token flow
	Token(ctx context.Context, req *Request) (*Response, error)
}

Provider is a service that generates access & refresh tokens

type RawToken

type RawToken struct {
	Key string
	Raw string
}

RawToken is a struct that binds a key to a raw token string

type RawTokens

type RawTokens []RawToken

RawTokens is a list of tokens that implements sorting by keys

func (RawTokens) Len

func (rts RawTokens) Len() int

func (RawTokens) Less

func (rts RawTokens) Less(a, b int) bool

func (RawTokens) Swap

func (rts RawTokens) Swap(i, j int)

type Request

type Request struct {
	GrantType    GrantType `json:"grant_type"`
	Code         string    `json:"code"`
	Username     string    `json:"username"`
	Password     string    `json:"password"`
	RefreshToken string    `json:"refresh_token"`
	RedirectURI  string    `json:"redirect_uri"`
}

Request is a wrapper for incoming token requests

type Response

type Response struct {
	AccessToken  string `json:"access_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int64  `json:"expires_in"`
	RefreshToken string `json:"refresh_token,omitempty"`
}

Response wraps the token response object

type ResponseType

type ResponseType string

ResponseType the type of authorization request

func (ResponseType) String

func (rt ResponseType) String() string

type Source

type Source interface {
	CreateToken(pro *profile.Profile, ttl time.Duration) (string, error)
	CreateTokenWithClaims(claims *Claims, ttl time.Duration) (string, error)
	// VerifyKey returns the verification key for a given token
	VerificationKey(t *Token) (interface{}, error)
}

Source creates tokens, and provides a verification key for all tokens it creates

implementations of Source must conform to the assertion test defined in the spec subpackage

func NewPrivKeySource

func NewPrivKeySource(privKey crypto.PrivKey) (Source, error)

NewPrivKeySource creates an authentication interface backed by a single private key. Intended for a node running as remote, or providing a public API

type Store

type Store interface {
	PutToken(ctx context.Context, key, rawToken string) error
	RawToken(ctx context.Context, key string) (rawToken string, err error)
	DeleteToken(ctx context.Context, key string) (err error)
	ListTokens(ctx context.Context, offset, limit int) (results []RawToken, err error)
}

Store is a store intended for clients, who need to persist secret jwts given to them by other remotes for API access. It deals in raw, string-formatted json web tokens, which are more useful when working with APIs, but validates the tokens are well-formed when placed in the store

implementations of Store must conform to the assertion test defined in the spec subpackage

func NewStore

func NewStore(filepath string, fs qfs.Filesystem) (Store, error)

NewStore creates a token store with a qfs.Filesystem

type Token

type Token = jwt.Token

Token abstracts a json web token

func Parse

func Parse(tokenString string, tokens Source) (*Token, error)

Parse will parse, validate and return a token

func ParseAuthToken

func ParseAuthToken(ctx context.Context, tokenString string, keystore key.Store) (*Token, error)

ParseAuthToken will parse, validate and return a token

func ParseWithClaims

func ParseWithClaims(tokenString string, claims *Claims, tokens Source) (*Token, error)

ParseWithClaims will parse, validate and return a token with claims

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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