authn

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2023 License: GPL-3.0 Imports: 13 Imported by: 0

Documentation

Overview

Package authn implements authentication (in contrast to authorization) for DEXPRO services.

While most types should be reusable and oriented towards standardization, there are opinionated implementations that are required to implement the DEXPRO architecture.

Index

Constants

View Source
const (
	CtxKeyToken    = "dexp-serviceframework-access-token"
	CtxKeyTokenStr = "dexp-serviceframework-access-token-str"
)

Variables

View Source
var (
	ErrAuthTokenMissing = errors.New("auth token missing")
)

Functions

func AccessTokenCookieName

func AccessTokenCookieName(prefix string) string

AccessTokenCookieName returns a standard cookie name to be used for cookies carrying access tokens.

func GetAccessTokenCookie

func GetAccessTokenCookie(request *http.Request, prefix string) (*http.Cookie, error)

GetAccessTokenCookie retrieves the access token cookie from the request.

func GetCtxAccessToken deprecated

func GetCtxAccessToken(ctx context.Context) interface{}

Deprecated: GetCtxAccessToken is deprecated because it uses weakly typed parameters. Use GetCtxJwt instead.

func GetCtxAccessTokenStr deprecated

func GetCtxAccessTokenStr(ctx context.Context) string

Deprecated: GetCtxAccessTokenStr is deprecated because it uses weakly typed parameters. Use GetCtxJwt instead.

func MockJwtMiddleware

func MockJwtMiddleware() gin.HandlerFunc

MockJwtMiddleware returns a middleware which adds a mocked Jwt to the request's context. You should only use this during development or during debugging if you can't / won't setup proper authentication via Keycloak / similar.

func NewKeycloakKeyfunc

func NewKeycloakKeyfunc(trustedIssuerBaseUrl string, jwksManager *JwksManager) jwt.Keyfunc

NewKeycloakKeyfunc returns a keyfunc that fetches JWKS instances from a single trusted Keycloak server.

Callers of this func have to supply a JwksManager which is responsible for fetching and caching the public keys used for token signature validation.

The returned keyfunc inspects the tokens "iss" (issuer) claim to determine what key set to use.

func RequireExpAndIssuedAtClaims

func RequireExpAndIssuedAtClaims(claims jwt.RegisteredClaims) error

RequireExpAndIssuedAtClaims checks that the given claims contain exp and iat claims.

You may want to use this because jwt.RegisteredClaims.Valid() does not check for the existence of these claims.

func SetCtxAccessToken deprecated

func SetCtxAccessToken(ctx context.Context, token interface{}) context.Context

Deprecated: SetCtxAccessToken is deprecated because it uses weakly typed parameters. Use SetCtxJwtGin instead.

func SetCtxAccessTokenStr deprecated

func SetCtxAccessTokenStr(ctx context.Context, token string) context.Context

Deprecated: SetCtxAccessTokenStr is deprecated because it uses weakly typed parameters. Use SetCtxJwtGin instead.

func SetCtxJwtGin

func SetCtxJwtGin(ctx *gin.Context, obj *Jwt)

SetCtxJwtGin sets the JWT object in the given gin context.

Types

type AuthStack

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

AuthStack is responsible for performing authentication in our APIs.

func NewDefaultAuthStack

func NewDefaultAuthStack(trustedIssuerBaseUrl string, cookieName string) *AuthStack

func (*AuthStack) ExtractRequestToken

func (d *AuthStack) ExtractRequestToken(request *http.Request) (string, error)

func (*AuthStack) ParseToken

func (d *AuthStack) ParseToken(tokenString string) (*jwt.Token, *Claims, error)

func (*AuthStack) ToMiddleware

func (d *AuthStack) ToMiddleware() *JwtMiddleware

func (*AuthStack) ValidateToken

func (d *AuthStack) ValidateToken(token *jwt.Token) (bool, error)

type Base64CookieEncoder

type Base64CookieEncoder struct {
}

Base64CookieEncoder is an encoder which encodes values via base64.

func NewBase64CookieEncoder

func NewBase64CookieEncoder() *Base64CookieEncoder

func (*Base64CookieEncoder) Decode

func (u *Base64CookieEncoder) Decode(val []byte) ([]byte, error)

func (*Base64CookieEncoder) DecodeCookie

func (u *Base64CookieEncoder) DecodeCookie(cookie *http.Cookie) error

func (*Base64CookieEncoder) Encode

func (u *Base64CookieEncoder) Encode(val []byte) []byte

func (*Base64CookieEncoder) EncodeCookie

func (u *Base64CookieEncoder) EncodeCookie(cookie *http.Cookie) error

type BearerHeaderTokenExtractor

type BearerHeaderTokenExtractor struct{}

BearerHeaderTokenExtractor extracts tokens from the Authorization header. It expects the token to be prefixed with "Bearer ".

func NewBearerHeaderTokenExtractor

func NewBearerHeaderTokenExtractor() *BearerHeaderTokenExtractor

func (*BearerHeaderTokenExtractor) ExtractRequestToken

func (d *BearerHeaderTokenExtractor) ExtractRequestToken(request *http.Request) (string, error)

type Claims

type Claims struct {
	jwt.RegisteredClaims

	Scope string `json:"scope,omitempty"`

	// TenantId
	//
	// This claim is set on tokens that are scoped to a tenant, ie a customer / organization consuming some service.
	TenantId   uuid.UUID `json:"tenant_id,omitempty"`
	TenantName string    `json:"tenant_name,omitempty"`

	Email string `json:"email,omitempty"`
	Name  string `json:"name,omitempty"`

	// ResourceAccess is set by Keycloak on default clients
	ResourceAccess map[string]map[string][]string `json:"resource_access,omitempty"`

	// RealmAccess is set by Keycloak on default clients
	RealmAccess map[string][]string `json:"realm_access,omitempty"`

	// ClientId is set by Keycloak on client using client credentials grant
	ClientId string `json:"clientId,omitempty"`
	// ClientHost is set by Keycloak on client using client credentials grant
	ClientHost string `json:"clientHost,omitempty"`
	// ClientAddress is set by Keycloak on client using client credentials grant
	ClientAddress string `json:"clientAddress,omitempty"`

	PreferredUsername string `json:"preferred_username,omitempty"`
}

Claims is a custom type that contains fields for all claims used by DEXPRO services.

func (*Claims) HasTenantId

func (claims *Claims) HasTenantId() bool

func (Claims) Valid

func (claims Claims) Valid() error

Valid is the method called by the jwt library when parsing and validating a token.

type CookieEncoder

type CookieEncoder interface {
	EncodeCookie(cookie *http.Cookie) error
	DecodeCookie(cookie *http.Cookie) error
	Encode(val []byte) []byte
	Decode(val []byte) ([]byte, error)
}

CookieEncoder is a helper interface for types that are able to encode / decode cookie values.

Usage of this type allows to use different encryption methods (or none) for cookies.

type JwksManager

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

JwksManager is responsible for caching JWKS instances, mapped by their URL. This is internally implemented based on the keyfunc.JWKS type.

This type is pretty stateful as it caches JWKS instances and creates background goroutines for each keyfunc.JWKS.

Remember to call JwksManager.Close before discarding any JwksManager.

func NewJwksManager

func NewJwksManager() *JwksManager

func (*JwksManager) Close

func (m *JwksManager) Close()

func (*JwksManager) GetKeyfuncForJwksURL

func (m *JwksManager) GetKeyfuncForJwksURL(url string) (jwt.Keyfunc, error)

type Jwt

type Jwt struct {
	TokenStr string
	Token    *jwt.Token
	Claims   *Claims
}

Jwt is a wrapper around a parsed JWT token and its claims.

func GetCtxJwt

func GetCtxJwt(ctx context.Context) *Jwt

GetCtxJwt returns the JWT object from the given context. Returns nil if no value is found.

type JwtCookieExtractor

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

JwtCookieExtractor extracts tokens from a cookie.

func NewJwtCookieExtractor

func NewJwtCookieExtractor(cookieName string, encoder CookieEncoder) *JwtCookieExtractor

NewJwtCookieExtractor creates a new JwtCookieExtractor.

If encoder is nil, the cookie value will be returned as is.

func (*JwtCookieExtractor) ExtractRequestToken

func (j *JwtCookieExtractor) ExtractRequestToken(request *http.Request) (string, error)

type JwtMiddleware

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

JwtMiddleware is responsible for extraction, parsing and validation of JWTs from requests.

func NewJwtMiddleware

func NewJwtMiddleware(extractor TokenExtractor, parser TokenParser) *JwtMiddleware

func (*JwtMiddleware) Gin

func (mw *JwtMiddleware) Gin(ctx *gin.Context)

type TokenExtractor

type TokenExtractor interface {
	// ExtractRequestToken tries to extract an access token as plain string from the given request.
	//
	// If no token is found, an empty string and no error must be returned
	ExtractRequestToken(request *http.Request) (string, error)
}

type TokenExtractorChain

type TokenExtractorChain []TokenExtractor

TokenExtractorChain allows you to chain multiple TokenExtractor objects together.

func NewTokenExtractorChain

func NewTokenExtractorChain() TokenExtractorChain

func (TokenExtractorChain) Append

func (chain TokenExtractorChain) Append(extractor TokenExtractor) TokenExtractorChain

func (TokenExtractorChain) ExtractRequestToken

func (chain TokenExtractorChain) ExtractRequestToken(request *http.Request) (string, error)

type TokenParser

type TokenParser interface {
	// ParseToken parses a string to a jwt.Token. Parsed Claims must also be returned. This ensures that the correct
	// claims type is used.
	//
	// This method will either return an error or a parsed token.
	ParseToken(tokenString string) (*jwt.Token, *Claims, error)
}

type UnsecureJwtParser

type UnsecureJwtParser struct{}

UnsecureJwtParser parses a JWT token without validating its signature. Do not use this type in production!

func NewUnsecureJwtParser

func NewUnsecureJwtParser() *UnsecureJwtParser

func (*UnsecureJwtParser) ParseToken

func (u *UnsecureJwtParser) ParseToken(str string) (*jwt.Token, *Claims, error)

Jump to

Keyboard shortcuts

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