diff --git a/auth_jwt.go b/auth_jwt.go index 838fbc5..39b163b 100644 --- a/auth_jwt.go +++ b/auth_jwt.go @@ -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 @@ -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 { diff --git a/auth_jwt_test.go b/auth_jwt_test.go index 0ce76ed..e4de976 100644 --- a/auth_jwt_test.go +++ b/auth_jwt_test.go @@ -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) +}