How jwtauth middleware works
masterThe jwtauth package uses a two-step middleware pattern to handle JWT authentication:
jwtauth.Verifier: This middleware extracts the token from the request, decodes it, verifies the signature, and validates expiration. It then injects the resultingjwt.Tokenand any potential errors into the request context using the keysjwtauth.TokenCtxKeyandjwtauth.ErrorCtxKey. TheVerifieralways calls the next handler in the chain.Authentication Handler: Since the
Verifieralways continues the chain, you must use a second handler to decide how to respond to the user.- Use
jwtauth.Authenticatorfor a default behavior that returns a401 Unauthorizedplain-text response for invalid tokens and allows valid tokens to proceed. - Implement a custom handler if you need specific response formats (e.g., JSON error bodies).
- Use
By default, the Verifier looks for tokens in this order:
Authorization: BEARER <token>headerjwtCookie value
r.Use(jwtauth.Verifier(tokenAuth))
r.Use(jwtauth.Authenticator(tokenAuth))