AxilJS Auth Middleware for JWT Token Verification
Protect AxilJS routes with JWT authentication middleware, extract bearer tokens from headers, cookies, or query parameters, and support optional authentication.
JWT Authentication Middleware
AxilJS provides the authenticate middleware for extracting and verifying JWT tokens from incoming HTTP requests.
The middleware uses an AxilJS JWT instance to validate authentication tokens and makes the authenticated user information available through req.locals.user.
It can read tokens from request headers, cookies, query parameters, or multiple sources.
Protect a Route
Pass your JWT instance to authenticate() to protect an HTTP route.
For an authenticated request, the verified JWT payload is available through:
This allows route handlers to access the authenticated user's claims after successful token verification.
Token Sources
AxilJS supports multiple JWT token sources.
Authorization Header
Use the header source to extract a bearer token from the Authorization header.
The expected request format is:
This is the conventional approach for APIs where clients send JWTs using HTTP authorization headers.
Cookie
Use the cookie source to read the token from a cookie named token.
The middleware expects the JWT to be provided through the token cookie.
Query Parameter
Use the query source to extract the JWT from the token query parameter.
The corresponding request format is:
Query-string authentication should generally be used only when the application's transport or integration requirements make it necessary, because URLs can be recorded by infrastructure such as logs and proxies.
Multiple Token Sources
You can configure more than one token source by providing an array.
This allows the middleware to support authentication tokens from both the Authorization header and the token cookie.
Optional Authentication
By default, authentication is required for a protected route.
You can make authentication optional with required: false.
With optional authentication, unauthenticated requests are allowed to continue and:
is undefined when no authenticated user is available.
This is useful for endpoints that provide different behavior for authenticated and unauthenticated users.
Authentication Flow
The middleware can be understood as the following request flow:
When multiple sources are configured, the middleware can use the configured authentication sources to locate the token before verification.
Common Authentication Patterns
A required bearer-token route:
A route supporting both headers and cookies:
An endpoint with optional authentication:
The same middleware can therefore support required authentication, optional authentication, and multiple token transport mechanisms.