Skip to content

Commit

Permalink
feat: add custom ExpField (#340)
Browse files Browse the repository at this point in the history
  • Loading branch information
RightFS authored Dec 28, 2024
1 parent 72b2ef1 commit 405da24
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions auth_jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,9 @@ type GinJWTMiddleware struct {

// ParseOptions allow to modify jwt's parser methods
ParseOptions []jwt.ParserOption

// Default vaule is "exp"
ExpField string
}

var (
Expand Down Expand Up @@ -402,6 +405,10 @@ func (mw *GinJWTMiddleware) MiddlewareInit() error {
mw.CookieName = "jwt"
}

if mw.ExpField == "" {
mw.ExpField = "exp"
}

// bypass other key settings if KeyFunc is set
if mw.KeyFunc != nil {
return nil
Expand All @@ -414,6 +421,7 @@ func (mw *GinJWTMiddleware) MiddlewareInit() error {
if mw.Key == nil {
return ErrMissingSecretKey
}

return nil
}

Expand All @@ -431,7 +439,7 @@ func (mw *GinJWTMiddleware) middlewareImpl(c *gin.Context) {
return
}

switch v := claims["exp"].(type) {
switch v := claims[mw.ExpField].(type) {
case nil:
mw.unauthorized(c, http.StatusBadRequest, mw.HTTPStatusMessageFunc(ErrMissingExpField, c))
return
Expand Down Expand Up @@ -517,7 +525,7 @@ func (mw *GinJWTMiddleware) LoginHandler(c *gin.Context) {
}

expire := mw.TimeFunc().Add(mw.TimeoutFunc(claims))
claims["exp"] = expire.Unix()
claims[mw.ExpField] = expire.Unix()
claims["orig_iat"] = mw.TimeFunc().Unix()
tokenString, err := mw.signedString(token)
if err != nil {
Expand Down Expand Up @@ -592,7 +600,7 @@ func (mw *GinJWTMiddleware) RefreshToken(c *gin.Context) (string, time.Time, err
}

expire := mw.TimeFunc().Add(mw.TimeoutFunc(claims))
newClaims["exp"] = expire.Unix()
newClaims[mw.ExpField] = expire.Unix()
newClaims["orig_iat"] = mw.TimeFunc().Unix()
tokenString, err := mw.signedString(newToken)
if err != nil {
Expand Down Expand Up @@ -642,7 +650,7 @@ func (mw *GinJWTMiddleware) TokenGenerator(data interface{}) (string, time.Time,
}

expire := mw.TimeFunc().Add(mw.TimeoutFunc(claims))
claims["exp"] = expire.Unix()
claims[mw.ExpField] = expire.Unix()
claims["orig_iat"] = mw.TimeFunc().Unix()
tokenString, err := mw.signedString(token)
if err != nil {
Expand Down

0 comments on commit 405da24

Please sign in to comment.