gin-jwt icon indicating copy to clipboard operation
gin-jwt copied to clipboard

missing system fields?

Open neee333ko opened this issue 2 months ago • 1 comments

// generateAccessToken method that clients can use to get a jwt token.
func (mw *GinJWTMiddleware) generateAccessToken(data any) (string, time.Time, error) {
	// 1. Validate signing algorithm
	signingMethod := jwt.GetSigningMethod(mw.SigningAlgorithm)
	if signingMethod == nil {
		return "", time.Time{}, ErrInvalidSigningAlgorithm
	}

	token := jwt.New(signingMethod)
	claims, ok := token.Claims.(jwt.MapClaims)
	if !ok {
		return "", time.Time{}, ErrFailedTokenCreation
	}

	// 2. Define reserved claims to prevent PayloadFunc from overwriting system fields
	reservedClaims := map[string]bool{
		"exp": true, "iat": true, "nbf": true, "iss": true,
		"aud": true, "sub": true, "jti": true, "orig_iat": true,
	}

	// 3. Safely add custom payload, avoiding system field overwrites
	if mw.PayloadFunc != nil {
		for key, value := range mw.PayloadFunc(data) {
			if !reservedClaims[key] {
				claims[key] = value
			}
		}
	}

	// 4. Calculate expiration time using original data instead of claims
	expire := mw.TimeFunc().Add(mw.TimeoutFunc(data))

	// 5. Set required system claims
	now := mw.TimeFunc()
	claims[mw.ExpField] = expire.Unix()
	claims["orig_iat"] = now.Unix()

	// 6. Sign the token
	tokenString, err := mw.signedString(token)
	if err != nil {
		return "", time.Time{}, err
	}

	return tokenString, expire, nil
}

In the v3 of this repo, when I check the payload setting, I found that except exp field and orig_iat field, other system fields are not filled? If I set these fields in PayloadFunc, they will not be filled because of reservedClaims. Please tell me if you know something more.

neee333ko avatar Nov 08 '25 04:11 neee333ko

I will take it.

appleboy avatar Dec 03 '25 15:12 appleboy

I'd like to +1 on this. It doesn't seem like many of these reserved fields are used.

For example, I am interested in passing along the user_id of the current session in the sub field, as the user is the Subject of the JWT Session Token in my context.

I agree that orig_iat should remain a reserved claim, as it is used by the framework for its own purposes, but I'm not sure whether iss, aud, sub or maybe even exp should also be. For me at least it nudges me towards using non-standard claims for purposes which are already covered by standardised claims from IANA

Alex-D-TC avatar Dec 13 '25 19:12 Alex-D-TC

Try https://github.com/appleboy/gin-jwt/releases/tag/v3.3.0

appleboy avatar Dec 14 '25 04:12 appleboy