Secure Token Handling
The @archibald/auth package uses JSON Web Encryption (JWE) to secure the user's session. JWE is a standard for encrypting content (in this case, the user's session data) to ensure its confidentiality.
What is JWE?
JWE is a compact, URL-safe means of representing encrypted content using JSON-based data structures. It consists of five parts:
- Header: Contains information about the encryption algorithm.
- Encrypted Key: The encrypted content encryption key.
- Initialization Vector: The initialization vector used for encryption.
- Ciphertext: The encrypted content.
- Authentication Tag: Used to verify the integrity of the encrypted content.
How Archibald Uses JWE
When a user logs in, the Archibald backend creates a JWE token that contains the user's session data. This token is then sent to the client and stored securely (e.g., in an HTTP-only cookie).
On subsequent requests, the client sends the JWE token back to the backend. The backend then decrypts the token to retrieve the user's session data.
This process ensures that the user's session data is always encrypted and protected from tampering.
Token Refresh Flow
Archibald implements a seamless token refresh strategy to ensure that users remain logged in without compromising security with long-lived session tokens.
- Short-Lived Session Token (
nct): The primary JWE token used for authentication has a short lifespan (typically 15 minutes). - Long-Lived Refresh Token (
ncr): A secondary encrypted token stored in a secure, HTTP-only cookie with a longer lifespan (e.g., 24 hours). - Automatic Detection: When the
AuthModuleon the server detects an expired session token, it automatically attempts to use the refresh token to issue a new session token. - Client-Side Interval: The
SessionClienton the frontend also maintains a background interval (configured via therefreshoption) to proactively check the session status and trigger a refresh if the token is nearing expiration.
This "silent refresh" happens entirely in the background, ensuring that the user's experience is never interrupted by unexpected logouts as long as they remain active.
Configuration
The JWE encryption and decryption is handled automatically by the @archibald/auth package. You only need to provide a secret key for signing the tokens in your server configuration.
// templates/shop/src/shop/server/module/server.tsx
// ...
export class Server extends CoreServer {
public async initModules() {
await this.registerModules([
new AuthModule({
// ...
options: () => ({
// ...
token: { secret: this.configService.get('server.credentials.token.secret') },
refresh: { secret: this.configService.get('server.credentials.token.secret') }
})
}),
// ... other modules
]);
}
}
By using JWE, Archibald provides a secure and robust session management system that protects your users' data.