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"
|
2019-01-30 12:56:56 +02:00
|
|
|
"github.com/labstack/echo/v4"
|
2021-07-15 22:34:01 +02:00
|
|
|
"net/http"
|
2015-05-12 00:43:54 +02:00
|
|
|
)
|
|
|
|
|
2021-07-15 22:34:01 +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.
|
|
|
|
SuccessHandler JWTSuccessHandler
|
|
|
|
|
|
|
|
// ErrorHandler defines a function which is executed when all lookups have been done and none of them passed Validator
|
|
|
|
// function. ErrorHandler is executed with last missing (ErrExtractionValueMissing) or an invalid key.
|
|
|
|
// It may be used to define a custom JWT error.
|
|
|
|
//
|
|
|
|
// Note: when error handler swallows the error (returns nil) middleware continues handler chain execution towards handler.
|
|
|
|
// This is useful in cases when portion of your site/api is publicly accessible and has extra features for authorized users
|
|
|
|
// In that case you can use ErrorHandler to set default public JWT token value to request and continue with handler chain.
|
|
|
|
ErrorHandler JWTErrorHandlerWithContext
|
|
|
|
|
|
|
|
// Context key to store user information from the token into context.
|
|
|
|
// Optional. Default value "user".
|
|
|
|
ContextKey string
|
|
|
|
|
|
|
|
// TokenLookup is a string in the form of "<source>:<name>" or "<source>:<name>,<source>:<name>" that is used
|
|
|
|
// to extract token(s) from the request.
|
|
|
|
// Optional. Default value "header:Authorization:Bearer ".
|
|
|
|
// Possible values:
|
|
|
|
// - "header:<name>"
|
|
|
|
// - "query:<name>"
|
|
|
|
// - "param:<name>"
|
|
|
|
// - "cookie:<name>"
|
|
|
|
// - "form:<name>"
|
|
|
|
// Multiple sources example:
|
|
|
|
// - "header:Authorization,cookie:myowncookie"
|
|
|
|
TokenLookup string
|
|
|
|
|
|
|
|
// ParseTokenFunc defines a user-defined function that parses token from given auth. Returns an error when token
|
|
|
|
// parsing fails or parsed token is invalid.
|
|
|
|
// NB: could be called multiple times per request when token lookup is able to extract multiple token values (i.e. multiple Authorization headers)
|
|
|
|
// See `jwt_external_test.go` for example implementation using `github.com/golang-jwt/jwt` as JWT implementation library
|
|
|
|
ParseTokenFunc func(c echo.Context, auth string) (interface{}, error)
|
|
|
|
}
|
2021-06-06 20:36:41 +02:00
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
// JWTSuccessHandler defines a function which is executed for a valid token.
|
|
|
|
type JWTSuccessHandler func(c echo.Context)
|
2016-04-25 19:58:11 +02:00
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
// JWTErrorHandler defines a function which is executed for an invalid token.
|
|
|
|
type JWTErrorHandler func(err error) error
|
2018-06-29 03:13:02 +02:00
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
// JWTErrorHandlerWithContext is almost identical to JWTErrorHandler, but it's passed the current context.
|
|
|
|
type JWTErrorHandlerWithContext func(c echo.Context, err error) error
|
2018-06-29 03:13:02 +02:00
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
type valuesExtractor func(c echo.Context) ([]string, ExtractorType, error)
|
2020-01-25 19:48:53 +02:00
|
|
|
|
2016-04-25 19:58:11 +02:00
|
|
|
const (
|
2021-07-15 22:34:01 +02:00
|
|
|
// AlgorithmHS256 is token signing algorithm
|
2016-04-25 19:58:11 +02:00
|
|
|
AlgorithmHS256 = "HS256"
|
2015-05-12 00:43:54 +02:00
|
|
|
)
|
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
// ErrJWTMissing denotes an error raised when JWT token value could not be extracted from request
|
|
|
|
var ErrJWTMissing = echo.NewHTTPError(http.StatusUnauthorized, "missing or malformed jwt")
|
2017-08-31 18:18:42 +02:00
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
// ErrJWTInvalid denotes an error raised when JWT token value is invalid or expired
|
|
|
|
var ErrJWTInvalid = echo.NewHTTPError(http.StatusUnauthorized, "invalid or expired jwt")
|
|
|
|
|
|
|
|
// DefaultJWTConfig is the default JWT auth middleware config.
|
|
|
|
var DefaultJWTConfig = JWTConfig{
|
|
|
|
Skipper: DefaultSkipper,
|
|
|
|
ContextKey: "user",
|
|
|
|
TokenLookup: "header:" + echo.HeaderAuthorization + ":Bearer ",
|
|
|
|
}
|
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
|
2021-07-15 22:34:01 +02:00
|
|
|
func JWT(parseTokenFunc func(c echo.Context, auth string) (interface{}, error)) echo.MiddlewareFunc {
|
2016-05-07 16:45:03 +02:00
|
|
|
c := DefaultJWTConfig
|
2021-07-15 22:34:01 +02:00
|
|
|
c.ParseTokenFunc = parseTokenFunc
|
2016-05-07 16:45:03 +02:00
|
|
|
return JWTWithConfig(c)
|
2016-04-25 19:58:11 +02:00
|
|
|
}
|
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
// JWTWithConfig returns a JSON Web Token (JWT) auth middleware or panics if configuration is invalid.
|
|
|
|
//
|
|
|
|
// 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
|
2016-05-07 16:45:03 +02:00
|
|
|
func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
|
2021-07-15 22:34:01 +02:00
|
|
|
return toMiddlewareOrPanic(config)
|
|
|
|
}
|
|
|
|
|
|
|
|
// ToMiddleware converts JWTConfig to middleware or returns an error for invalid configuration
|
|
|
|
func (config JWTConfig) ToMiddleware() (echo.MiddlewareFunc, error) {
|
2016-07-27 18:34:44 +02:00
|
|
|
if config.Skipper == nil {
|
|
|
|
config.Skipper = DefaultJWTConfig.Skipper
|
|
|
|
}
|
2021-07-15 22:34:01 +02:00
|
|
|
if config.ParseTokenFunc == nil {
|
|
|
|
return nil, errors.New("echo jwt middleware requires parse token function")
|
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-05-27 04:23:46 +02:00
|
|
|
if config.TokenLookup == "" {
|
|
|
|
config.TokenLookup = DefaultJWTConfig.TokenLookup
|
2016-05-26 23:06:30 +02:00
|
|
|
}
|
2021-07-15 22:34:01 +02:00
|
|
|
extractors, err := createExtractors(config.TokenLookup)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("echo jwt middleware could not create token extractor: %w", err)
|
2021-06-06 20:36:41 +02:00
|
|
|
}
|
2021-07-15 22:34:01 +02:00
|
|
|
if len(extractors) == 0 {
|
|
|
|
return nil, errors.New("echo jwt middleware could not create extractors from TokenLookup string")
|
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)
|
|
|
|
}
|
2021-07-15 22:34:01 +02:00
|
|
|
var lastExtractorErr error
|
|
|
|
var lastTokenErr error
|
2021-05-08 21:30:06 +02:00
|
|
|
for _, extractor := range extractors {
|
2021-07-15 22:34:01 +02:00
|
|
|
auths, _, extrErr := extractor(c)
|
|
|
|
if extrErr != nil {
|
|
|
|
lastExtractorErr = extrErr
|
|
|
|
continue
|
2018-07-09 20:34:53 +02:00
|
|
|
}
|
2021-07-15 22:34:01 +02:00
|
|
|
for _, auth := range auths {
|
|
|
|
token, err := config.ParseTokenFunc(c, auth)
|
|
|
|
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-06-13 22:21:03 +02:00
|
|
|
}
|
2016-04-25 19:58:11 +02:00
|
|
|
}
|
2021-05-08 21:30:06 +02:00
|
|
|
|
2021-07-15 22:34:01 +02:00
|
|
|
// prioritize token errors over extracting errors
|
|
|
|
err := lastTokenErr
|
2021-06-06 20:36:41 +02:00
|
|
|
if err == nil {
|
2021-07-15 22:34:01 +02:00
|
|
|
err = lastExtractorErr
|
2016-04-25 19:58:11 +02:00
|
|
|
}
|
2018-06-29 03:13:02 +02:00
|
|
|
if config.ErrorHandler != nil {
|
2021-07-15 22:34:01 +02:00
|
|
|
if err == ErrExtractionValueMissing {
|
|
|
|
err = ErrJWTMissing
|
|
|
|
}
|
|
|
|
// Allow error handler to swallow the error and continue handler chain execution
|
|
|
|
// Useful in cases when portion of your site/api is publicly accessible and has extra features for authorized users
|
|
|
|
// In that case you can use ErrorHandler to set default public token to request and continue with handler chain
|
|
|
|
if handledErr := config.ErrorHandler(c, err); handledErr != nil {
|
|
|
|
return handledErr
|
|
|
|
}
|
|
|
|
return next(c)
|
2018-06-29 03:13:02 +02:00
|
|
|
}
|
2021-07-15 22:34:01 +02:00
|
|
|
if err == ErrExtractionValueMissing {
|
|
|
|
return ErrJWTMissing
|
2019-06-13 22:21:03 +02:00
|
|
|
}
|
2021-07-15 22:34:01 +02:00
|
|
|
// everything else goes under http.StatusUnauthorized to avoid exposing JWT internals with generic error
|
2017-08-31 19:16:34 +02:00
|
|
|
return &echo.HTTPError{
|
2020-08-28 00:35:45 +02:00
|
|
|
Code: ErrJWTInvalid.Code,
|
|
|
|
Message: ErrJWTInvalid.Message,
|
2018-04-10 21:06:31 +02:00
|
|
|
Internal: err,
|
2017-08-31 19:16:34 +02:00
|
|
|
}
|
2016-04-02 23:19:39 +02:00
|
|
|
}
|
2021-07-15 22:34:01 +02:00
|
|
|
}, nil
|
2020-12-01 08:51:20 +02:00
|
|
|
}
|