jam

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2023 License: BSD-2-Clause Imports: 8 Imported by: 0

README

Jam

JWT Authentication Middleware. This project is just an extension of the go-chi middleware; it has a shameful amount of copy-paste, but it also includes some extra options to parse the token from (the original project has header and cookie lookup by default). Additionally, it borrows a lot of concepts / unambiguously steals ideas from the lestrrat-go/echo-middleware-jwx project.

lestrrat is also the creator of the wonderful JWX package, one of the best and most complete implementations of the JWT Standards available in Go.

All the credit goes to the go-chi team and to lestrrat; my work was secondary, and it wouldn't have been possible without all the effort and contributions from them.

Contributing

I encourage anyone to contribute with the original projects; nonetheless, if you feel like adding stuff to this repo, don't mind to check the CONTRIBUTING file.

Licensing

LICENSE.

Documentation

Index

Constants

View Source
const (
	/*
		Supported values for SignatureAlgorithm
	*/
	ES256  jwa.SignatureAlgorithm = "ES256"  // ECDSA using P-256 and SHA-256
	ES256K jwa.SignatureAlgorithm = "ES256K" // ECDSA using secp256k1 and SHA-256
	ES384  jwa.SignatureAlgorithm = "ES384"  // ECDSA using P-384 and SHA-384
	ES512  jwa.SignatureAlgorithm = "ES512"  // ECDSA using P-521 and SHA-512
	EdDSA  jwa.SignatureAlgorithm = "EdDSA"  // EdDSA signature algorithms
	HS256  jwa.SignatureAlgorithm = "HS256"  // HMAC using SHA-256
	HS384  jwa.SignatureAlgorithm = "HS384"  // HMAC using SHA-384
	HS512  jwa.SignatureAlgorithm = "HS512"  // HMAC using SHA-512
	/*
		NoSignature jwa.SignatureAlgorithm = "none" Not supported
	*/
	PS256 jwa.SignatureAlgorithm = "PS256" // RSASSA-PSS using SHA256 and MGF1-SHA256
	PS384 jwa.SignatureAlgorithm = "PS384" // RSASSA-PSS using SHA384 and MGF1-SHA384
	PS512 jwa.SignatureAlgorithm = "PS512" // RSASSA-PSS using SHA512 and MGF1-SHA512
	RS256 jwa.SignatureAlgorithm = "RS256" // RSASSA-PKCS-v1.5 using SHA-256
	RS384 jwa.SignatureAlgorithm = "RS384" // RSASSA-PKCS-v1.5 using SHA-384
	RS512 jwa.SignatureAlgorithm = "RS512" // RSASSA-PKCS-v1.5 using SHA-512
)

Variables

View Source
var (
	ErrUnauthorized = errors.New("token is unauthorized")
	ErrExpired      = errors.New("token is expired")
	ErrNBFInvalid   = errors.New("token nbf validation failed")
	ErrIATInvalid   = errors.New("token iat validation failed")
	ErrNoTokenFound = errors.New("no token found")
	ErrVerifyKeyNil = errors.New("algorithm requires a private and a public key pair")
)
View Source
var (
	TokenCtxKey = &contextKey{"Token"}
	ErrorCtxKey = &contextKey{"Error"}
)
View Source
var (
	DefaultLookupOptions = LookUpOptions{
		SearchFor:  "jwt",
		HeaderName: "Authorization",
		AuthScheme: "Bearer",
	}
)

Functions

func Authenticator

func Authenticator(next http.Handler) http.Handler

Authenticator is a default authentication middleware to enforce access from the Verifier middleware request context values. The Authenticator sends a 401 Unauthorized response for any unverified tokens and passes the good ones through. It's just fine until you decide to write something similar and customize your client response.

func EpochNow

func EpochNow() int64

EpochNow is a helper function that returns the NumericDate time value used by the spec

func ErrorReason

func ErrorReason(err error) error

ErrorReason will normalize the error message from the underlining jwt library

func ExpiresIn

func ExpiresIn(tm time.Duration) int64

ExpiresIn is a helper function to return calculated time in the future for "exp" claim

func FromContext

func FromContext(ctx context.Context) (jwt.Token, map[string]any, error)

FromContext reads the context and tries to find the token; if it exists, then the function tries to extract its payload and also the error from the parent context (if any).

func NewContext

func NewContext(ctx context.Context, t jwt.Token, err error) context.Context

NewContext adds the token and the error to the given context.

func SetExpiration

func SetExpiration(claims map[string]any, tm time.Time)

SetExpiration Set expiration time ("exp") in the claims

func SetExpiresIn

func SetExpiresIn(claims map[string]any, tm time.Duration)

SetExpiresIn Set Expiration Time ("exp") in the claims to some duration from the present time

func SetIssuedAt

func SetIssuedAt(claims map[string]any, tm time.Time)

SetIssuedAt Set issued at ("iat") to specified time in the claims

func SetIssuedNow

func SetIssuedNow(claims map[string]any)

SetIssuedNow Set issued at ("iat") to present time in the claims

func TokenFromCookie

func TokenFromCookie(r *http.Request, j *Jam) string

TokenFromCookie tries to retrieve the token string from a cookie, looking for the name specified in the "SearchFor" field of the config.

func TokenFromForm

func TokenFromForm(r *http.Request, j *Jam) string

TokenFromForm tries to retrieve the token string from a form.

func TokenFromHeader

func TokenFromHeader(r *http.Request, j *Jam) string

TokenFromHeader tries to retrieve the token string from the specified request header: "HEADERNAME: BEARER T".

func TokenFromParam

func TokenFromParam(r *http.Request, j *Jam) string

TokenFromParam tries to retrieve the token string from an url param.

func TokenFromQuery

func TokenFromQuery(r *http.Request, j *Jam) string

TokenFromQuery tries to retrieve the token string from a query.

func UnixTime

func UnixTime(tm time.Time) int64

UnixTime returns the given time in UTC milliseconds

func Verifier

func Verifier(ja *Jam) func(http.Handler) http.Handler

func Verify

func Verify(ja *Jam, extractors ...Extractor) func(http.Handler) http.Handler

Verify is the underlying implementation of Verifier. It takes the request and verify if it has a token; if it does, then this function will save that information to the request's context so the token can be used by other middlewares or parts of the application dealing with that request.

func VerifyRequest

func VerifyRequest(ja *Jam, r *http.Request, extractors ...Extractor) (jwt.Token, error)

VerifyRequest checks if the request contains a token, using the provided extractors.

func VerifyToken

func VerifyToken(ja *Jam, tokenString string) (jwt.Token, error)

VerifyToken takes a token string and checks if it's valid (e.g. not expired, correct signature, etc).

Types

type Extractor

type Extractor func(*http.Request, *Jam) string

Extractor is the standard function type (signature) used to check a request and try to extract a token from a specific part of it.

type Jam

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

func New

func New(
	alg jwa.SignatureAlgorithm,
	lookup LookUpOptions,
	signKey, verifyKey any,
	extractors ...Extractor) (*Jam, error)

func (*Jam) Decode

func (ja *Jam) Decode(tokenString string) (jwt.Token, error)

Decode takes a token string and decodes it.

func (*Jam) Encode

func (ja *Jam) Encode(claims map[string]any) (t jwt.Token, tokenString string, err error)

Encode creates a jwt.Token and encode the given payload.

type LookUpOptions

type LookUpOptions struct {
	// SearchFor is the name of the object containing the token
	SearchFor string
	// HeaderName name of the http header containing the token. Optional.
	HeaderName string
	// AuthScheme Used when the looking for a token in the headers - Authorization format.
	// The default value is "Bearer". It's optional
	AuthScheme string
}

LookUpOptions holds the basic structure of a token lookup flow.

type TokenLookup

type TokenLookup string

Jump to

Keyboard shortcuts

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