Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Proposal: Implement Standard JWT fields #512

@RyoKusnadi

Description

@RyoKusnadi

Is your feature request related to a problem? Please describe.
In Auth TODO indicates missing standard JWT fields, and i think we can implement JWT Claims using field that stated in Here

Describe the solution you'd like
Add new fields to the existing TokenInfo struct using pointer types for optional values
maybe something like this

type TokenInfo struct {
    // Existing fields (unchanged)
    Scopes     []string
    Expiration time.Time
    Extra      map[string]any
    
    // New standard JWT fields
    Subject   *string    `json:"sub,omitempty"`   // Subject (user identifier)
    Issuer    *string    `json:"iss,omitempty"`   // Issuer (who issued the token)
    Audience  []string   `json:"aud,omitempty"`   // Audience (intended recipients)
    IssuedAt  *time.Time `json:"iat,omitempty"`   // Issued at time
    NotBefore *time.Time `json:"nbf,omitempty"`   // Not valid before time
    JWTID     *string    `json:"jti,omitempty"`   // JWT ID (unique identifier)
}

Still thinking the access pattern, might be something like below

tokenInfo := auth.TokenInfoFromContext(ctx)
if tokenInfo != nil {
    // Safe access with nil checks
    if tokenInfo.Subject != nil {
        userID := *tokenInfo.Subject
    }
    
    // Audience is a slice, can be checked for length
    if len(tokenInfo.Audience) > 0 {
        primaryAudience := tokenInfo.Audience[0]
    }
    
    // Time fields with nil checks
    if tokenInfo.IssuedAt != nil {
        issuedTime := *tokenInfo.IssuedAt
    }
}

Describe alternatives you've considered

  1. Using the existing Extra map
    Store JWT claims in TokenInfo.Extra as map[string]any
    Pros: No struct changes needed
    Cons: No type safety, requires type assertions, error-prone
  2. Create a separate JWTTokenInfo struct
    New struct that embeds TokenInfo with JWT fields
    Pros: Clean separation, no existing struct changes
    Cons: Breaking change, requires new context functions, fragments the API
  3. Add JWT claims as methods instead of fields
    Functions like GetSubject(), GetIssuer() that parse from Extra
    Pros: Backward compatible, encapsulated logic
    Cons: Performance overhead, still requires Extra map usage
    NB: Will taking https://github.com/golang-jwt/jwt/blob/main/claims.go#L13 as reference during development

Additional context
NA

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions