matterbridge/vendor/github.com/labstack/echo/v4/middleware/jwt.go

301 lines
10 KiB
Go
Raw Normal View History

2022-03-12 10:41:07 -08:00
//go:build go1.15
// +build go1.15
2017-02-18 14:00:46 -08:00
package middleware
import (
2021-07-31 09:27:55 -07:00
"errors"
2017-02-18 14:00:46 -08:00
"fmt"
"github.com/golang-jwt/jwt"
"github.com/labstack/echo/v4"
2022-03-12 10:41:07 -08:00
"net/http"
"reflect"
2017-02-18 14:00:46 -08:00
)
type (
// JWTConfig defines the config for JWT middleware.
JWTConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// BeforeFunc defines a function which is executed just before the middleware.
BeforeFunc BeforeFunc
2022-03-12 10:41:07 -08:00
// SuccessHandler defines a function which is executed for a valid token before middleware chain continues with next
// middleware or handler.
SuccessHandler JWTSuccessHandler
// ErrorHandler defines a function which is executed for an invalid token.
// It may be used to define a custom JWT error.
ErrorHandler JWTErrorHandler
2020-05-23 15:06:21 -07:00
2019-09-07 13:46:58 -07:00
// ErrorHandlerWithContext is almost identical to ErrorHandler, but it's passed the current context.
ErrorHandlerWithContext JWTErrorHandlerWithContext
2022-03-12 10:41:07 -08:00
// ContinueOnIgnoredError allows the next middleware/handler to be called when ErrorHandlerWithContext decides to
// ignore the error (by returning `nil`).
// This is useful when parts of your site/api allow public access and some authorized routes provide extra functionality.
// In that case you can use ErrorHandlerWithContext to set a default public JWT token value in the request context
// and continue. Some logic down the remaining execution chain needs to check that (public) token value then.
ContinueOnIgnoredError bool
2021-05-29 15:25:30 -07:00
// Signing key to validate token.
// This is one of the three options to provide a token validation key.
// The order of precedence is a user-defined KeyFunc, SigningKeys and SigningKey.
// Required if neither user-defined KeyFunc nor SigningKeys is provided.
2017-02-18 14:00:46 -08:00
SigningKey interface{}
2019-06-16 14:33:25 -07:00
// Map of signing keys to validate token with kid field usage.
2021-05-29 15:25:30 -07:00
// This is one of the three options to provide a token validation key.
// The order of precedence is a user-defined KeyFunc, SigningKeys and SigningKey.
// Required if neither user-defined KeyFunc nor SigningKey is provided.
2019-06-16 14:33:25 -07:00
SigningKeys map[string]interface{}
2021-05-29 15:25:30 -07:00
// Signing method used to check the token's signing algorithm.
2017-02-18 14:00:46 -08:00
// Optional. Default value HS256.
SigningMethod string
// Context key to store user information from the token into context.
// Optional. Default value "user".
ContextKey string
2021-07-31 09:27:55 -07:00
// Claims are extendable claims data defining token content. Used by default ParseTokenFunc implementation.
// Not used if custom ParseTokenFunc is set.
2017-02-18 14:00:46 -08:00
// Optional. Default value jwt.MapClaims
Claims jwt.Claims
2021-07-31 09:27:55 -07:00
// TokenLookup is a string in the form of "<source>:<name>" or "<source>:<name>,<source>:<name>" that is used
2017-02-18 14:00:46 -08:00
// to extract token from the request.
// Optional. Default value "header:Authorization".
// Possible values:
2022-03-12 10:41:07 -08:00
// - "header:<name>" or "header:<name>:<cut-prefix>"
// `<cut-prefix>` is argument value to cut/trim prefix of the extracted value. This is useful if header
// value has static prefix like `Authorization: <auth-scheme> <authorisation-parameters>` where part that we
// want to cut is `<auth-scheme> ` note the space at the end.
// In case of JWT tokens `Authorization: Bearer <token>` prefix we cut is `Bearer `.
// If prefix is left empty the whole value is returned.
2017-02-18 14:00:46 -08:00
// - "query:<name>"
2019-06-16 14:33:25 -07:00
// - "param:<name>"
2017-02-18 14:00:46 -08:00
// - "cookie:<name>"
2021-03-20 14:40:23 -07:00
// - "form:<name>"
2022-03-12 10:41:07 -08:00
// Multiple sources example:
// - "header:Authorization,cookie:myowncookie"
2017-02-18 14:00:46 -08:00
TokenLookup string
2022-03-12 10:41:07 -08:00
// TokenLookupFuncs defines a list of user-defined functions that extract JWT token from the given context.
// This is one of the two options to provide a token extractor.
// The order of precedence is user-defined TokenLookupFuncs, and TokenLookup.
// You can also provide both if you want.
TokenLookupFuncs []ValuesExtractor
2017-02-18 14:00:46 -08:00
// AuthScheme to be used in the Authorization header.
// Optional. Default value "Bearer".
AuthScheme string
2021-05-29 15:25:30 -07:00
// KeyFunc defines a user-defined function that supplies the public key for a token validation.
// The function shall take care of verifying the signing algorithm and selecting the proper key.
// A user-defined KeyFunc can be useful if tokens are issued by an external party.
2021-07-31 09:27:55 -07:00
// Used by default ParseTokenFunc implementation.
2021-05-29 15:25:30 -07:00
//
// When a user-defined KeyFunc is provided, SigningKey, SigningKeys, and SigningMethod are ignored.
// This is one of the three options to provide a token validation key.
// The order of precedence is a user-defined KeyFunc, SigningKeys and SigningKey.
// Required if neither SigningKeys nor SigningKey is provided.
2021-07-31 09:27:55 -07:00
// Not used if custom ParseTokenFunc is set.
2021-05-29 15:25:30 -07:00
// Default to an internal implementation verifying the signing algorithm and selecting the proper key.
KeyFunc jwt.Keyfunc
2021-07-31 09:27:55 -07:00
// ParseTokenFunc defines a user-defined function that parses token from given auth. Returns an error when token
// parsing fails or parsed token is invalid.
// Defaults to implementation using `github.com/golang-jwt/jwt` as JWT implementation library
2021-07-31 09:27:55 -07:00
ParseTokenFunc func(auth string, c echo.Context) (interface{}, error)
2017-02-18 14:00:46 -08:00
}
// JWTSuccessHandler defines a function which is executed for a valid token.
2022-03-12 10:41:07 -08:00
JWTSuccessHandler func(c echo.Context)
// JWTErrorHandler defines a function which is executed for an invalid token.
2022-03-12 10:41:07 -08:00
JWTErrorHandler func(err error) error
2019-09-07 13:46:58 -07:00
// JWTErrorHandlerWithContext is almost identical to JWTErrorHandler, but it's passed the current context.
2022-03-12 10:41:07 -08:00
JWTErrorHandlerWithContext func(err error, c echo.Context) error
2017-02-18 14:00:46 -08:00
)
// Algorithms
const (
AlgorithmHS256 = "HS256"
)
2017-12-07 14:00:56 -08:00
// Errors
var (
ErrJWTMissing = echo.NewHTTPError(http.StatusBadRequest, "missing or malformed jwt")
2021-03-20 14:40:23 -07:00
ErrJWTInvalid = echo.NewHTTPError(http.StatusUnauthorized, "invalid or expired jwt")
2017-12-07 14:00:56 -08:00
)
2017-02-18 14:00:46 -08:00
var (
// DefaultJWTConfig is the default JWT auth middleware config.
DefaultJWTConfig = JWTConfig{
2022-03-12 10:41:07 -08:00
Skipper: DefaultSkipper,
SigningMethod: AlgorithmHS256,
ContextKey: "user",
TokenLookup: "header:" + echo.HeaderAuthorization,
TokenLookupFuncs: nil,
AuthScheme: "Bearer",
Claims: jwt.MapClaims{},
KeyFunc: nil,
2017-02-18 14:00:46 -08:00
}
)
// JWT returns a JSON Web Token (JWT) auth middleware.
//
// For valid token, it sets the user in context and calls next handler.
// For invalid token, it returns "401 - Unauthorized" error.
// For missing token, it returns "400 - Bad Request" error.
//
// See: https://jwt.io/introduction
// See `JWTConfig.TokenLookup`
2017-12-07 14:00:56 -08:00
func JWT(key interface{}) echo.MiddlewareFunc {
2017-02-18 14:00:46 -08:00
c := DefaultJWTConfig
c.SigningKey = key
return JWTWithConfig(c)
}
// JWTWithConfig returns a JWT auth middleware with config.
// See: `JWT()`.
func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
// Defaults
if config.Skipper == nil {
config.Skipper = DefaultJWTConfig.Skipper
}
2021-07-31 09:27:55 -07:00
if config.SigningKey == nil && len(config.SigningKeys) == 0 && config.KeyFunc == nil && config.ParseTokenFunc == nil {
2017-06-05 15:01:05 -07:00
panic("echo: jwt middleware requires signing key")
2017-02-18 14:00:46 -08:00
}
if config.SigningMethod == "" {
config.SigningMethod = DefaultJWTConfig.SigningMethod
}
if config.ContextKey == "" {
config.ContextKey = DefaultJWTConfig.ContextKey
}
if config.Claims == nil {
config.Claims = DefaultJWTConfig.Claims
}
2022-03-12 10:41:07 -08:00
if config.TokenLookup == "" && len(config.TokenLookupFuncs) == 0 {
2017-02-18 14:00:46 -08:00
config.TokenLookup = DefaultJWTConfig.TokenLookup
}
if config.AuthScheme == "" {
config.AuthScheme = DefaultJWTConfig.AuthScheme
}
2021-05-29 15:25:30 -07:00
if config.KeyFunc == nil {
config.KeyFunc = config.defaultKeyFunc
2017-02-18 14:00:46 -08:00
}
2021-07-31 09:27:55 -07:00
if config.ParseTokenFunc == nil {
config.ParseTokenFunc = config.defaultParseToken
}
2017-02-18 14:00:46 -08:00
2022-03-12 10:41:07 -08:00
extractors, err := createExtractors(config.TokenLookup, config.AuthScheme)
if err != nil {
panic(err)
}
if len(config.TokenLookupFuncs) > 0 {
extractors = append(config.TokenLookupFuncs, extractors...)
2017-02-18 14:00:46 -08:00
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if config.Skipper(c) {
return next(c)
}
if config.BeforeFunc != nil {
config.BeforeFunc(c)
}
2022-03-12 10:41:07 -08:00
var lastExtractorErr error
var lastTokenErr error
2021-05-29 15:25:30 -07:00
for _, extractor := range extractors {
2022-03-12 10:41:07 -08:00
auths, err := extractor(c)
if err != nil {
lastExtractorErr = ErrJWTMissing // backwards compatibility: all extraction errors are same (unlike KeyAuth)
continue
2021-05-29 15:25:30 -07:00
}
2022-03-12 10:41:07 -08:00
for _, auth := range auths {
token, err := config.ParseTokenFunc(auth, c)
if err != nil {
lastTokenErr = err
continue
}
// Store user information from token into context.
c.Set(config.ContextKey, token)
if config.SuccessHandler != nil {
config.SuccessHandler(c)
}
return next(c)
2019-09-07 13:46:58 -07:00
}
2017-02-18 14:00:46 -08:00
}
2022-03-12 10:41:07 -08:00
// we are here only when we did not successfully extract or parse any of the tokens
err := lastTokenErr
if err == nil { // prioritize token errors over extracting errors
err = lastExtractorErr
2017-02-18 14:00:46 -08:00
}
if config.ErrorHandler != nil {
return config.ErrorHandler(err)
}
2019-09-07 13:46:58 -07:00
if config.ErrorHandlerWithContext != nil {
2022-03-12 10:41:07 -08:00
tmpErr := config.ErrorHandlerWithContext(err, c)
if config.ContinueOnIgnoredError && tmpErr == nil {
return next(c)
}
return tmpErr
2019-09-07 13:46:58 -07:00
}
2022-03-12 10:41:07 -08:00
// backwards compatible errors codes
if lastTokenErr != nil {
return &echo.HTTPError{
Code: ErrJWTInvalid.Code,
Message: ErrJWTInvalid.Message,
Internal: err,
}
2017-12-07 14:00:56 -08:00
}
2022-03-12 10:41:07 -08:00
return err // this is lastExtractorErr value
2017-02-18 14:00:46 -08:00
}
}
}
2021-07-31 09:27:55 -07:00
func (config *JWTConfig) defaultParseToken(auth string, c echo.Context) (interface{}, error) {
token := new(jwt.Token)
var err error
// Issue #647, #656
if _, ok := config.Claims.(jwt.MapClaims); ok {
token, err = jwt.Parse(auth, config.KeyFunc)
} else {
t := reflect.ValueOf(config.Claims).Type().Elem()
claims := reflect.New(t).Interface().(jwt.Claims)
token, err = jwt.ParseWithClaims(auth, claims, config.KeyFunc)
}
if err != nil {
return nil, err
}
if !token.Valid {
return nil, errors.New("invalid token")
}
return token, nil
}
2021-05-29 15:25:30 -07:00
// defaultKeyFunc returns a signing key of the given token.
func (config *JWTConfig) defaultKeyFunc(t *jwt.Token) (interface{}, error) {
// Check the signing method
if t.Method.Alg() != config.SigningMethod {
return nil, fmt.Errorf("unexpected jwt signing method=%v", t.Header["alg"])
}
if len(config.SigningKeys) > 0 {
if kid, ok := t.Header["kid"].(string); ok {
if key, ok := config.SigningKeys[kid]; ok {
return key, nil
}
}
return nil, fmt.Errorf("unexpected jwt key id=%v", t.Header["kid"])
}
return config.SigningKey, nil
}