Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check if token expired in MiddlewareFunc #169

Merged
merged 10 commits into from
Sep 17, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,10 +155,11 @@ func main() {
})

auth := r.Group("/auth")
// Refresh time can be longer than token timeout
auth.GET("/refresh_token", authMiddleware.RefreshHandler)
auth.Use(authMiddleware.MiddlewareFunc())
{
auth.GET("/hello", helloHandler)
auth.GET("/refresh_token", authMiddleware.RefreshHandler)
}

if err := http.ListenAndServe(":"+port, r); err != nil {
Expand Down
9 changes: 7 additions & 2 deletions auth_jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ type GinJWTMiddleware struct {

// This field allows clients to refresh their token until MaxRefresh has passed.
// Note that clients can refresh their token in the last moment of MaxRefresh.
// This means that the maximum validity timespan for a token is MaxRefresh + Timeout.
// This means that the maximum validity timespan for a token is TokenTime + MaxRefresh.
// Optional, defaults to 0 meaning not refreshable.
MaxRefresh time.Duration

Expand Down Expand Up @@ -336,6 +336,11 @@ func (mw *GinJWTMiddleware) middlewareImpl(c *gin.Context) {
return
}

if int64(claims["exp"].(float64)) < mw.TimeFunc().Unix() {
mw.unauthorized(c, http.StatusUnauthorized, mw.HTTPStatusMessageFunc(ErrExpiredToken, c))
return
}

c.Set("JWT_PAYLOAD", claims)
identity := mw.IdentityHandler(c)

Expand Down Expand Up @@ -454,7 +459,7 @@ func (mw *GinJWTMiddleware) RefreshHandler(c *gin.Context) {
func (mw *GinJWTMiddleware) RefreshToken(c *gin.Context) (string, time.Time, error) {
claims, err := mw.CheckIfTokenExpire(c)
if err != nil {
return "", time.Now(), ErrExpiredToken
return "", time.Now(), err
a180285 marked this conversation as resolved.
Show resolved Hide resolved
}

// Create the token
Expand Down
55 changes: 54 additions & 1 deletion auth_jwt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,11 @@ func ginHandler(auth *GinJWTMiddleware) *gin.Engine {
r.POST("/login", auth.LoginHandler)

group := r.Group("/auth")
// Refresh time can be longer than token timeout
group.GET("/refresh_token", auth.RefreshHandler)
group.Use(auth.MiddlewareFunc())
{
group.GET("/hello", helloHandler)
group.GET("/refresh_token", auth.RefreshHandler)
}

return r
Expand Down Expand Up @@ -979,3 +980,55 @@ func TestSendAuthorizationBool(t *testing.T) {
assert.Equal(t, http.StatusOK, r.Code)
})
}

func TestExpiredTokenOnAuth(t *testing.T) {
// the middleware to test
authMiddleware, _ := New(&GinJWTMiddleware{
Realm: "test zone",
Key: key,
Timeout: time.Hour,
MaxRefresh: time.Hour * 24,
Authenticator: defaultAuthenticator,
SendAuthorization: true,
Authorizator: func(data interface{}, c *gin.Context) bool {
return data.(string) == "admin"
},
TimeFunc: func() time.Time {
return time.Now().AddDate(0, 0, 1)
},
})

handler := ginHandler(authMiddleware)

r := gofight.New()

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

func TestBadTokenOnRefreshHandler(t *testing.T) {
// the middleware to test
authMiddleware, _ := New(&GinJWTMiddleware{
Realm: "test zone",
Key: key,
Timeout: time.Hour,
Authenticator: defaultAuthenticator,
})

handler := ginHandler(authMiddleware)

r := gofight.New()

r.GET("/auth/refresh_token").
SetHeader(gofight.H{
"Authorization": "Bearer " + "BadToken",
}).
Run(handler, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
assert.Equal(t, http.StatusUnauthorized, r.Code)
})
}
3 changes: 2 additions & 1 deletion example/basic/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,11 @@ func main() {
})

auth := r.Group("/auth")
// Refresh time can be longer than token timeout
auth.GET("/refresh_token", authMiddleware.RefreshHandler)
auth.Use(authMiddleware.MiddlewareFunc())
{
auth.GET("/hello", helloHandler)
auth.GET("/refresh_token", authMiddleware.RefreshHandler)
}

if err := http.ListenAndServe(":"+port, r); err != nil {
Expand Down