AxilJS JWT Authentication: Token Signing and Verification
Sign and verify JSON Web Tokens with AxilJS using HMAC-SHA256, expiration settings, and constant-time signature comparison.
JWT Authentication
AxilJS provides a JWT utility for signing and verifying JSON Web Tokens using HMAC-SHA256.
JWTs can be used to represent authenticated user information and securely transfer claims between your application components.
Setup
Import JWT from @axiljs/auth and initialize it with a secret.
The JWT secret should be at least 32 characters long. Store the secret securely in an environment variable rather than directly in application source code.
Sign a Token
Use jwt.sign() to create a signed JWT containing application claims.
The payload in this example contains:
sub— the subject identifier, representing the user ID.role— an application-specific authorization claim.expiresIn— controls how long the generated token remains valid.
The resulting token can be returned to an authenticated client and subsequently presented when accessing protected resources.
Verify a Token
Use jwt.verify() to verify a token and retrieve its payload.
Verification validates the token signature and returns the decoded payload when the token is valid.
Applications should perform JWT verification before trusting claims such as user identifiers or roles.
Token Expiration
AxilJS supports human-readable expiration formats as well as numeric seconds.
Supported examples include:
You can also provide the expiration as a number representing seconds.
For example:
Shorter expiration periods can be useful for tokens that should have a limited lifetime.
JWT Security
JWT signature verification uses constant-time comparison to reduce the risk of timing attacks.
Warning
Signature comparison uses constant-time comparison to prevent timing attacks.
Keep the JWT secret private and use a sufficiently strong secret in production. Never expose the signing secret to browser-side code or commit it to source control.