Skip to content

Processor ​

Processor is the core JWT operation type, implementing the TokenManager interface. All methods are concurrency-safe.

Create an instance via jwt.New(cfg).

Method Index ​

MethodDescription
Processor.CreateCreate an access token
Processor.CreateRefreshCreate a refresh token
Processor.ParseVerify and parse an access token (v1.2.3+)
Processor.ParseIntoVerify and populate custom Claims in place (v1.2.3+)
Processor.RefreshExchange a refresh token for a new access token
Processor.RefreshIntoRefresh with custom Claims
Processor.RevokeRevoke a token (blacklist it)
Processor.IsRevokedCheck whether a token has been revoked
Processor.ParseUnverifiedParse without signature verification (debug/logging only)
Processor.CloseRelease resources and clear key material
Processor.IsClosedCheck whether the processor is closed

The deprecated Validate / ValidateInto methods remain available; migrate to Parse / ParseInto respectively (see Migrating from Validate to Parse).

Nil Receiver Behavior

Every *Processor method returns ErrProcessorClosed on a nil receiver, and IsClosed returns true. A nil pointer never panics, but callers cannot distinguish "never initialized" from "already closed".

Common Errors ​

Parse, ParseInto, Refresh, and RefreshInto share one parsing and validation pipeline. The table below lists every error of that pipeline; each method section adds only its own specific errors and otherwise refers to this table.

ErrorTrigger Condition
ErrProcessorClosedProcessor is closed or nil
ErrEmptyTokenToken is empty
ErrInvalidTokenInvalid signature or malformed token
ErrAlgorithmMismatchToken algorithm does not match configuration
ErrExpirationRequiredRequireExpiration is enabled but the token lacks an exp claim
ErrTokenExpiredToken expired
ErrTokenNotValidYetToken not yet valid
ErrTokenInvalidIssuerIssuer mismatch
ErrTokenInvalidAudienceAudience mismatch
ErrTokenRevokedToken revoked
ErrInvalidClaimsClaims validation failed
ErrTokenTypeMismatchToken type does not fit the call site (see each method)
ErrStoreClosedBlacklist store is closed (returned while querying the blacklist)

The common errors of Create and CreateRefresh are only ErrProcessorClosed, ErrInvalidClaims, and ErrRateLimitExceeded.

Create ​

go
func (p *Processor) Create(claims CustomClaims) (string, error)

Creates a new JWT access token. Accepts any type implementing the CustomClaims interface.

Parameters ​

ParameterTypeDescription
claimsCustomClaimsToken claims

Returns ​

ReturnTypeDescription
tokenstringSigned JWT string
errerrorError on validation or signing failure

Errors ​

The error set is ErrProcessorClosed, ErrInvalidClaims, and ErrRateLimitExceeded.

Example ​

go
// Built-in Claims
claims := &jwt.Claims{UserID: "user123", Username: "alice"}
token, err := processor.Create(claims)

// Custom Claims
myClaims := &MyClaims{UserID: "123"}
token, err = processor.Create(myClaims)

Parse v1.2.3+ ​

go
func (p *Processor) Parse(tokenString string) (Claims, error)

Verifies a JWT access token and returns the parsed Claims (a value copy). A nil err means the token is valid — there is no separate boolean to check. Replaces the deprecated Validate.

Parameters ​

ParameterTypeDescription
tokenStringstringJWT string

Returns ​

ReturnTypeDescription
claimsClaimsParsed claims (value copy)
errerrorError on validation failure; nil means valid

Errors ​

The error set is the same as Common Errors.

Example ​

go
claims, err := processor.Parse(tokenString)
if err != nil {
    // Handle error
    return
}
fmt.Println(claims.UserID)

Validate ​

go
func (p *Processor) Validate(tokenString string) (Claims, bool, error)

Deprecated

Validate is deprecated since v1.2.3; use Parse instead. The boolean result valid is always equivalent to err == nil and carries no extra information.

Validates a JWT access token and returns the parsed Claims. Internally delegates directly to Parse.

The only difference from Parse is the return values: one extra bool, always equal to err == nil. Parameters and the error set are identical.

Migrating from Validate to Parse ​

Drop the boolean check and test err directly.

go
// Old style (deprecated)
parsed, valid, err := processor.Validate(token)
if valid {
    // ...
}

// New style: nil err means valid
parsed, err := processor.Parse(token)
if err != nil {
    // Handle error
}

Parameters ​

Same as Parse: tokenString string.

Returns ​

ReturnTypeDescription
claimsClaimsParsed claims (value copy)
validboolWhether valid (always equal to err == nil)
errerrorError on validation failure

Errors ​

The error set is the same as Common Errors.

Example ​

go
claims, valid, err := processor.Validate(tokenString)
if err != nil {
    // Handle error
    return
}
if valid {
    fmt.Println(claims.UserID)
}

CreateRefresh ​

go
func (p *Processor) CreateRefresh(claims CustomClaims) (string, error)

Creates a refresh token using RefreshTokenTTL instead of AccessTokenTTL. Claims validation follows the same rules as Create.

Parameters ​

ParameterTypeDescription
claimsCustomClaimsToken claims

Returns ​

ReturnTypeDescription
tokenstringSigned refresh token
errerrorError on validation or signing failure

Errors ​

The error set matches Create: ErrProcessorClosed, ErrInvalidClaims, ErrRateLimitExceeded.


Refresh ​

go
func (p *Processor) Refresh(refreshTokenString string) (string, error)

Exchanges a refresh token for a new access token. The refresh token is fully validated first (signature, expiration, blacklist); once it passes, a new access token is issued. The original token's IssuedAt, ExpiresAt, and ID are reset and regenerated.

Two Constraints for Custom Claims

  • Refresh rebuilds the token from the built-in Claims type. When the supplied refresh token carries a custom type, every custom field is discarded and the new token keeps only the registered claims. To preserve business fields, use RefreshInto.
  • Validation against the built-in Claims requires the refresh token to carry UserID or Username. A refresh token with only Subject returns invalid claims: user_id or username is required.

Token Type & Rotation

  • Token type check: tokens with token_type=access are rejected with ErrTokenTypeMismatch. Older tokens without token_type are still accepted for backward compatibility.
  • The original token is not revoked by default: Refresh does not revoke the supplied refresh token. It stays valid until it expires or is explicitly Revoke()d. For one-time-use semantics, enable Config.RotateRefreshTokens. See Token Refresh & Rotation for the authoritative description.

Security Note

Refresh validates only the standard JWT fields (exp, nbf, iss, aud, blacklist) and basic structural validity. Deep field constraints (length limits, injection patterns) are not re-checked because they were validated at creation time.

Parameters ​

ParameterTypeDescription
refreshTokenStringstringRefresh token

Returns ​

ReturnTypeDescription
tokenstringNew access token
errerrorError on validation failure

Errors ​

Beyond Common Errors, Refresh has these specific errors:

ErrorTrigger Condition
ErrTokenTypeMismatchRefreshing with an access token (token_type=access)
ErrTokenMissingIDRotateRefreshTokens is enabled but the refresh token lacks a jti claim
ErrBlacklistNotConfiguredRotateRefreshTokens is enabled but the blacklist is not configured
ErrRefreshRotationFailedThe underlying blacklist store returned an error while RotateRefreshTokens is enabled
ErrRateLimitExceededRate limit threshold exceeded

ParseInto v1.2.3+ ​

go
func (p *Processor) ParseInto(tokenString string, claims CustomClaims) (CustomClaims, error)

Verifies a token and populates the provided custom Claims struct in place; on success it returns the same pointer that was passed in. A nil err means the token is valid. Unlike Parse, which returns a value copy, this fills the caller-supplied struct directly.

Claims state on error

On validation failure the supplied claims may be partially populated and must not be used.

Parameters ​

ParameterTypeDescription
tokenStringstringJWT string
claimsCustomClaimsTarget Claims pointer

Returns ​

ReturnTypeDescription
claimsCustomClaimsPopulated Claims (same pointer as the input)
errerrorError on validation failure; nil means valid

Errors ​

The error set is the same as Common Errors.

Example ​

go
myClaims := &MyClaims{}
result, err := processor.ParseInto(tokenString, myClaims)
if err != nil {
    // Handle error
    return
}
fmt.Println(result.(*MyClaims).UserID)

ValidateInto ​

go
func (p *Processor) ValidateInto(tokenString string, claims CustomClaims) (CustomClaims, bool, error)

Deprecated

ValidateInto is deprecated since v1.2.3; use ParseInto instead. The boolean result is as redundant as in Validate, and the migration is the same.

Validates a token and populates a custom Claims struct. Internally delegates directly to ParseInto.

The only difference from ParseInto is the return values: one extra bool, always equal to err == nil. Parameters and the error set are identical.

Parameters ​

Same as ParseInto: tokenString string and claims CustomClaims.

Returns ​

ReturnTypeDescription
claimsCustomClaimsPopulated Claims
validboolWhether valid (always equal to err == nil)
errerrorError on validation failure

Migrating from ValidateInto to ParseInto ​

go
// Old style (deprecated)
result, valid, err := processor.ValidateInto(tokenString, myClaims)
if valid {
    fmt.Println(result.(*MyClaims).UserID)
}

// New style: nil err means valid
result, err := processor.ParseInto(tokenString, myClaims)
if err != nil {
    // Handle error
    return
}
fmt.Println(result.(*MyClaims).UserID)

Errors ​

The error set is the same as Common Errors.


RefreshInto ​

go
func (p *Processor) RefreshInto(refreshTokenString string, claims CustomClaims) (string, error)

Refreshes a token using custom Claims. The Claims object's timing fields (IssuedAt, ExpiresAt, ID) are restored after the operation, even on error or panic. Custom fields are preserved in the new token.

Custom Claims types must use this method rather than Refresh, which rebuilds the token from the built-in Claims and drops custom fields.

Token Type Check

Tokens with token_type=access are rejected (returns ErrTokenTypeMismatch) to prevent access tokens from being exchanged for new tokens; older tokens without a token_type are still accepted for backward compatibility.

Security Note

Refresh validates only the standard JWT fields (exp, nbf, iss, aud, blacklist) and basic structural validity. Deep field constraints (length limits, injection patterns) are not re-checked because they were validated at creation time.

Parameters ​

ParameterTypeDescription
refreshTokenStringstringRefresh token
claimsCustomClaimsTarget Claims pointer

Returns ​

ReturnTypeDescription
tokenstringNew access token
errerrorError on validation failure

Errors ​

Beyond Common Errors, RefreshInto has these specific errors:

ErrorTrigger Condition
ErrTokenTypeMismatchRefreshing with an access token (token_type=access)
ErrTokenMissingIDRotateRefreshTokens is enabled but the refresh token lacks a jti claim
ErrBlacklistNotConfiguredRotateRefreshTokens is enabled but the blacklist is not configured
ErrRefreshRotationFailedThe underlying blacklist store returned an error while RotateRefreshTokens is enabled
ErrRateLimitExceededRate limit threshold exceeded

Revoke ​

go
func (p *Processor) Revoke(tokenString string) error

Adds the token to the blacklist by verifying the signature and extracting the token ID (jti). Only tokens with a valid signature can be revoked, preventing malicious callers from adding arbitrary token IDs to the blacklist.

Blacklist Entry TTL

An entry lives for the token's remaining lifetime, clamped to a 7-day floor and a 30-day cap. The floor keeps revocations of short-lived tokens from disappearing too early; the cap stops an oversized exp from occupying storage long-term.

Estimate capacity as peak revocation volume × entry lifetime: ordinary access tokens take the 7-day floor, while long-TTL refresh tokens take their remaining lifetime (up to the 30-day cap). Tokens without an exp or already expired are treated as the 7-day floor. Expired tokens can still be revoked; the entry is removed by blacklist cleanup.

Built-in Store Saturation

When the built-in store is full, expired entries are removed first, roughly the earliest-expiring 10% is then evicted, and the new entry is written directly — Add never fails because the store is full.

The cost is fail-open: revocation records dropped by eviction silently stop taking effect, and those tokens become usable again. Raising MaxSize lowers the fail-open probability.

Parameters ​

ParameterTypeDescription
tokenStringstringToken to revoke

Returns ​

ReturnTypeDescription
errerrorError on validation failure or when the blacklist store is closed

Errors ​

Revoke verifies only the signature, issuer, audience, and jti; it does not check exp/nbf, so it never returns expiration errors.

ErrorTrigger Condition
ErrProcessorClosedProcessor is closed
ErrEmptyTokenToken is empty
ErrBlacklistNotConfiguredBlacklist not configured
ErrInvalidTokenInvalid signature or malformed token
ErrTokenInvalidIssuerIssuer mismatch
ErrTokenInvalidAudienceAudience mismatch
ErrTokenMissingIDToken missing jti field
ErrStoreClosedBlacklist store is closed

IsRevoked ​

go
func (p *Processor) IsRevoked(tokenString string) (bool, error)

Checks whether a token has been revoked. After verifying the signature it looks up the token's jti in the blacklist. When the blacklist is not configured it returns false and nil.

As with Revoke, this method does not check exp/nbf.

Parameters ​

ParameterTypeDescription
tokenStringstringJWT string

Returns ​

ReturnTypeDescription
revokedboolWhether revoked
errerrorError on query failure

Errors ​

The error set matches Revoke, except that an unconfigured blacklist returns false and nil instead of ErrBlacklistNotConfigured.


ParseUnverified ​

go
func (p *Processor) ParseUnverified(tokenString string, claims any) error

Parses a token without verifying the signature. Useful for extracting Claims information in scenarios that do not require trust.

WARNING

The returned Claims are not verified and must not be trusted. Use only for debugging or logging.

Parameters ​

ParameterTypeDescription
tokenStringstringJWT string
claimsanyTarget Claims pointer

Returns ​

ReturnTypeDescription
errerrorError on parse failure

Errors ​

ErrorTrigger Condition
ErrProcessorClosedProcessor is closed
ErrEmptyTokenToken is empty
Wrapped errorReturns a wrapped parse error on malformed tokens (not a sentinel error; cannot be matched with errors.Is)

Close ​

go
func (p *Processor) Close() error

Releases resources and clears key material, and closes the internal rate limiter and blacklist store. Can be called multiple times; the second and later calls return ErrProcessorClosed.

What gets cleared depends on the algorithm:

  • HMAC: the copied key bytes are zeroed and the process-wide HMAC hasher pool is drained. The pool is package-global, so this also invalidates cached hashers of other live processors — they rebuild transparently on next use, with no correctness impact and only a one-time performance cost.
  • Asymmetric: only the references to SigningKey / VerificationKey are dropped; the caller-owned *rsa.PrivateKey / *ecdsa.PrivateKey is not overwritten. Destroying that key object remains the caller's responsibility.

Close waits for in-flight operations to finish by acquiring the write lock.

Returns ​

ReturnTypeDescription
errerrorError on close failure

IsClosed ​

go
func (p *Processor) IsClosed() bool

Checks if the Processor is closed.

Returns ​

ReturnTypeDescription
closedboolWhether closed