Skip to content

Commit

Permalink
support parse string of token. (#197)
Browse files Browse the repository at this point in the history
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
  • Loading branch information
appleboy authored Apr 9, 2019
1 parent f3e0d8e commit d4b5b81
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
16 changes: 15 additions & 1 deletion auth_jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,7 @@ func (mw *GinJWTMiddleware) jwtFromParam(c *gin.Context, key string) (string, er
return token, nil
}

// ParseToken parse jwt token
// ParseToken parse jwt token from gin context
func (mw *GinJWTMiddleware) ParseToken(c *gin.Context) (*jwt.Token, error) {
var token string
var err error
Expand Down Expand Up @@ -660,6 +660,20 @@ func (mw *GinJWTMiddleware) ParseToken(c *gin.Context) (*jwt.Token, error) {
})
}

// ParseTokenString parse jwt token string
func (mw *GinJWTMiddleware) ParseTokenString(token string) (*jwt.Token, error) {
return jwt.Parse(token, func(t *jwt.Token) (interface{}, error) {
if jwt.GetSigningMethod(mw.SigningAlgorithm) != t.Method {
return nil, ErrInvalidSigningAlgorithm
}
if mw.usingPublicKeyAlgo() {
return mw.pubKey, nil
}

return mw.Key, nil
})
}

func (mw *GinJWTMiddleware) unauthorized(c *gin.Context, code int, message string) {
c.Header("WWW-Authenticate", "JWT realm="+mw.Realm)
if !mw.DisabledAbort {
Expand Down
42 changes: 42 additions & 0 deletions auth_jwt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1140,3 +1140,45 @@ func TestExpiredField(t *testing.T) {
assert.Equal(t, http.StatusBadRequest, r.Code)
})
}

func TestCheckTokenString(t *testing.T) {
// the middleware to test
authMiddleware, _ := New(&GinJWTMiddleware{
Realm: "test zone",
Key: key,
Timeout: 1 * time.Second,
Authenticator: defaultAuthenticator,
Unauthorized: func(c *gin.Context, code int, message string) {
c.String(code, message)
},
})

handler := ginHandler(authMiddleware)

r := gofight.New()

userToken, _, _ := authMiddleware.TokenGenerator(MapClaims{
"identity": "admin",
})

r.GET("/auth/hello").
SetHeader(gofight.H{
"Authorization": "Bearer " + userToken,
}).
Run(handler, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
assert.Equal(t, http.StatusOK, r.Code)
})

time.Sleep(2 * time.Second)

r.GET("/auth/hello").
SetHeader(gofight.H{
"Authorization": "Bearer " + userToken,
}).
Run(handler, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
assert.Equal(t, http.StatusUnauthorized, r.Code)
})

_, err := authMiddleware.ParseTokenString(userToken)
assert.Error(t, err)
}

0 comments on commit d4b5b81

Please sign in to comment.