jwtauth http middleware package provides a simple way to verify a JWT token from a http request and send the result down the request context (
jwtauth works with any Go http router, but resides under the go-chi group for maintenance and organization – its only 3rd party dependency is the underlying jwt library “github.com/dgrijalva/jwt-go”.
This package uses the new
context package in Go 1.7 stdlib and net/http#Request.Context to pass values between handler chains.
In a complete JWT-authentication flow, you’ll first capture the token from a http request, decode it, verify it and then validate that its correctly signed and hasn’t expired – the
jwtauth.Verifier middleware handler takes care of all of that. The
jwtauth.Verifier will set the context values on keys
Next, it’s up to an authentication handler to respond or continue processing after the
jwtauth.Authenticator middleware responds with a 401 Unauthorized plain-text payload for all unverified tokens and passes the good ones through. You can also copy the Authenticator and customize it to handle invalid tokens to better fit your flow (ie. with a JSON error response body).
Verifier will search for a JWT token in a http request, in the order:
- ‘jwt’ URI query parameter
- ‘Authorization: BEARER T’ request header
- Cookie ‘jwt’ value
- (optional), use
jwtauth.Verify("state")for additional query/cookie parameter aliases
The first JWT string that is found as a query parameter, authorization header or cookie header is then decoded by the
jwt-go library and a *jwt.Token object is set on the request context. In the case of a signature decoding error the Verifier will also set the error on the request context.
The Verifier always calls the next http handler in sequence, which can either be the generic
jwtauth.Authenticatormiddleware or your own custom handler which checks the request context jwt token and error to prepare a custom http response.