2024-03-09 11:21:24 +02:00
|
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
|
|
|
|
|
2022-01-24 22:03:45 +02:00
|
|
|
//go:build go1.15
|
2021-08-01 10:12:23 +02:00
|
|
|
// +build go1.15
|
|
|
|
|
2015-05-12 00:43:54 +02:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2021-06-06 20:36:41 +02:00
|
|
|
"errors"
|
2016-04-25 19:58:11 +02:00
|
|
|
"fmt"
|
2021-08-01 10:12:23 +02:00
|
|
|
"github.com/golang-jwt/jwt"
|
2019-01-30 12:56:56 +02:00
|
|
|
"github.com/labstack/echo/v4"
|
2022-01-24 22:03:45 +02:00
|
|
|
"net/http"
|
|
|
|
"reflect"
|
2015-05-12 00:43:54 +02:00
|
|
|
)
|
|
|
|
|
2024-03-09 17:53:07 +02:00
|
|
|
// JWTConfig defines the config for JWT middleware.
|
|
|
|
type JWTConfig struct {
|
|
|
|
// Skipper defines a function to skip middleware.
|
|
|
|
Skipper Skipper
|
|
|
|
|
|
|
|
// BeforeFunc defines a function which is executed just before the middleware.
|
|
|
|
BeforeFunc BeforeFunc
|
|
|
|
|
|
|
|
// 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
|
|
|
|
|
|
|
|
// ErrorHandlerWithContext is almost identical to ErrorHandler, but it's passed the current context.
|
|
|
|
ErrorHandlerWithContext JWTErrorHandlerWithContext
|
|
|
|
|
|
|
|
// 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
|
|
|
|
|
|
|
|
// 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.
|
|
|
|
SigningKey interface{}
|
|
|
|
|
|
|
|
// Map of signing keys to validate token with kid field usage.
|
|
|
|
// 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.
|
|
|
|
SigningKeys map[string]interface{}
|
|
|
|
|
|
|
|
// Signing method used to check the token's signing algorithm.
|
|
|
|
// Optional. Default value HS256.
|
|
|
|
SigningMethod string
|
|
|
|
|
|
|
|
// Context key to store user information from the token into context.
|
|
|
|
// Optional. Default value "user".
|
|
|
|
ContextKey string
|
|
|
|
|
|
|
|
// Claims are extendable claims data defining token content. Used by default ParseTokenFunc implementation.
|
|
|
|
// Not used if custom ParseTokenFunc is set.
|
|
|
|
// Optional. Default value jwt.MapClaims
|
|
|
|
Claims jwt.Claims
|
|
|
|
|
|
|
|
// TokenLookup is a string in the form of "<source>:<name>" or "<source>:<name>,<source>:<name>" that is used
|
|
|
|
// to extract token from the request.
|
|
|
|
// Optional. Default value "header:Authorization".
|
|
|
|
// Possible values:
|
|
|
|
// - "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.
|
|
|
|
// - "query:<name>"
|
|
|
|
// - "param:<name>"
|
|
|
|
// - "cookie:<name>"
|
|
|
|
// - "form:<name>"
|
|
|
|
// Multiple sources example:
|
|
|
|
// - "header:Authorization,cookie:myowncookie"
|
|
|
|
TokenLookup string
|
|
|
|
|
|
|
|
// 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
|
|
|
|
|
|
|
|
// AuthScheme to be used in the Authorization header.
|
|
|
|
// Optional. Default value "Bearer".
|
|
|
|
AuthScheme string
|
|
|
|
|
|
|
|
// 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.
|
|
|
|
// Used by default ParseTokenFunc implementation.
|
|
|
|
//
|
|
|
|
// 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.
|
|
|
|
// Not used if custom ParseTokenFunc is set.
|
|
|
|
// Default to an internal implementation verifying the signing algorithm and selecting the proper key.
|
|
|
|
KeyFunc jwt.Keyfunc
|
|
|
|
|
|
|
|
// 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
|
|
|
|
ParseTokenFunc func(auth string, c echo.Context) (interface{}, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
// JWTSuccessHandler defines a function which is executed for a valid token.
|
|
|
|
type JWTSuccessHandler func(c echo.Context)
|
|
|
|
|
|
|
|
// JWTErrorHandler defines a function which is executed for an invalid token.
|
|
|
|
type JWTErrorHandler func(err error) error
|
|
|
|
|
|
|
|
// JWTErrorHandlerWithContext is almost identical to JWTErrorHandler, but it's passed the current context.
|
|
|
|
type JWTErrorHandlerWithContext func(err error, c echo.Context) error
|
2015-05-12 00:43:54 +02:00
|
|
|
|
2016-12-09 19:05:40 +02:00
|
|
|
// Algorithms
|
2016-04-25 19:58:11 +02:00
|
|
|
const (
|
|
|
|
AlgorithmHS256 = "HS256"
|
2015-05-12 00:43:54 +02:00
|
|
|
)
|
|
|
|
|
2024-03-09 17:53:07 +02:00
|
|
|
// ErrJWTMissing is error that is returned when no JWToken was extracted from the request.
|
|
|
|
var ErrJWTMissing = echo.NewHTTPError(http.StatusBadRequest, "missing or malformed jwt")
|
|
|
|
|
|
|
|
// ErrJWTInvalid is error that is returned when middleware could not parse JWT correctly.
|
|
|
|
var ErrJWTInvalid = echo.NewHTTPError(http.StatusUnauthorized, "invalid or expired jwt")
|
|
|
|
|
|
|
|
// DefaultJWTConfig is the default JWT auth middleware config.
|
|
|
|
var DefaultJWTConfig = JWTConfig{
|
|
|
|
Skipper: DefaultSkipper,
|
|
|
|
SigningMethod: AlgorithmHS256,
|
|
|
|
ContextKey: "user",
|
|
|
|
TokenLookup: "header:" + echo.HeaderAuthorization,
|
|
|
|
TokenLookupFuncs: nil,
|
|
|
|
AuthScheme: "Bearer",
|
|
|
|
Claims: jwt.MapClaims{},
|
|
|
|
KeyFunc: nil,
|
|
|
|
}
|
2016-03-14 22:55:38 +02:00
|
|
|
|
2016-05-07 16:45:03 +02:00
|
|
|
// JWT returns a JSON Web Token (JWT) auth middleware.
|
2016-04-25 19:58:11 +02:00
|
|
|
//
|
|
|
|
// For valid token, it sets the user in context and calls next handler.
|
2016-08-27 19:52:35 +02:00
|
|
|
// For invalid token, it returns "401 - Unauthorized" error.
|
2017-01-03 06:12:06 +02:00
|
|
|
// For missing token, it returns "400 - Bad Request" error.
|
2016-04-25 19:58:11 +02:00
|
|
|
//
|
2016-05-13 02:45:00 +02:00
|
|
|
// See: https://jwt.io/introduction
|
2016-07-02 11:26:05 +02:00
|
|
|
// See `JWTConfig.TokenLookup`
|
2022-12-27 21:08:37 +02:00
|
|
|
//
|
|
|
|
// Deprecated: Please use https://github.com/labstack/echo-jwt instead
|
2017-06-20 00:42:27 +02:00
|
|
|
func JWT(key interface{}) echo.MiddlewareFunc {
|
2016-05-07 16:45:03 +02:00
|
|
|
c := DefaultJWTConfig
|
2016-04-25 19:58:11 +02:00
|
|
|
c.SigningKey = key
|
2016-05-07 16:45:03 +02:00
|
|
|
return JWTWithConfig(c)
|
2016-04-25 19:58:11 +02:00
|
|
|
}
|
|
|
|
|
2016-09-01 05:10:14 +02:00
|
|
|
// JWTWithConfig returns a JWT auth middleware with config.
|
2016-05-13 02:45:00 +02:00
|
|
|
// See: `JWT()`.
|
2022-12-27 21:08:37 +02:00
|
|
|
//
|
|
|
|
// Deprecated: Please use https://github.com/labstack/echo-jwt instead
|
2016-05-07 16:45:03 +02:00
|
|
|
func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
|
2016-04-25 19:58:11 +02:00
|
|
|
// Defaults
|
2016-07-27 18:34:44 +02:00
|
|
|
if config.Skipper == nil {
|
|
|
|
config.Skipper = DefaultJWTConfig.Skipper
|
|
|
|
}
|
2021-06-06 20:36:41 +02:00
|
|
|
if config.SigningKey == nil && len(config.SigningKeys) == 0 && config.KeyFunc == nil && config.ParseTokenFunc == nil {
|
2017-06-03 02:55:59 +02:00
|
|
|
panic("echo: jwt middleware requires signing key")
|
2016-04-25 19:58:11 +02:00
|
|
|
}
|
|
|
|
if config.SigningMethod == "" {
|
2016-05-07 16:45:03 +02:00
|
|
|
config.SigningMethod = DefaultJWTConfig.SigningMethod
|
2016-04-25 19:58:11 +02:00
|
|
|
}
|
|
|
|
if config.ContextKey == "" {
|
2016-05-07 16:45:03 +02:00
|
|
|
config.ContextKey = DefaultJWTConfig.ContextKey
|
2016-04-25 19:58:11 +02:00
|
|
|
}
|
2016-08-20 17:59:36 +02:00
|
|
|
if config.Claims == nil {
|
2016-09-15 00:35:10 +02:00
|
|
|
config.Claims = DefaultJWTConfig.Claims
|
2016-08-20 17:59:36 +02:00
|
|
|
}
|
2021-08-19 15:00:07 +02:00
|
|
|
if config.TokenLookup == "" && len(config.TokenLookupFuncs) == 0 {
|
2016-05-27 04:23:46 +02:00
|
|
|
config.TokenLookup = DefaultJWTConfig.TokenLookup
|
2016-05-26 23:06:30 +02:00
|
|
|
}
|
2017-01-03 06:12:06 +02:00
|
|
|
if config.AuthScheme == "" {
|
|
|
|
config.AuthScheme = DefaultJWTConfig.AuthScheme
|
|
|
|
}
|
2021-05-08 21:19:24 +02:00
|
|
|
if config.KeyFunc == nil {
|
|
|
|
config.KeyFunc = config.defaultKeyFunc
|
2016-09-15 00:35:10 +02:00
|
|
|
}
|
2021-06-06 20:36:41 +02:00
|
|
|
if config.ParseTokenFunc == nil {
|
|
|
|
config.ParseTokenFunc = config.defaultParseToken
|
|
|
|
}
|
2016-05-26 23:06:30 +02:00
|
|
|
|
2023-02-21 12:20:30 +02:00
|
|
|
extractors, cErr := createExtractors(config.TokenLookup, config.AuthScheme)
|
|
|
|
if cErr != nil {
|
|
|
|
panic(cErr)
|
2022-01-24 22:03:45 +02:00
|
|
|
}
|
|
|
|
if len(config.TokenLookupFuncs) > 0 {
|
|
|
|
extractors = append(config.TokenLookupFuncs, extractors...)
|
2016-04-25 19:58:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
|
|
|
return func(c echo.Context) error {
|
2016-07-27 18:34:44 +02:00
|
|
|
if config.Skipper(c) {
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
|
2018-06-29 03:13:02 +02:00
|
|
|
if config.BeforeFunc != nil {
|
|
|
|
config.BeforeFunc(c)
|
|
|
|
}
|
2022-01-24 22:03:45 +02:00
|
|
|
|
|
|
|
var lastExtractorErr error
|
|
|
|
var lastTokenErr error
|
2021-05-08 21:30:06 +02:00
|
|
|
for _, extractor := range extractors {
|
2022-01-24 22:03:45 +02:00
|
|
|
auths, err := extractor(c)
|
|
|
|
if err != nil {
|
|
|
|
lastExtractorErr = ErrJWTMissing // backwards compatibility: all extraction errors are same (unlike KeyAuth)
|
|
|
|
continue
|
2021-05-08 21:30:06 +02:00
|
|
|
}
|
2022-01-24 22:03:45 +02: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)
|
2018-07-09 20:34:53 +02:00
|
|
|
}
|
2016-04-25 19:58:11 +02:00
|
|
|
}
|
2022-01-24 22:03:45 +02: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
|
2016-04-25 19:58:11 +02:00
|
|
|
}
|
2018-06-29 03:13:02 +02:00
|
|
|
if config.ErrorHandler != nil {
|
2018-07-18 08:21:54 +02:00
|
|
|
return config.ErrorHandler(err)
|
2018-06-29 03:13:02 +02:00
|
|
|
}
|
2019-06-13 22:21:03 +02:00
|
|
|
if config.ErrorHandlerWithContext != nil {
|
2022-01-24 22:03:45 +02:00
|
|
|
tmpErr := config.ErrorHandlerWithContext(err, c)
|
|
|
|
if config.ContinueOnIgnoredError && tmpErr == nil {
|
|
|
|
return next(c)
|
|
|
|
}
|
|
|
|
return tmpErr
|
2019-06-13 22:21:03 +02:00
|
|
|
}
|
2022-01-24 22:03:45 +02:00
|
|
|
|
|
|
|
// backwards compatible errors codes
|
|
|
|
if lastTokenErr != nil {
|
|
|
|
return &echo.HTTPError{
|
|
|
|
Code: ErrJWTInvalid.Code,
|
|
|
|
Message: ErrJWTInvalid.Message,
|
|
|
|
Internal: err,
|
|
|
|
}
|
2017-08-31 19:16:34 +02:00
|
|
|
}
|
2022-01-24 22:03:45 +02:00
|
|
|
return err // this is lastExtractorErr value
|
2016-04-02 23:19:39 +02:00
|
|
|
}
|
2016-02-18 07:49:31 +02:00
|
|
|
}
|
2015-06-10 05:06:51 +02:00
|
|
|
}
|
2016-04-25 22:41:09 +02:00
|
|
|
|
2021-06-06 20:36:41 +02:00
|
|
|
func (config *JWTConfig) defaultParseToken(auth string, c echo.Context) (interface{}, error) {
|
2022-11-21 16:05:30 +02:00
|
|
|
var token *jwt.Token
|
2021-06-06 20:36:41 +02:00
|
|
|
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-08 21:19:24 +02: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
|
|
|
|
}
|