Skip to content

Commit

Permalink
feat: support ExtractClaimsFromToken func (#198)
Browse files Browse the repository at this point in the history
Signed-off-by: Bo-Yi Wu <[email protected]>
  • Loading branch information
appleboy authored Apr 9, 2019
1 parent 8e4bdc8 commit 633d983
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
14 changes: 14 additions & 0 deletions auth_jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -693,6 +693,20 @@ func ExtractClaims(c *gin.Context) MapClaims {
return claims.(MapClaims)
}

// ExtractClaimsFromToken help to extract the JWT claims from token
func ExtractClaimsFromToken(token *jwt.Token) MapClaims {
if token == nil {
return make(MapClaims)
}

claims := MapClaims{}
for key, value := range token.Claims.(jwt.MapClaims) {
claims[key] = value
}

return claims
}

// GetToken help to get the JWT token string
func GetToken(c *gin.Context) string {
token, exists := c.Get("JWT_TOKEN")
Expand Down
15 changes: 14 additions & 1 deletion auth_jwt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1151,6 +1151,13 @@ func TestCheckTokenString(t *testing.T) {
Unauthorized: func(c *gin.Context, code int, message string) {
c.String(code, message)
},
PayloadFunc: func(data interface{}) MapClaims {
if v, ok := data.(MapClaims); ok {
return v
}

return nil
},
})

handler := ginHandler(authMiddleware)
Expand All @@ -1169,6 +1176,11 @@ func TestCheckTokenString(t *testing.T) {
assert.Equal(t, http.StatusOK, r.Code)
})

token, err := authMiddleware.ParseTokenString(userToken)
assert.NoError(t, err)
claims := ExtractClaimsFromToken(token)
assert.Equal(t, "admin", claims["identity"])

time.Sleep(2 * time.Second)

r.GET("/auth/hello").
Expand All @@ -1179,6 +1191,7 @@ func TestCheckTokenString(t *testing.T) {
assert.Equal(t, http.StatusUnauthorized, r.Code)
})

_, err := authMiddleware.ParseTokenString(userToken)
_, err = authMiddleware.ParseTokenString(userToken)
assert.Error(t, err)
assert.Equal(t, MapClaims{}, ExtractClaimsFromToken(nil))
}

0 comments on commit 633d983

Please sign in to comment.