JWT Authentication

This guide demonstrates practical examples of using JWT (JSON Web Tokens) with the Stilmark Base library.

Table of Contents

Prerequisites

Make sure you have these environment variables configured in your .env file:

JWT_SECRET=your-secret-key-here
JWT_ISSUER=https://your-domain.com
JWT_ALGORITHM=HS256

Basic Usage

1. Generating a Token

2. Validating a Token

4. Complete Login Example with Cookies

Using with AuthMiddleware

The AuthMiddleware can automatically validate JWT tokens from the Authorization header.

1. Protect a Route

2. Accessing User Data in Protected Routes

After successful validation, the decoded token is stored in the session:

Handling Token Refresh

Implement a refresh token endpoint:

Custom Claims and Validation

Adding Custom Claims

Validating Custom Claims

Error Handling

Common JWT Exceptions

Best Practices

  1. Secure Token Storage

    • For web applications, always use HTTP-only, secure cookies with SameSite attribute

    • Set appropriate cookie expiration times (shorter is more secure)

    • For mobile/SPA, use secure storage (e.g., Keychain, SecureStore)

    • Never store sensitive data in JWT payload

    • Implement proper token refresh flow

  2. Token Expiration

    • Keep access tokens short-lived (e.g., 15-60 minutes)

    • Use refresh tokens for longer sessions

  3. Secret Management

    • Never hardcode JWT_SECRET in your code

    • Use different secrets for different environments

    • Rotate secrets periodically

  4. Token Payload

    • Keep the payload small (JWT is sent with every request)

    • Don't store sensitive data in the token

    • Use standard claims when possible (e.g., sub, iss, exp)

  5. Security Headers

    • Always use HTTPS

    • Set appropriate CORS headers

    • Use security headers like Strict-Transport-Security

Complete Example: JWT Login Flow

This example provides a solid foundation for implementing JWT authentication in your application. Remember to adapt it to your specific security requirements and application architecture.

Last updated