Skip to main content

JWT

JWT extracts a token, parses it, validates it, and stores the token and claims on the Zinc context.

Quick start

app.Use(middleware.JWT(func(_ *zinc.Context, token *jwt.Token) (any, error) {
return signingKey, nil
}))

Default extraction

By default Zinc reads bearer tokens from the Authorization header.

Authorization: Bearer <token>

Extractor helpers

  • JWTFromAuthHeader("Bearer")
  • JWTFromHeader(name)
  • JWTFromHeaderPrefix(name, prefix)
  • JWTFromCookie(name)
  • JWTFromQuery(name)
  • JWTFromFirst(extractors...)

Config fields

FieldMeaning
SkipperSkip auth for selected requests
ExtractorCustom token source
NewClaimsConstruct the claims value before parsing
KeyFuncResolve the verification key for a token
ParseTokenFuncReplace Zinc's parser entirely
ParserOptionsForward parser options to jwt/v5
ValidateRun custom post-parse validation
SuccessHandlerOverride the success path
ErrorHandlerOverride unauthorized handling
RealmUsed in the WWW-Authenticate challenge

Typed claims

type Claims struct {
Role string `json:"role"`
jwt.RegisteredClaims
}

app.Use(middleware.JWTWithConfig(middleware.JWTConfig{
NewClaims: func(*zinc.Context) jwt.Claims {
return &Claims{}
},
KeyFunc: func(_ *zinc.Context, token *jwt.Token) (any, error) {
return signingKey, nil
},
}))

Then in a handler:

claims, ok := middleware.JWTClaims[*Claims](c)
token, ok := middleware.JWTToken(c)
raw, ok := middleware.JWTTokenString(c)

Failure behavior

When validation fails, Zinc sets a WWW-Authenticate: Bearer ... challenge automatically unless you override ErrorHandler.

Malformed tokens are treated differently from missing tokens so you can distinguish:

  • missing credentials
  • malformed credentials
  • invalid credentials

When to customize ParseTokenFunc

Use ParseTokenFunc only when Zinc's normal KeyFunc + NewClaims path is too small for your needs. Most apps should stick to the standard config flow.