1
0
mirror of https://github.com/labstack/echo.git synced 2024-12-24 20:14:31 +02:00
Signed-off-by: Vishal Rana <vr@labstack.com>
This commit is contained in:
Vishal Rana 2016-04-26 02:10:57 -07:00
parent 13648d06f3
commit fb8690d42b
2 changed files with 8 additions and 8 deletions

View File

@ -23,7 +23,7 @@ type (
JWTAuthConfig struct {
// SigningKey is the key to validate token.
// Required.
SigningKey string
SigningKey []byte
// SigningMethod is used to check token signing method.
// Optional, with default value as `HS256`.
@ -114,7 +114,7 @@ func BasicAuthWithConfig(config BasicAuthConfig) echo.MiddlewareFunc {
// For empty or invalid `Authorization` header, it sends "400 - Bad Request".
//
// See https://jwt.io/introduction
func JWTAuth(key string) echo.MiddlewareFunc {
func JWTAuth(key []byte) echo.MiddlewareFunc {
c := DefaultJWTAuthConfig
c.SigningKey = key
return JWTAuthWithConfig(c)
@ -124,7 +124,7 @@ func JWTAuth(key string) echo.MiddlewareFunc {
// See `JWTAuth()`.
func JWTAuthWithConfig(config JWTAuthConfig) echo.MiddlewareFunc {
// Defaults
if config.SigningKey == "" {
if config.SigningKey == nil {
panic("jwt middleware requires signing key")
}
if config.SigningMethod == "" {
@ -148,7 +148,7 @@ func JWTAuthWithConfig(config JWTAuthConfig) echo.MiddlewareFunc {
if t.Method.Alg() != config.SigningMethod {
return nil, fmt.Errorf("unexpected jwt signing method=%v", t.Header["alg"])
}
return []byte(config.SigningKey), nil
return config.SigningKey, nil
})
if err == nil && token.Valid {

View File

@ -67,7 +67,7 @@ func TestJWTAuth(t *testing.T) {
})
// Unexpected signing method
config.SigningKey = "secret"
config.SigningKey = []byte("secret")
config.SigningMethod = "RS256"
h := JWTAuthWithConfig(config)(handler)
he := h(c).(*echo.HTTPError)
@ -76,13 +76,13 @@ func TestJWTAuth(t *testing.T) {
// Invalid key
auth := bearer + " " + token
req.Header().Set(echo.HeaderAuthorization, auth)
config.SigningKey = "invalid-key"
config.SigningKey = []byte("invalid-key")
h = JWTAuthWithConfig(config)(handler)
he = h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusUnauthorized, he.Code)
// Valid JWT
h = JWTAuth("secret")(handler)
h = JWTAuth([]byte("secret"))(handler)
if assert.NoError(t, h(c)) {
user := c.Get("user").(*jwt.Token)
assert.Equal(t, user.Claims["name"], "John Doe")
@ -90,7 +90,7 @@ func TestJWTAuth(t *testing.T) {
// Invalid Authorization header
req.Header().Set(echo.HeaderAuthorization, "invalid-auth")
h = JWTAuth("secret")(handler)
h = JWTAuth([]byte("secret"))(handler)
he = h(c).(*echo.HTTPError)
assert.Equal(t, http.StatusBadRequest, he.Code)
}