jose

package
v1.8.6 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2024 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Example
package main

import (
	"fmt"

	"github.com/spothero/tools/jose"
)

func main() {
	// The JOSE Config allows users to configure the JOSE client for use with their OIDC provider
	c := jose.Config{
		// The "JWKS" endpoint for retrieving key sets for JWT verification
		JSONWebKeySetURLs: []string{"https://your-oidc-provider/.well-known/jwks.json"},
		// ValidIssuer is the URL of the JWT issuer for this environment. This must match the `iss`
		// within the JWT claim
		ValidIssuers: []string{"https://your-oidc-provider/issuerID"},
		// ClaimGenerators determine how JWT claims are to be parsed.
		ClaimGenerators: []jose.ClaimGenerator{
			jose.Auth0Generator{},
		},
	}

	// Instantiate the JOSE provider
	client := c.NewJOSE()

	// With the instantiated client, callers may choose to add HTTP Middleware and GRPC
	// interceptors directly to their servers:
	//
	// httpMiddleware := jose.GetHTTPServerMiddleware(client),
	//
	// joseInterceptorFunc := jose.GetContextAuth(client)
	// grpcauth.UnaryServerInterceptor(joseInterceptorFunc)

	// The instantiated client may also be used directly to parse and validate JWTs
	claims := client.GetClaims()
	if err := client.ParseValidateJWT("<your-jwt>", claims...); err != nil {
		fmt.Println(fmt.Errorf("failed to parse token: %w", err))
	}
	fmt.Printf("successfully parsed token: %+v\n", claims[0])
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthenticationMiddleware added in v0.36.0

func AuthenticationMiddleware(next http.Handler) http.Handler

AuthenticationMiddleware enforces authentication for all routes associated with a subrouter.

func EnforceAuthentication added in v0.36.0

func EnforceAuthentication(next http.HandlerFunc) http.HandlerFunc

EnforceAuthentication enforces authentication for a single HTTP handler. This handler only performs authentication. For authorization see EnforceAuthenticationWithAuthorization

func EnforceAuthenticationWithAuthorization added in v0.54.0

func EnforceAuthenticationWithAuthorization(next http.HandlerFunc, params AuthParams) http.HandlerFunc

func GetContextAuth added in v0.16.1

func GetContextAuth(jh Handler) func(context.Context) (context.Context, error)

GetContextAuth is a function which parameterizes and returns a function which extracts the Authorization data (if present) from incoming GRPC requests. If Authorization data is found, this function attempts to parse and validate that value as a JWT with the configured Credential types for the given JOSE provider.

func GetHTTPServerMiddleware added in v0.22.0

func GetHTTPServerMiddleware(jh Handler) func(next http.Handler) http.Handler

GetHTTPServerMiddleware returns an HTTP middleware function which extracts the Authorization header, if present, on all incoming HTTP requests. If an Authorization header is found, this middleware attempts to parse and validate that value as a JWT with the configured Credential types for the given JOSE provider.

func StreamClientInterceptor added in v0.21.0

func StreamClientInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error)

StreamClientInterceptor returns an interceptor that ensures that any authorization data on the context is passed through to the downstream server

func UnaryClientInterceptor added in v0.21.0

func UnaryClientInterceptor(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error

UnaryClientInterceptor returns an interceptor that ensures that any authorization data on the context is passed through to the downstream server

Types

type Auth0Claim added in v0.26.0

type Auth0Claim struct {
	ID string `json:"sub"`
	// Email claims are namespaced to prevent collisions. Hardcoding for now as this will be constant.
	Email          string `json:"https://api.spothero.com/claims/email"`
	ClientName     string `json:"https://api.spothero.com/claims/clientName"`
	GrantType      string `json:"gty"`
	Scope          string `json:"scope"`
	ExternalUserID string `json:"https://api.spothero.com/claims/user_id"`
}

Auth0Claim defines a JWT Claim for tokens issued by Auth0. Note that for Client Credentials JWTs, ClientID will be populated. For normal User authentication UserID will be populated. Both UserID and ClientID will not be populated together.

func FromContext added in v0.33.0

func FromContext(ctx context.Context) (*Auth0Claim, error)

FromContext extracts an Auth0 claim from a context

func (Auth0Claim) GetClientID added in v0.33.0

func (cc Auth0Claim) GetClientID() string

GetClientID returns the ClientID field of the claim if it is present, otherwise the empty string

func (Auth0Claim) GetUserID added in v0.33.0

func (cc Auth0Claim) GetUserID() string

GetUserID returns the UserID field of the claim if it is present, otherwise the empty string

func (Auth0Claim) NewContext added in v0.26.0

func (cc Auth0Claim) NewContext(ctx context.Context) context.Context

NewContext registers a claim to a given context and returns that new context

type Auth0CtxKey added in v0.26.0

type Auth0CtxKey int

Auth0CtxKey is the type used to uniquely place the Auth0 claim in the context

const Auth0ClaimKey Auth0CtxKey = iota

Auth0ClaimKey is the value used to uniquely place the Auth0 claim within the context

type Auth0Generator added in v0.26.0

type Auth0Generator struct{}

Auth0Generator satisfies the ClaimGenerator interface, allowing middleware to create intermediate Claim objects without specific knowledge of the underlying implementing types.

func (Auth0Generator) New added in v0.26.0

func (cg Auth0Generator) New() Claim

New satisfies the ClaimGenerator interface, returning an empty claim for use with JOSE parsing and validation.

type AuthParams added in v0.54.0

type AuthParams struct {
	RequiredScopes []string
}

type Claim added in v0.12.0

type Claim interface {
	// NewContext accepts an input context and embeds the claim within the context, returning it
	// for further use
	NewContext(c context.Context) context.Context
}

Claim defines an interface for common JWT claim functionality, such as registering claims to contexts.

type ClaimGenerator added in v0.12.0

type ClaimGenerator interface {
	// New creates and returns a new Claim of the given underlying type
	New() Claim
}

ClaimGenerator defines an interface which creates a JWT Claim

type Config

type Config struct {
	JSONWebKeySetURLs []string // JSON Web Key Set (JWKS) URLs for JSON Web Token (JWT) Verification
	ValidIssuers      []string // URL of the JWT Issuer for this environment
	// List of one or more claims to be captured from JWTs. If using http middleware,
	// these generators will determine which claims appear on the context.
	ClaimGenerators []ClaimGenerator
}

Config contains configuration for the JOSE package

func (Config) NewJOSE

func (c Config) NewJOSE() JOSE

NewJOSE creates and returns a JOSE client for use.

func (*Config) RegisterFlags

func (c *Config) RegisterFlags(flags *pflag.FlagSet)

RegisterFlags registers JOSE flags with pflags

type Handler added in v1.3.4

type Handler interface {
	// GetClaims returns an array containing empty claims
	GetClaims() []Claim
	// ParseValidateJWT accepts an input JWT string and populates any provided claims with
	// available claim data from the token.
	ParseValidateJWT(input string, claims ...Claim) error
}

Handler defines an interface for interfacing with JOSE and JWT functionality

type JOSE

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

JOSE contains configuration for handling JWTs, JWKS, and other JOSE specifications

func (JOSE) GetClaims added in v0.12.0

func (j JOSE) GetClaims() []Claim

GetClaims returns a set of empty and initialized Claims registered to the JOSE struct

func (JOSE) ParseValidateJWT

func (j JOSE) ParseValidateJWT(input string, claims ...Claim) error

ParseValidateJWT accepts a string containing a JWT token and attempts to parse and validate the token. If you wish to inspect other components of the payload, you may supply one or more claims structs which will be populated if the JWT is valid. Claims must be structs with json fields that match the keys in the payload field, or a map[string]interface{}. Use of map[string]interface{} is strongly discouraged.

type JWTHeaderCtxKey added in v0.21.0

type JWTHeaderCtxKey int

JWTHeaderCtxKey is the type used to uniquely place the JWT Header in the context

const JWTClaimKey JWTHeaderCtxKey = iota

JWTClaimKey is the value used to uniquely place the JWT Header within the context

type MockClaim added in v0.12.0

type MockClaim struct{}

MockClaim defines a JWT Claim for tokens

func (MockClaim) NewContext added in v0.12.0

func (mc MockClaim) NewContext(ctx context.Context) context.Context

NewContext registers a claim to a given context

type MockCtxKey added in v0.12.0

type MockCtxKey int

MockCtxKey is the type used to uniquely place the mock claim in the context

const MockClaimKey MockCtxKey = iota

MockClaimKey is the value used to uniquely place the mock claim within the context

type MockGenerator added in v0.12.0

type MockGenerator struct{}

MockGenerator satisfies the ClaimGenerator interface

func (MockGenerator) New added in v0.12.0

func (mg MockGenerator) New() Claim

New satisfies the ClaimGenerator interface, returning an empty claim for use with JOSE parsing and validation.

type MockHandler added in v0.12.0

type MockHandler struct {
	mock.Mock
	// contains filtered or unexported fields
}

MockHandler defines an interface for mocking JOSE and JWT functionality

func (*MockHandler) GetClaims added in v0.12.0

func (mh *MockHandler) GetClaims() []Claim

GetClaims mocks retrieval of claim instances

func (*MockHandler) ParseValidateJWT added in v0.12.0

func (mh *MockHandler) ParseValidateJWT(input string, claims ...Claim) error

ParseValidateJWT mocks the ParseValidateJWT function

type RoundTripper added in v0.24.0

type RoundTripper struct {
	RoundTripper http.RoundTripper
}

RoundTripper implements an http.RoundTripper which passes along any auth headers automatically

func (RoundTripper) RoundTrip added in v0.24.0

func (rt RoundTripper) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip is intended for use in HTTP Clients and it propagates the Authorization headers on outgoing HTTP calls automatically

Jump to

Keyboard shortcuts

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