middleware

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2024 License: MIT Imports: 6 Imported by: 0

README

connectrpc-middleware

Go Reference

auth interceptor

used with caution, still in development

//default bearer token extractor and parser
//extract token from "Authorization": Bearer <token>, and parse token into jwt.MapClaim
authMiddleware, err := middleware.NewAuthMiddleware(middleware.WithDefaultBearerExtractorAndParser([]byte("secret")))
if err != nil {
	panic(err)
}
http.ListenAndServe(
	"localhost:8080",
	// Use h2c so we can serve HTTP/2 without TLS.
	h2c.NewHandler(authMiddleware.Wrap(mux), &http2.Server{}),
)

TODO

  • tests for cookie
  • e2e test
  • test for kid field

refs

Documentation

Index

Constants

View Source
const (
	// AlgorithmHS256 is token signing algorithm
	AlgorithmHS256 = "HS256"
)
View Source
const HeaderAuthorization = "Authorization"
View Source
const (
	UnaryAndStreamHandler = UnaryHandler | StreamHandler
)

Variables

This section is empty.

Functions

func DefaultSkipper

func DefaultSkipper(context.Context, *Request) bool

DefaultSkipper returns false which processes the middleware.

func FromContext

func FromContext[T any](ctx context.Context) (T, bool)

FromContext is used to get the payload from context, T is the returned type from parser

func FromRawCookies

func FromRawCookies(rawCookies string) []*http.Cookie

FromRawCookies takes a raw cookie string and returns a slice of *http.Cookie

func IsExtractTokenErr

func IsExtractTokenErr(err error) bool

IsExtractTokenErr checks if err is from Extractor

func IsParseTokenErr

func IsParseTokenErr(err error) bool

IsParseTokenErr checks if err is from Parser It can be used in ErrorHandle to determine where to err come from

func NewAuthInterceptor

func NewAuthInterceptor(opts ...authInterceptorOpt) (*authInterceptor, error)

func NewAuthMiddleware added in v0.2.0

func NewAuthMiddleware(opts ...authMiddlewareOpt) (*authMiddleware, error)

func NewContext added in v0.2.0

func NewContext(ctx context.Context, payload any) context.Context

func NewJWTParser

func NewJWTParser(opts ...jwtParserOpt) (jwtParser, error)

func ValuesFromCookie

func ValuesFromCookie(name, cookiesRaw string) ([]string, error)

ValuesFromCookie returns a function that extracts values from the named cookie.

func ValuesFromHeader

func ValuesFromHeader(values []string, valuePrefix string) ([]string, error)

ValuesFromHeader take http.Request.Header.Values and a prefix as input return a slice of string without the prefix when values is empty, return errHeaderExtractorValueMissing when prefix is empty, return the input values, keep the http.Request.Header.Values backing array if there is one when prefix is not empty, return a new slice of values without the prefix

func WithBeforeFunc added in v0.2.0

func WithBeforeFunc(fn BeforeFunc) authMiddlewareOpt

func WithCustomJWTClaimsParser

func WithCustomJWTClaimsParser(signningKey any, claimsFunc func(context.Context) jwt.Claims) authMiddlewareOpt

WithCustomJWTClaimsParser sets Parser with signning key and a claimsFunc, the claimsFunc must return a reference for example:

func(ctx context.Context) jwt.Claims{
	return &jwt.MapClaims{}
}

func WithDefaultBearerExtractor

func WithDefaultBearerExtractor() authMiddlewareOpt

func WithDefaultBearerExtractorAndParser

func WithDefaultBearerExtractorAndParser(signningKey any) authMiddlewareOpt

func WithDefaultJWTMapClaimsParser

func WithDefaultJWTMapClaimsParser(signningKey any) authMiddlewareOpt

func WithErrorHandler added in v0.2.0

func WithErrorHandler(fn ErrorHandle) authMiddlewareOpt

func WithErrorWriterOpts added in v0.2.1

func WithErrorWriterOpts(opts ...connect.HandlerOption) authMiddlewareOpt

func WithExtractor added in v0.2.0

func WithExtractor(fn Extractor) authMiddlewareOpt

func WithIgnoreError added in v0.2.0

func WithIgnoreError() authMiddlewareOpt

func WithInterceptorBeforeFunc added in v0.2.1

func WithInterceptorBeforeFunc(fn BeforeFunc) authInterceptorOpt

func WithInterceptorClientTokenGetter added in v0.2.1

func WithInterceptorClientTokenGetter(getter ClientTokenGetter) authInterceptorOpt

WithClientTokenGetter sets client token getter when the interceptor in client side

func WithInterceptorCustomJWTClaimsParser added in v0.2.1

func WithInterceptorCustomJWTClaimsParser(signningKey any, claimsFunc func(context.Context) jwt.Claims) authInterceptorOpt

WithCustomJWTClaimsParser sets Parser with signning key and a claimsFunc, the claimsFunc must return a reference for example:

func(ctx context.Context) jwt.Claims{
	return &jwt.MapClaims{}
}

func WithInterceptorDefaultBearerExtractor added in v0.2.1

func WithInterceptorDefaultBearerExtractor() authInterceptorOpt

func WithInterceptorDefaultBearerExtractorAndParser added in v0.2.1

func WithInterceptorDefaultBearerExtractorAndParser(signningKey any) authInterceptorOpt

func WithInterceptorDefaultJWTMapClaimsParser added in v0.2.1

func WithInterceptorDefaultJWTMapClaimsParser(signningKey any) authInterceptorOpt

func WithInterceptorErrorHandler added in v0.2.1

func WithInterceptorErrorHandler(fn ErrorHandle) authInterceptorOpt

func WithInterceptorExtractor added in v0.2.1

func WithInterceptorExtractor(fn Extractor) authInterceptorOpt

func WithInterceptorIgnoreError added in v0.2.1

func WithInterceptorIgnoreError() authInterceptorOpt

func WithInterceptorParser added in v0.2.1

func WithInterceptorParser(p Parser) authInterceptorOpt

func WithInterceptorSkipper added in v0.2.1

func WithInterceptorSkipper(s Skipper) authInterceptorOpt

WithUnarySkipper skip the interceptor for unary handler

func WithInterceptorSuccessFunc added in v0.2.1

func WithInterceptorSuccessFunc(fn SuccessFunc) authInterceptorOpt

func WithJWTMapClaims

func WithJWTMapClaims(signingKey any) jwtParserOpt

WithJWTMapClaims returns a jwtParser with default jwt.MapClaims and signingMethod

func WithKeyFunc

func WithKeyFunc(keyFunc jwt.Keyfunc) jwtParserOpt

func WithLookupConfig

func WithLookupConfig(source, name, cutPrefix string) headerExtractorOpt

func WithLookupConfigs

func WithLookupConfigs(configs ...LookupConfig) headerExtractorOpt

func WithNewClaimsFunc

func WithNewClaimsFunc(newClaimsFunc func(context.Context) jwt.Claims) jwtParserOpt

WithNewClaimsFunc sets NewClaimsFunc. the newClaimsFunc must return a reference for json unmarshalling to work

func WithParser

func WithParser(p Parser) authMiddlewareOpt

func WithServiceHandlerType added in v0.2.0

func WithServiceHandlerType(s ServiceHandlerType) authInterceptorOpt

func WithSigningKey

func WithSigningKey(signingKey any) jwtParserOpt

func WithSigningKeys

func WithSigningKeys(signingKeys map[string]any) jwtParserOpt

func WithSigningMethod

func WithSigningMethod(signingMethod string) jwtParserOpt

func WithSkipper added in v0.2.0

func WithSkipper(s Skipper) authMiddlewareOpt

WithUnarySkipper skip the interceptor for unary handler

func WithSuccessFunc added in v0.2.0

func WithSuccessFunc(fn SuccessFunc) authMiddlewareOpt

Types

type AuthHandler

type AuthHandler struct {
	//Skipper defines a function to skip the middleware
	Skipper Skipper
	// BeforeFunc defines a function which is executed before Extracor and Parser.
	// If this function return an error, the middleware will return the error and skip the rest of the process.
	// ErrorHandler will be ignored if BeforeFunc return an error.
	BeforeFunc BeforeFunc
	// Extractor defines a function which is used to extract token from request.
	Extractor Extractor
	Parser    Parser
	// SuccessFunc defines a function which is executed after Extracor and Parser when they return no error.
	// This function accepts the context, the request and the payload returned by Parser.
	// If this function return an error, the middleware will return with the error and skip error handler.
	// ErrorHandler will be ignored if SuccessFunc return an error.
	SuccessFunc SuccessFunc
	// ErrorHandler defines a function which is executed when Extractor or Parser return error.
	ErrorHandler ErrorHandle
}

AuthHandler is used in unary and streaming service handler The order of execution of handler's functions are: Skipper -> BeforeFunc (if this function return err, skip the rest process) -> Extractor -> Parser (parser will be skipped if extractor return an empty token list) -> SuccessFunc (if thie function return err, skip error handler) -> ErrorHandler (if extractor or parser return an error, and SuccessFunc return nil, this function will be called)

type BeforeFunc added in v0.3.0

type BeforeFunc func(context.Context, *Request) error

BeforeFunc

type ClientTokenGetter

type ClientTokenGetter interface {
	Get() (string, string)
}

ClientTokenGetter is used to get token for client request

type ErrorHandle

type ErrorHandle func(context.Context, *Request, error) error

ErrorHandle take error from Extractor or Parser, return nil to ignore error

type ExtractedHeader added in v0.2.0

type ExtractedHeader map[string][]string

func (ExtractedHeader) Get added in v0.2.0

func (h ExtractedHeader) Get(key string) []string

func (ExtractedHeader) Set added in v0.2.0

func (h ExtractedHeader) Set(key string, values []string)

type Extractor

type Extractor func(context.Context, *Request) (ExtractedHeader, error)

Extractor is used to extract token from request, The returned map contain all the information extracted from the request header, it is a map of headerName->[]headerValues

type HeaderExtractor

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

HeaderExtractor can take multiple LookupConfig as config LookupConfig is used to extract token from request header, it can either be header value or cookie value ToExtractor will output a function which can extract values from header based on the provided configs The returned ExtractedHeader is case sensitive and will keep the config.Name case The Extractor returned by ToExtractor will use config.Name's canonical format to extract values from header

func DefaultBasicAuthExtractor added in v0.3.0

func DefaultBasicAuthExtractor() HeaderExtractor

func DefaultBearerTokenExtractor

func DefaultBearerTokenExtractor() HeaderExtractor

func NewHeaderExtractor

func NewHeaderExtractor(opts ...headerExtractorOpt) (HeaderExtractor, error)

func (HeaderExtractor) ToExtractor added in v0.2.0

func (e HeaderExtractor) ToExtractor() Extractor

ToExtractor return a function which can extract values from header based on the provided configs it loop through the LookupConfigs, if the config source is header, it will extract values from header if the config source is cookie, it will extract values from cookie it will try to extract at least one value with the provided configs if no value can be extracted, it will return errHeaderExtractorValueMissing

type LookupConfig

type LookupConfig struct {
	Source    TokenSource
	Name      string
	CutPrefix string // Optional, used only if Source is "header"
}

type Middleware added in v0.2.3

type Middleware interface {
	Wrap(http.Handler) http.Handler
}

type Parser

type Parser func(ctx context.Context, extractedHeader ExtractedHeader) (any, error)

Parser is used to parse tokens from Extractor

func DefaultJWTMapClaimsParser

func DefaultJWTMapClaimsParser(signingKey any) Parser

DefaultJWTMapClaimsParser returns a jwtParser with default jwt.MapClaims and signingMethod

type Request added in v0.2.0

type Request struct {
	Procedure  string // for example, "/acme.foo.v1.FooService/Bar"
	ClientAddr string // client address, in IP:port format
	Protocol   string // connect.ProtocolConnect, connect.ProtocolGRPC, or connect.ProtocolGRPCWeb
	Header     http.Header
}

Request describes a single RPC invocation.

type ServiceHandlerType added in v0.2.0

type ServiceHandlerType int
const (
	UnaryHandler ServiceHandlerType = 1 << iota
	StreamHandler
)

type Skipper

type Skipper func(context.Context, *Request) bool

Skipper can return true to skip middleware

type SuccessFunc added in v0.3.0

type SuccessFunc func(context.Context, *Request) error

SuccessFunc

type TokenSource

type TokenSource string
const (
	TokenSourceHeader TokenSource = "header"
	TokenSourceCookie TokenSource = "cookie"
)

Directories

Path Synopsis
gen/ping/v1/pingv1connect
The connect.ping.v1 package contains an echo service designed to test the connect-go implementation.
The connect.ping.v1 package contains an echo service designed to test the connect-go implementation.

Jump to

Keyboard shortcuts

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