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).

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

ErrorTrigger Condition
ErrProcessorClosedProcessor is closed
ErrInvalidClaimsClaims validation failed
ErrRateLimitExceededRate limit threshold exceeded

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)

Validate

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

Validates a JWT access token and returns the parsed Claims.

Parameters

ParameterTypeDescription
tokenStringstringJWT string

Returns

ReturnTypeDescription
claimsClaimsParsed claims (value copy)
validboolWhether valid
errerrorError on validation failure

Errors

ErrorTrigger Condition
ErrProcessorClosedProcessor is closed
ErrEmptyTokenToken is empty
ErrInvalidTokenInvalid signature
ErrAlgorithmMismatchToken algorithm does not match config
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

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.

Parameters

ParameterTypeDescription
claimsCustomClaimsToken claims

Returns

ReturnTypeDescription
tokenstringSigned refresh token
errerrorError on validation or signing failure

Errors

ErrorTrigger Condition
ErrProcessorClosedProcessor is closed
ErrInvalidClaimsClaims validation failed
ErrRateLimitExceededRate limit threshold exceeded

Refresh

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

Refreshes an existing refresh token and returns a new access token. The refresh token is fully validated (signature, expiration, blacklist) before a new access token is issued; the original token's IssuedAt, ExpiresAt, and ID are reset and regenerated.

Token Type & Rotation

  • Token type check: Tokens with token_type=access are rejected (returns ErrTokenTypeMismatch) to prevent access tokens from being used to obtain new tokens; older tokens without a token_type are still accepted for backward compatibility.
  • Does not auto-revoke the original token: Refresh does not revoke the supplied refresh token. The original token remains valid until it expires or is explicitly Revoke()d. For one-time-use semantics, call Revoke(refreshTokenString) after a successful Refresh.

Security Note

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

Parameters

ParameterTypeDescription
refreshTokenStringstringRefresh token

Returns

ReturnTypeDescription
tokenstringNew access token
errerrorError on validation failure

Errors

ErrorTrigger Condition
ErrProcessorClosedProcessor is closed
ErrEmptyTokenToken is empty
ErrInvalidTokenInvalid signature
ErrAlgorithmMismatchToken algorithm does not match config
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
ErrTokenTypeMismatchRefreshing with an access token (token_type=access)
ErrRateLimitExceededRate limit threshold exceeded

ValidateInto

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

Validates a token and populates a custom Claims struct. Returns the same pointer as the input claims.

Parameters

ParameterTypeDescription
tokenStringstringJWT string
claimsCustomClaimsTarget Claims pointer

Returns

ReturnTypeDescription
claimsCustomClaimsPopulated Claims
validboolWhether valid
errerrorError on validation failure

Example

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

Errors

ErrorTrigger Condition
ErrProcessorClosedProcessor is closed
ErrEmptyTokenToken is empty
ErrInvalidTokenInvalid signature
ErrAlgorithmMismatchToken algorithm does not match config
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

RefreshInto

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

Refreshes a token using custom Claims. Timing fields (IssuedAt, ExpiresAt, ID) are automatically restored after the operation, even if an error or panic occurs.

Token Type Check

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

Security Note

Refresh only validates standard JWT fields and basic structural validity. Deep field constraints are not re-checked since they were validated at creation time.

Parameters

ParameterTypeDescription
refreshTokenStringstringRefresh token
claimsCustomClaimsTarget Claims pointer

Returns

ReturnTypeDescription
tokenstringNew access token
errerrorError on validation failure

Errors

ErrorTrigger Condition
ErrProcessorClosedProcessor is closed
ErrEmptyTokenToken is empty
ErrInvalidTokenInvalid signature
ErrAlgorithmMismatchToken algorithm does not match config
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
ErrTokenTypeMismatchRefreshing with an access token (token_type=access)
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.

TTL Behavior

  • The token's exp determines the TTL of the blacklist entry
  • Tokens without an exp default to a 7-day TTL
  • TTL is capped at 30 days to prevent forged excessive exp values from locking memory (DoS protection)
  • Expired tokens can still be revoked; the entry is automatically cleaned up by the blacklist

Parameters

ParameterTypeDescription
tokenStringstringToken to revoke

Returns

ReturnTypeDescription
errerrorError on revocation failure

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

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 status in the blacklist. When the blacklist is not configured, returns false and a nil error.

Parameters

ParameterTypeDescription
tokenStringstringJWT string

Returns

ReturnTypeDescription
revokedboolWhether revoked
errerrorError on query failure

Errors

ErrorTrigger Condition
ErrProcessorClosedProcessor is closed
ErrEmptyTokenToken is empty
ErrInvalidTokenInvalid signature or malformed token
ErrTokenInvalidIssuerIssuer mismatch
ErrTokenInvalidAudienceAudience mismatch
ErrTokenMissingIDToken missing jti field

ParseUnverified

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

Parses a token without verifying the signature. Useful for extracting Claims information without needing to trust the token.

Warning

The returned Claims are not verified and must not be trusted. Only use for debugging or logging.

Parameters

ParameterTypeDescription
tokenStringstringJWT string
claimsanyTarget Claims pointer

Returns

ReturnTypeDescription
errerrorError on parse failure

Errors

ErrorCondition
ErrProcessorClosedProcessor has been 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 securely clears keys. Can be called multiple times; subsequent calls return ErrProcessorClosed.

Returns

ReturnTypeDescription
errerrorError on close failure

IsClosed

go
func (p *Processor) IsClosed() bool

Checks if the Processor is closed.

Returns

ReturnTypeDescription
closedboolWhether closed