1
0
mirror of https://github.com/labstack/echo.git synced 2025-07-13 01:30:31 +02:00

Dropped custom error handler for jwt, closes #589, closes ##591

Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana
2016-08-27 10:52:35 -07:00
2 changed files with 172 additions and 57 deletions

View File

@ -38,6 +38,7 @@ type (
// Possible values: // Possible values:
// - "header:<name>" // - "header:<name>"
// - "query:<name>" // - "query:<name>"
// - "cookie:<name>"
TokenLookup string `json:"token_lookup"` TokenLookup string `json:"token_lookup"`
} }
@ -67,10 +68,11 @@ var (
// JWT returns a JSON Web Token (JWT) auth middleware. // JWT returns a JSON Web Token (JWT) auth middleware.
// //
// For valid token, it sets the user in context and calls next handler. // For valid token, it sets the user in context and calls next handler.
// For invalid token, it sends "401 - Unauthorized" response. // For invalid token, it returns "401 - Unauthorized" error.
// For empty or invalid `Authorization` header, it sends "400 - Bad Request". // For empty or invalid `Authorization` header, it sends "400 - Bad Request".
// //
// See: https://jwt.io/introduction // See: https://jwt.io/introduction
// See `JWTConfig.TokenLookup`
func JWT(key []byte) echo.MiddlewareFunc { func JWT(key []byte) echo.MiddlewareFunc {
c := DefaultJWTConfig c := DefaultJWTConfig
c.SigningKey = key c.SigningKey = key
@ -93,12 +95,12 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
if config.ContextKey == "" { if config.ContextKey == "" {
config.ContextKey = DefaultJWTConfig.ContextKey config.ContextKey = DefaultJWTConfig.ContextKey
} }
if config.TokenLookup == "" {
config.TokenLookup = DefaultJWTConfig.TokenLookup
}
if config.Claims == nil { if config.Claims == nil {
config.Claims = DefaultJWTConfig.Claims config.Claims = DefaultJWTConfig.Claims
} }
if config.TokenLookup == "" {
config.TokenLookup = DefaultJWTConfig.TokenLookup
}
// Initialize // Initialize
parts := strings.Split(config.TokenLookup, ":") parts := strings.Split(config.TokenLookup, ":")
@ -106,6 +108,8 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
switch parts[0] { switch parts[0] {
case "query": case "query":
extractor = jwtFromQuery(parts[1]) extractor = jwtFromQuery(parts[1])
case "cookie":
extractor = jwtFromCookie(parts[1])
} }
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {
@ -136,8 +140,7 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
} }
} }
// jwtFromHeader returns a `jwtExtractor` that extracts token from the provided // jwtFromHeader returns a `jwtExtractor` that extracts token from request header.
// request header.
func jwtFromHeader(header string) jwtExtractor { func jwtFromHeader(header string) jwtExtractor {
return func(c echo.Context) (string, error) { return func(c echo.Context) (string, error) {
auth := c.Request().Header().Get(header) auth := c.Request().Header().Get(header)
@ -145,18 +148,29 @@ func jwtFromHeader(header string) jwtExtractor {
if len(auth) > l+1 && auth[:l] == bearer { if len(auth) > l+1 && auth[:l] == bearer {
return auth[l+1:], nil return auth[l+1:], nil
} }
return "", errors.New("empty or invalid jwt in authorization header") return "", errors.New("empty or invalid jwt in request header")
} }
} }
// jwtFromQuery returns a `jwtExtractor` that extracts token from the provided query // jwtFromQuery returns a `jwtExtractor` that extracts token from query string.
// parameter.
func jwtFromQuery(param string) jwtExtractor { func jwtFromQuery(param string) jwtExtractor {
return func(c echo.Context) (string, error) { return func(c echo.Context) (string, error) {
token := c.QueryParam(param) token := c.QueryParam(param)
var err error
if token == "" { if token == "" {
return "", errors.New("empty jwt in query param") return "", errors.New("empty jwt in query string")
} }
return token, nil return token, err
}
}
// jwtFromCookie returns a `jwtExtractor` that extracts token from named cookie.
func jwtFromCookie(name string) jwtExtractor {
return func(c echo.Context) (string, error) {
cookie, err := c.Cookie(name)
if err != nil {
return "", errors.New("empty jwt in cookie")
}
return cookie.Value(), nil
} }
} }

View File

@ -24,59 +24,160 @@ type jwtCustomClaims struct {
func TestJWT(t *testing.T) { func TestJWT(t *testing.T) {
e := echo.New() e := echo.New()
req := test.NewRequest(echo.GET, "/", nil)
res := test.NewResponseRecorder()
c := e.NewContext(req, res)
handler := func(c echo.Context) error { handler := func(c echo.Context) error {
return c.String(http.StatusOK, "test") return c.String(http.StatusOK, "test")
} }
config := JWTConfig{}
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ" token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
validKey := []byte("secret")
invalidKey := []byte("invalid-key")
validAuth := bearer + " " + token
// No signing key provided for _, tc := range []struct {
assert.Panics(t, func() { expPanic bool
JWTWithConfig(config) expErrCode int // 0 for Success
}) config JWTConfig
reqURL string // "/" if empty
hdrAuth string
hdrCookie string // test.Request doesn't provide SetCookie(); use name=val
info string
}{
{expPanic: true, info: "No signing key provided"},
{
expErrCode: http.StatusBadRequest,
config: JWTConfig{
SigningKey: validKey,
SigningMethod: "RS256",
},
info: "Unexpected signing method",
},
{
expErrCode: http.StatusUnauthorized,
hdrAuth: validAuth,
config: JWTConfig{SigningKey: invalidKey},
info: "Invalid key",
},
{
hdrAuth: validAuth,
config: JWTConfig{SigningKey: validKey},
info: "Valid JWT",
},
{
hdrAuth: validAuth,
config: JWTConfig{
Claims: &jwtCustomClaims{},
SigningKey: []byte("secret"),
},
info: "Valid JWT with custom claims",
},
{
hdrAuth: "invalid-auth",
expErrCode: http.StatusBadRequest,
config: JWTConfig{SigningKey: validKey},
info: "Invalid Authorization header",
},
{
config: JWTConfig{SigningKey: validKey},
expErrCode: http.StatusBadRequest,
info: "Empty header auth field",
},
{
config: JWTConfig{
SigningKey: validKey,
TokenLookup: "query:jwt",
},
reqURL: "/?a=b&jwt=" + token,
info: "Valid query method",
},
{
config: JWTConfig{
SigningKey: validKey,
TokenLookup: "query:jwt",
},
reqURL: "/?a=b&jwtxyz=" + token,
expErrCode: http.StatusBadRequest,
info: "Invalid query param name",
},
{
config: JWTConfig{
SigningKey: validKey,
TokenLookup: "query:jwt",
},
reqURL: "/?a=b&jwt=invalid-token",
expErrCode: http.StatusUnauthorized,
info: "Invalid query param value",
},
{
config: JWTConfig{
SigningKey: validKey,
TokenLookup: "query:jwt",
},
reqURL: "/?a=b",
expErrCode: http.StatusBadRequest,
info: "Empty query",
},
{
config: JWTConfig{
SigningKey: validKey,
TokenLookup: "cookie:jwt",
},
hdrCookie: "jwt=" + token,
info: "Valid cookie method",
},
{
config: JWTConfig{
SigningKey: validKey,
TokenLookup: "cookie:jwt",
},
expErrCode: http.StatusUnauthorized,
hdrCookie: "jwt=invalid",
info: "Invalid token with cookie method",
},
{
config: JWTConfig{
SigningKey: validKey,
TokenLookup: "cookie:jwt",
},
expErrCode: http.StatusBadRequest,
info: "Empty cookie",
},
} {
// Unexpected signing method if tc.reqURL == "" {
config.SigningKey = []byte("secret") tc.reqURL = "/"
config.SigningMethod = "RS256" }
h := JWTWithConfig(config)(handler)
he := h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusBadRequest, he.Code)
// Invalid key req := test.NewRequest(echo.GET, tc.reqURL, nil)
auth := bearer + " " + token res := test.NewResponseRecorder()
req.Header().Set(echo.HeaderAuthorization, auth) req.Header().Set(echo.HeaderAuthorization, tc.hdrAuth)
config.SigningKey = []byte("invalid-key") req.Header().Set(echo.HeaderCookie, tc.hdrCookie)
h = JWTWithConfig(config)(handler) c := e.NewContext(req, res)
he = h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusUnauthorized, he.Code)
// Valid JWT if tc.expPanic {
h = JWT([]byte("secret"))(handler) assert.Panics(t, func() {
if assert.NoError(t, h(c)) { JWTWithConfig(tc.config)
user := c.Get("user").(*jwt.Token) }, tc.info)
claims := user.Claims.(jwt.MapClaims) continue
assert.Equal(t, claims["name"], "John Doe") }
if tc.expErrCode != 0 {
h := JWTWithConfig(tc.config)(handler)
he := h(c).(*echo.HTTPError)
assert.Equal(t, tc.expErrCode, he.Code, tc.info)
continue
}
h := JWTWithConfig(tc.config)(handler)
if assert.NoError(t, h(c), tc.info) {
user := c.Get("user").(*jwt.Token)
switch claims := user.Claims.(type) {
case jwt.MapClaims:
assert.Equal(t, claims["name"], "John Doe", tc.info)
case *jwtCustomClaims:
assert.Equal(t, claims.Name, "John Doe")
assert.Equal(t, claims.Admin, true)
default:
panic("unexpected type of claims")
}
}
} }
// Valid JWT with custom claims
config = JWTConfig{
Claims: &jwtCustomClaims{},
SigningKey: []byte("secret"),
}
h = JWTWithConfig(config)(handler)
if assert.NoError(t, h(c)) {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(*jwtCustomClaims)
assert.Equal(t, claims.Name, "John Doe")
assert.Equal(t, claims.Admin, true)
}
// Invalid Authorization header
req.Header().Set(echo.HeaderAuthorization, "invalid-auth")
h = JWT([]byte("secret"))(handler)
he = h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusBadRequest, he.Code)
} }