Skip to content

Configuration ​

Config is the unified configuration entry point for CyberGo JWT. This page focuses on security and behavior configuration fields beyond signing algorithms; for signing keys and algorithm selection, see Signing Algorithms.

Configuration Overview ​

DefaultConfig() provides sensible defaults; setting the secret key is enough to get started:

FieldDefaultDescription
AccessTokenTTL15 minutesAccess token lifetime
RefreshTokenTTL7 daysRefresh token lifetime
Issuer"jwt-service"Written to iss claim and validated
SigningMethodHS256Signing algorithm
ClockSkew0Clock skew tolerance
RequireExpirationfalseWhether exp claim is required
RejectRefreshAsAccessfalseReject refresh tokens being used as access tokens (new in v1.2.3)
RotateRefreshTokensfalseAutomatically revoke the old refresh token on refresh for one-time rotation (new in v1.2.3)
ExpectedAudience"" (no check)Expected audience

normalizeConfig Auto-fill Rules ​

New() calls normalizeConfig before validation, filling zero-value fields with defaults. The table below lists each rule:

Zero-Value ConditionFilled DefaultTrigger
AccessTokenTTL == 015 minutesAlways
RefreshTokenTTL == 07 daysAlways
Issuer == """jwt-service"Always
SigningMethod == ""HS256Always
RateLimitRate == 0100Only when EnableRateLimit == true
RateLimitWindow == 01 minuteOnly when EnableRateLimit == true
Blacklist.MaxSize == 0100000Only for built-in storage (Store == nil)
Blacklist.CleanupInterval == 05 minutesOnly for built-in storage
Blacklist.EnableAutoCleanupForced trueBuilt-in storage is always on; the field itself only affects a custom Store

When Rate Limit Defaults Apply

The defaults for RateLimitRate and RateLimitWindow are filled only when EnableRateLimit is true. If EnableRateLimit is false (the default), rate limiting is not enabled and these two fields are ignored. See Rate Limiting.

Custom BlacklistStore Skips Auto-fill

When Blacklist.Store is not nil (custom storage backend), MaxSize and CleanupInterval are ignored and storage management becomes the backend's responsibility. EnableAutoCleanup only applies to a custom Store; built-in storage is always on and is forced to true during normalization to prevent unbounded memory growth.

Issuer and Audience Validation ​

Issuer ​

When Issuer is set, it is written to the iss claim during token creation and validated for consistency during verification:

go
cfg := jwt.DefaultConfig()
cfg.SecretKey = "hmac-key-that-has-at-least-32-bytes!"
cfg.Issuer = "my-app-v1" // Token will carry iss: "my-app-v1"

During validation, if the token's iss does not match the configured value, ErrTokenInvalidIssuer is returned.

The Library Fills Zero Values Only

The library fills zero values only: an iss/exp/iat/jti value set explicitly by the caller is used as-is, overriding the configuration and TTL. In the example above, if claims.RegisteredClaims.Issuer is already "other-app", the issue step does not write cfg.Issuer. Validation then fails on the issuer mismatch with ErrTokenInvalidIssuer, so the token fails its own verification. When standardizing the issuer, leave the Issuer field unset.

ExpectedAudience ​

When ExpectedAudience is set, validation checks that the token's aud claim contains this value:

go
package main

import (
    "fmt"

    "github.com/cybergodev/jwt"
)

func main() {
    cfg := jwt.DefaultConfig()
    cfg.SecretKey = "hmac-key-that-has-at-least-32-bytes!"
    cfg.ExpectedAudience = "billing-api"

    processor, err := jwt.New(cfg)
    if err != nil {
        panic(err)
    }
    defer processor.Close()

    // Token with matching audience
    claims := &jwt.Claims{
        UserID: "user1",
        RegisteredClaims: jwt.RegisteredClaims{
            Audience: jwt.StringOrSlice{"billing-api"},
        },
    }
    token, err := processor.Create(claims)
    if err != nil {
        panic(err)
    }

    _, err = processor.Parse(token)
    fmt.Println("Valid:", err == nil)
    // Output: Valid: true

    // Token with wrong audience is rejected
    wrongClaims := &jwt.Claims{
        UserID: "user2",
        RegisteredClaims: jwt.RegisteredClaims{
            Audience: jwt.StringOrSlice{"admin-api"},
        },
    }
    wrongToken, _ := processor.Create(wrongClaims)
    _, err = processor.Parse(wrongToken)
    fmt.Println("Wrong audience valid:", err == nil)
    // Output: Wrong audience valid: false
}

Multi-Service Scenarios

In a microservice architecture, give each service a different ExpectedAudience so a token issued by one service cannot be accepted by another, achieving inter-service token isolation.

Clock Skew ​

ClockSkew provides a tolerance window for exp (expiration) and nbf (not-before) validation, absorbing clock drift between the issuer and the validator. The skew applies symmetrically to both time claims:

  • exp direction: a token is considered expired only after exp + ClockSkew — relaxing expiration validation
  • nbf direction: a token is considered valid from nbf - ClockSkew — relaxing not-before validation
go
cfg := jwt.DefaultConfig()
cfg.SecretKey = "hmac-key-that-has-at-least-32-bytes!"
cfg.ClockSkew = 30 * time.Second // Tolerate 30 seconds of clock drift

Recommendation

In distributed systems, clock skew between servers can be several seconds. Setting ClockSkew = 30s ~ 60s is recommended. A zero value (default) means strict validation with no tolerance.

ClockSkew Impact on Token Validity ​

The table below shows the validity of a token with exp = 12:00:00 and nbf = 12:00:00 at various validation times when ClockSkew = 30s:

Validation TimeRelation to expRelation to nbfResult
11:59:20Not expirednbf - 40s (beyond skew)Invalid: ErrTokenNotValidYet
11:59:40Not expirednbf - 20s (within skew window)Valid
12:00:00Not expiredAt nbf momentValid
12:00:10exp + 10s (within skew window)Already validValid
12:00:40exp + 40s (beyond skew)Already validInvalid: ErrTokenExpired

Skew Only Relaxes, Never Tightens

ClockSkew only widens the acceptance window of a token; it never narrows the window of strict validation. A zero value is equivalent to RFC 7519's strict semantics: the token takes effect exactly at nbf and expires exactly at exp.

ClockSkew must not be negative — Config.Validate() returns ErrInvalidConfig.

Mandatory Expiration (RequireExpiration) ​

By default (RequireExpiration = false), tokens without an exp claim never expire. This is valid per RFC 7519 but can be a security concern in sensitive scenarios.

Setting RequireExpiration = true rejects tokens that lack an exp claim during validation:

go
cfg := jwt.DefaultConfig()
cfg.SecretKey = "hmac-key-that-has-at-least-32-bytes!"
cfg.RequireExpiration = true // Reject tokens without exp

Security Hardening

Tokens issued by this library always carry exp, derived from the TTL when the value is zero. RequireExpiration therefore mainly affects tokens from other issuers or legacy tokens that lack exp. Enabling it in production is recommended. The switch only checks whether exp exists; it does not judge whether the value is reasonable.

Token TTL Design ​

Access and refresh token TTLs should balance security and user experience for the deployment scenario:

ScenarioAccessTokenTTLRefreshTokenTTLNotes
High-security (finance, healthcare)5 minutes1 hourShort TTL limits exposure window
Web application15 minutes7 daysDefault, balances security and UX
Mobile app30 minutes30 daysLonger TTL reduces re-login
Internal service1 hour24 hoursHigher trust on internal networks

Constraint

Config.Validate() requires AccessTokenTTL < RefreshTokenTTL, and both must be positive.

TTL Applies Only to an Unset exp

The library fills zero values only: an iss/exp/iat/jti value set explicitly by the caller is used as-is, overriding the configuration and TTL. If ExpiresAt is set in the Claims (for example to one year from now), that value becomes the token lifetime, AccessTokenTTL no longer applies, and the TTL design above is bypassed. Business code should not assign ExpiresAt directly.

Configuration Validation Matrix ​

Config.Validate() runs inside New() after normalizeConfig and returns three categories of errors: ErrInvalidConfig, ErrInvalidSecretKey, and ErrInvalidSigningMethod.

Signing Key Validation (by Algorithm) ​

Algorithm FamilySigningKey RequirementVerificationKey (optional)
HMAC (HS256/384/512)SecretKey string ≥ 32 bytes + non-weak keyN/A (HMAC is symmetric)
RSA (RS/PS 256/384/512)*rsa.PrivateKey ≥ 2048 bits*rsa.PublicKey ≥ 2048 bits
ECDSA (ES256/384/512)*ecdsa.PrivateKey, curve matches algorithm*ecdsa.PublicKey

Purpose of VerificationKey

When VerificationKey is set, the public key is used for token verification instead of the private key — suitable for verify-only services (e.g., resource servers). When omitted, verification uses the private key from SigningKey. See Signing Algorithms.

Config.Validate() Complete Checks ​

CheckConditionReturned Error
Config pointernilErrInvalidConfig
HMAC key lengthSecretKey < 32 bytesErrInvalidSecretKey
HMAC key strengthWeak key (low entropy / low complexity)ErrInvalidSecretKey
RSA signing key typeNot *rsa.PrivateKeyErrInvalidSecretKey
RSA signing key strength< 2048 bitsErrInvalidSecretKey
RSA verification key typeNot *rsa.PublicKey (when set)ErrInvalidSecretKey
RSA verification key strength< 2048 bits (when set)ErrInvalidSecretKey
ECDSA signing key typeNot *ecdsa.PrivateKeyErrInvalidSecretKey
ECDSA curve matchCurve does not match algorithm (e.g., ES256 requires P-256)ErrInvalidSecretKey
ECDSA verification key typeNot *ecdsa.PublicKey (when set)ErrInvalidSecretKey
Signing algorithmNot one of the 12 built-in algorithmsErrInvalidSigningMethod
AccessTokenTTL<= 0ErrInvalidConfig
RefreshTokenTTL<= 0ErrInvalidConfig
TTL relationshipAccessTokenTTL >= RefreshTokenTTLErrInvalidConfig
ClockSkew< 0ErrInvalidConfig
Rate limit parameter signEnableRateLimit == true and RateLimitRate < 0 or RateLimitWindow < 0ErrInvalidConfig
RateLimitRate upper boundEnableRateLimit == true and RateLimitRate > 1000000ErrInvalidConfig
RateLimitWindow upper boundEnableRateLimit == true and RateLimitWindow > 30 daysErrInvalidConfig
Blacklist MaxSize<= 0 (built-in storage only)ErrInvalidConfig
Blacklist CleanupInterval<= 0 (built-in storage only)ErrInvalidConfig

Validation Order

Validate() checks the signing key first (returning ErrInvalidSecretKey or ErrInvalidSigningMethod), then TTL, ClockSkew, rate limit parameters, and Blacklist configuration (returning ErrInvalidConfig). If the key is invalid, later checks are skipped; fix the first error and test again.

What the Rate Limit Bounds Mean

When EnableRateLimit == true, rate limit parameters must be non-negative, the per-window count must not exceed 1000000, and the window must not exceed 30 days; otherwise New() returns ErrInvalidConfig. These limits surface configuration mistakes early. AllowN performs separate overflow protection internally. See Rate Limiting.

Input Validation and Security Hardening ​

CyberGo JWT applies multi-layer input validation to Claims fields, preventing injection attacks and abnormal data. Deep field validation runs only when a token is created. The verification path runs only Validate() for required fields and sanitizes standard-claim strings.

Field Constraints ​

ValidationLimitTriggered Error
String field length≤ 256 bytes after UTF-8 encoding (about 85 Chinese characters)ValidationError
Array size (permissions, scopes, audience)≤ 100 itemsValidationError
Extra field count≤ 50 fieldsValidationError
Extra value typesstring, []stringValidationError (nested maps rejected)

Length is measured in bytes: Go's len(string) returns the byte count, and one Chinese character takes 3 bytes in UTF-8. 85 Chinese characters (255 bytes) pass; 86 characters (258 bytes) are rejected.

Validated string fields include UserID, Username, Role, SessionID, ClientID, and the RegisteredClaims fields Issuer, Subject, ID, TokenType.

Injection Pattern Detection ​

The library includes 46 built-in dangerous pattern detections covering XSS, SQL injection, path traversal, and other attack vectors:

  • XSS: <script>, javascript:, onerror=, <iframe>, and other HTML/JS injection tags
  • SQL injection: drop table, union select, etc.
  • Path traversal: ../, /etc/passwd, file://
  • Control characters: ASCII < 32 except Tab (9), newline (10), carriage return (13)

When a dangerous pattern is detected, a ValidationError is returned with Field set to the field name and Message set to "suspicious pattern detected".

Handling Validation Errors ​

go
token, err := processor.Create(claims)
if err != nil {
    var ve *jwt.ValidationError
    if errors.As(err, &ve) {
        fmt.Printf("Field: %s, Reason: %s\n", ve.Field, ve.Message)
        // Field: UserID, Reason: suspicious pattern detected
    }
}

ValidationError implements Unwrap(), so errors.Is and errors.As can traverse the underlying error. On the Create path, a ValidationError from deep validation is wrapped by ErrInvalidClaims; on the verification path, a failed Validate() is wrapped the same way.

Custom Claims Validation

Custom fields of types implementing the CustomClaims interface are not deeply validated; implementers must handle them in Validate(). Deep field validation runs only when a token is created, and the verification path only calls Validate() for required fields and sanitizes standard-claim strings. A token that passed validation at creation is therefore not checked again for length or injection rules at parse time. See Custom Claims.

Next Steps ​