mirror of
https://github.com/labstack/echo.git
synced 2025-11-29 22:48:07 +02:00
Custom jwt errors (#999)
* Custom error for jwt * New field `inner` in HTTPError to store error from external dependency Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
@@ -1,7 +1,6 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"reflect"
|
||||
@@ -57,6 +56,11 @@ const (
|
||||
AlgorithmHS256 = "HS256"
|
||||
)
|
||||
|
||||
// Errors
|
||||
var (
|
||||
ErrJWTInvalid = echo.NewHTTPError(http.StatusBadRequest, "Missing or invalid jwt")
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultJWTConfig is the default JWT auth middleware config.
|
||||
DefaultJWTConfig = JWTConfig{
|
||||
@@ -134,7 +138,7 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
|
||||
|
||||
auth, err := extractor(c)
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
|
||||
return err
|
||||
}
|
||||
token := new(jwt.Token)
|
||||
// Issue #647, #656
|
||||
@@ -150,7 +154,9 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
|
||||
c.Set(config.ContextKey, token)
|
||||
return next(c)
|
||||
}
|
||||
return echo.ErrUnauthorized
|
||||
he := echo.NewHTTPError(http.StatusUnauthorized, "Invalid or expired jwt")
|
||||
he.Inner = err
|
||||
return he
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -163,7 +169,7 @@ func jwtFromHeader(header string, authScheme string) jwtExtractor {
|
||||
if len(auth) > l+1 && auth[:l] == authScheme {
|
||||
return auth[l+1:], nil
|
||||
}
|
||||
return "", errors.New("Missing or invalid jwt in the request header")
|
||||
return "", ErrJWTInvalid
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,7 +178,7 @@ func jwtFromQuery(param string) jwtExtractor {
|
||||
return func(c echo.Context) (string, error) {
|
||||
token := c.QueryParam(param)
|
||||
if token == "" {
|
||||
return "", errors.New("Missing jwt in the query string")
|
||||
return "", ErrJWTInvalid
|
||||
}
|
||||
return token, nil
|
||||
}
|
||||
@@ -183,7 +189,7 @@ func jwtFromCookie(name string) jwtExtractor {
|
||||
return func(c echo.Context) (string, error) {
|
||||
cookie, err := c.Cookie(name)
|
||||
if err != nil {
|
||||
return "", errors.New("Missing jwt in the cookie")
|
||||
return "", ErrJWTInvalid
|
||||
}
|
||||
return cookie.Value, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user