jwtauth

package
v0.133.0 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2021 License: Apache-2.0 Imports: 13 Imported by: 0

README

jwtauth

This is sysl-go's vendored version of the jwtauth library.

See docs for more details on the role and desigh.

Usage

Middleware
Customize authorisation

Authorisation refers to the process of checking a request as sufficient permissions to be executed. There are all sorts of conditions that can affect whether a request should be authorised, so this module provides an interface you should implement for custom authorisation

type Authoriser interface {
    Authorise(Claims) error
}

type AuthoriseFunc func(Claims) error
Configure authentication

Configuration can be done via json, yaml and viper, and integrates directly into larger config structs.

// Add Auth to your config
type AppConfig struct {
    Auth jwthttp.Config `json:"auth" yaml:"auth" mapstructure:"auth"`
}

// Initialise auth from config
func main() {
    // load config

    authClient := &http.Client{}
    auth := jwthttp.AuthFromConfig(&appConfig.Auth, func(string) *http.Client {return authClient})
    // This client func can be used to select a client on a per-issuer basis
}

// config.yaml
app:
  auth:
    headers: ["Authorisation"]
    issuers:
      - name: "mountebank"
        jwksUrl: "http://localhost:8888/.well-known/jwks.json"
        cacheTTL: "30m"

Documentation

Overview

Package jwtauth manages request authentication with jwts

This module provides a simple API to manage authentication and authorization with JWTs (JSON Web Token). Use this module when you have any one of the following needs

1. You need to authenticate JWTs from various token issues

2. You need to authorize JWTs have sufficient claims to execute a request

3. You need fine-grained control over the endpoints that get auth'n/o, and what gets checked

Authentication

Authentication in the JWT world refers to the action of verifying a jwt comes from a trusted source. This occurs via the Authenticator interface...

    type Authenticator interface {
		Authenticate(string token) (*Claims, error)
	}

TODO(cantosd): document configuration when done

Authorization

Authorization in the JWT world refers to verifying the claims have sufficient permissions to execute the request. This always happens after authentication, and it is generally assumed that jwts coming from trusted sources have had the claims verified by the source (issuer will not generate a jwt with admin permissions for a customer).

Authorization is handled by the Authorizor interface...

    type Authorizor interface {
		Authorize(claims *Claims) error
	}

It is up to the application to implement this interface. To do this, first define what valid permissions are for any given request, then implement this interface and make sure the request passes through it.

TODO(cantosd): Add middleware when done

Index

Constants

View Source
const (
	AuthErrCodeUnknown = iota
	AuthErrCodeInvalidJWT
	AuthErrCodeUntrustedSource
	AuthErrCodeBadSignature
	AuthErrCodeInsufficientPermissions
)

Authorization error codes.

Variables

This section is empty.

Functions

func AddClaimsToContext

func AddClaimsToContext(ctx context.Context, c Claims) context.Context

AddClaimsToContext adds claims to the context.

func SetLogFuncs

func SetLogFuncs(debug func(ctx context.Context, args ...interface{}), debugf func(ctx context.Context, format string, args ...interface{}))

SetLogFuncs sets the log functions to be used by the jwtauth logger.

func SetLogger

func SetLogger(l Logger)

SetLogger allows users of this library to set a logger to record non-critical errors.

eg. Failure to pre-fill the JWKS cache

If SetLogger is not called, logging will be sent to the default go log.

Types

type AuthError

type AuthError struct {
	Code  int
	Cause error
}

AuthError is a protocol agnostic error.

Codes can be translated into actual protocol error codes.

func (*AuthError) Error

func (e *AuthError) Error() string

func (*AuthError) HTTPStatus

func (e *AuthError) HTTPStatus() int

HTTPStatus returns an http status code corresponding to the AuthError code.

func (*AuthError) Unwrap

func (e *AuthError) Unwrap() error

Unwrap implements the unwrap interface in errors.

type Authenticator

type Authenticator interface {
	Authenticate(ctx context.Context, token string) (Claims, error)
}

Authenticator can authenticate raw tokens.

type AuthoriseFunc

type AuthoriseFunc func(Claims) error

AuthoriseFunc is a function type that implements Authorizor.

func (AuthoriseFunc) Authorise

func (a AuthoriseFunc) Authorise(c Claims) error

Authorise implements Authorizor for the AuthorizeFunc type.

type Authoriser

type Authoriser interface {
	Authorise(Claims) error
}

Authoriser is an interface that can authorize claims.

type Claims

type Claims = map[string]interface{}

Claims is weakly typed so it can hold any conceivable JSON claims value.

func GetClaimsFromContext

func GetClaimsFromContext(ctx context.Context) (Claims, bool)

GetClaimsFromContext retrieves claims from the context.

Returned claims is a safe copy of the context claims, so the context cannot be modified. To add new claims, you must re-add them to the context with AddClaimsToContext, and get a new context with the new claims added.

type Config

type Config struct {
	Issuers []IssuerConfig `json:"issuers"         yaml:"issuers"         mapstructure:"issuers"`
}

Config defines configuration for the standard authenticator.

type FuncLogger

type FuncLogger struct {
	DebugFunc  func(ctx context.Context, args ...interface{})
	DebugfFunc func(ctx context.Context, format string, args ...interface{})
}

func (*FuncLogger) Debug

func (f *FuncLogger) Debug(ctx context.Context, args ...interface{})

func (*FuncLogger) Debugf

func (f *FuncLogger) Debugf(ctx context.Context, format string, args ...interface{})

type InsecureAuthenticator

type InsecureAuthenticator struct{}

InsecureAuthenticator does not attempt to verify the signature of a jwt.

USE ONLY IN TESTING.

func (InsecureAuthenticator) Authenticate

func (i InsecureAuthenticator) Authenticate(ctx context.Context, raw string) (Claims, error)

Authenticate implements the Authenticator interface.

type IssuerConfig

type IssuerConfig struct {
	Name         string            `json:"name"                       yaml:"name"                       mapstructure:"name"`
	JWKSURL      string            `json:"jwksUrl,omitempty"          yaml:"jwksUrl,omitempty"          mapstructure:"jwksUrl"`
	CacheTTL     jsontime.Duration `json:"cacheTTL"                   yaml:"cacheTTL"                   mapstructure:"cacheTTL"`
	CacheRefresh jsontime.Duration `json:"cacheRefresh"               yaml:"cacheRefresh"               mapstructure:"cacheRefresh"`
}

IssuerConfig defines config for issuers for the std authenticator.

type Logger

type Logger interface {
	Debug(ctx context.Context, args ...interface{})
	Debugf(ctx context.Context, format string, args ...interface{})
}

func XXX_GetLogger

func XXX_GetLogger() Logger

XXX_GetLogger exposes the jwtauth package logger for use in auth middleware generated by protoc-gen-go-jwtauth.

DO NOT use this to get the logger yourself.

type RemoteJWKSIssuer

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

RemoteJWKSIssuer is a Verifier that retrieves and stores a jwks from a remote issuer.

Assumes the public key is served at GET {url}/.well-known/jwks.json.

func NewRemoteJWKSIssuer

func NewRemoteJWKSIssuer(ctx context.Context, issuer string, issuerURL string, client *http.Client, cacheTTL time.Duration,
	cacheRefresh time.Duration) (*RemoteJWKSIssuer, error)

NewRemoteJWKSIssuer creates a new RemoteJWKSIssuer. UNSTABLE: This API should be avoided in favour of `VerifierFromIssuerConfig()`.

keeps a cache of the jwks so it does not have to poll the remote jwks endpoint for every verify. cacheTTL defines the expiry time of the cache. cacheRefresh defines a cycle-time for a pre-emptive refresh background process (where cacheRefresh > 0).

func (*RemoteJWKSIssuer) Verify

func (r *RemoteJWKSIssuer) Verify(token *jwt.JSONWebToken, claims ...interface{}) error

Verify implements the Verify interface for RemoteJWKSIssuer.

type StdAuthenticator

type StdAuthenticator struct {
	Verifiers map[string]Verifier
}

StdAuthenticator is the standard jwt authenticator.

Keeps track of multiple verifiers. Authenticates jwts using the iss and kid fields in the jwt to pick a public key from multiple possible issuers and keys.

func AuthFromConfig

func AuthFromConfig(ctx context.Context, c *Config, client func(string) *http.Client) (*StdAuthenticator, error)

AuthFromConfig constructs a standard authenticator from config.

The client func allows the application to configure clients on a per-issuer basis. This is in case various remote issuers have different requirements about how to call them.

func (*StdAuthenticator) Authenticate

func (a *StdAuthenticator) Authenticate(ctx context.Context, raw string) (Claims, error)

Authenticate authenticates a jwt and returns the extracted claims, or an error if any occur.

type Verifier

type Verifier interface {
	Verify(token *jwt.JSONWebToken, claims ...interface{}) error
}

Verifier defines an interface that can verify an already parsed jwt token.

Intended use is in the StdAuthenticator, where each verifier corresponds to a single named token issuer.

func VerifierFromIssuerConfig

func VerifierFromIssuerConfig(ctx context.Context, i IssuerConfig, client *http.Client) (Verifier, error)

VerifierFromIssuerConfig creates a token verifier from issuer config.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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