1
0
mirror of https://github.com/labstack/echo.git synced 2024-12-24 20:14: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
commit bc7b992d23
2 changed files with 172 additions and 57 deletions

View File

@ -38,6 +38,7 @@ type (
// Possible values:
// - "header:<name>"
// - "query:<name>"
// - "cookie:<name>"
TokenLookup string `json:"token_lookup"`
}
@ -67,10 +68,11 @@ var (
// 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 sends "401 - Unauthorized" response.
// For invalid token, it returns "401 - Unauthorized" error.
// For empty or invalid `Authorization` header, it sends "400 - Bad Request".
//
// See: https://jwt.io/introduction
// See `JWTConfig.TokenLookup`
func JWT(key []byte) echo.MiddlewareFunc {
c := DefaultJWTConfig
c.SigningKey = key
@ -93,12 +95,12 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
if config.ContextKey == "" {
config.ContextKey = DefaultJWTConfig.ContextKey
}
if config.TokenLookup == "" {
config.TokenLookup = DefaultJWTConfig.TokenLookup
}
if config.Claims == nil {
config.Claims = DefaultJWTConfig.Claims
}
if config.TokenLookup == "" {
config.TokenLookup = DefaultJWTConfig.TokenLookup
}
// Initialize
parts := strings.Split(config.TokenLookup, ":")
@ -106,6 +108,8 @@ func JWTWithConfig(config JWTConfig) echo.MiddlewareFunc {
switch parts[0] {
case "query":
extractor = jwtFromQuery(parts[1])
case "cookie":
extractor = jwtFromCookie(parts[1])
}
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
// request header.
// jwtFromHeader returns a `jwtExtractor` that extracts token from request header.
func jwtFromHeader(header string) jwtExtractor {
return func(c echo.Context) (string, error) {
auth := c.Request().Header().Get(header)
@ -145,18 +148,29 @@ func jwtFromHeader(header string) jwtExtractor {
if len(auth) > l+1 && auth[:l] == bearer {
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
// parameter.
// jwtFromQuery returns a `jwtExtractor` that extracts token from query string.
func jwtFromQuery(param string) jwtExtractor {
return func(c echo.Context) (string, error) {
token := c.QueryParam(param)
var err error
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) {
e := echo.New()
req := test.NewRequest(echo.GET, "/", nil)
res := test.NewResponseRecorder()
c := e.NewContext(req, res)
handler := func(c echo.Context) error {
return c.String(http.StatusOK, "test")
}
config := JWTConfig{}
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
validKey := []byte("secret")
invalidKey := []byte("invalid-key")
validAuth := bearer + " " + token
// No signing key provided
assert.Panics(t, func() {
JWTWithConfig(config)
})
for _, tc := range []struct {
expPanic bool
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
config.SigningKey = []byte("secret")
config.SigningMethod = "RS256"
h := JWTWithConfig(config)(handler)
he := h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusBadRequest, he.Code)
if tc.reqURL == "" {
tc.reqURL = "/"
}
// Invalid key
auth := bearer + " " + token
req.Header().Set(echo.HeaderAuthorization, auth)
config.SigningKey = []byte("invalid-key")
h = JWTWithConfig(config)(handler)
he = h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusUnauthorized, he.Code)
req := test.NewRequest(echo.GET, tc.reqURL, nil)
res := test.NewResponseRecorder()
req.Header().Set(echo.HeaderAuthorization, tc.hdrAuth)
req.Header().Set(echo.HeaderCookie, tc.hdrCookie)
c := e.NewContext(req, res)
// Valid JWT
h = JWT([]byte("secret"))(handler)
if assert.NoError(t, h(c)) {
user := c.Get("user").(*jwt.Token)
claims := user.Claims.(jwt.MapClaims)
assert.Equal(t, claims["name"], "John Doe")
if tc.expPanic {
assert.Panics(t, func() {
JWTWithConfig(tc.config)
}, tc.info)
continue
}
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)
}