Skip to main content
The JWT (JSON Web Token) strategy authenticates requests using signed JWT access tokens. It’s the primary method for authenticating API requests and WebSocket connections after initial login.

How JWT Strategy Works

The JWT strategy:
  1. Parses authentication tokens from HTTP headers or WebSocket messages
  2. Verifies the token signature and expiration
  3. Extracts the user ID from the token payload (subject claim)
  4. Retrieves the full user entity from the database
  5. Returns the authenticated user

Installation

The JWT strategy is included in @feathersjs/authentication:

Configuration

1

Register JWT Strategy

Register the JWT strategy with your authentication service:
2

Configure JWT Options

Set JWT options in your application configuration:
3

Protect Services

Use the authenticate hook to require JWT authentication:

Configuration Options

JWT Options (jwtOptions)

These options control JWT token creation: Expiration formats: '1d', '2h', '30m', '60s', or seconds as number Algorithms: HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, ES512

JWT Strategy Options (jwt)

These options control JWT token parsing from HTTP requests:
JWT strategy options must be configured in the jwt section, not as top-level strategy options. Setting invalid options will throw an error.

Token Creation

Tokens are created by the authentication service after successful login:

Manual Token Creation

Create tokens programmatically:

Token Verification

Tokens are automatically verified by the JWT strategy:

Manual Token Verification

HTTP Authentication

The most common format:
JavaScript:

WebSocket Authentication

Authenticate WebSocket connections:

Connection Management

The JWT strategy automatically manages WebSocket connections:
Connections are automatically closed when tokens expire, forcing clients to re-authenticate with a fresh token.

Token Refresh

Implement token refresh by re-authenticating with an existing token:

Custom Entity Queries

Customize the query used to fetch the user entity:

Custom Entity ID Extraction

Extract user ID from custom token claims:

Security Best Practices

Critical Security Considerations

Secret Management

Token Expiration

Algorithm Selection

Token Validation

HTTPS Only

Always use HTTPS in production to prevent token interception.Consider setting secure cookie flags and HTTP Strict Transport Security (HSTS) headers.

Troubleshooting

Token Verification Fails

User Not Found

Configuration Errors

Next Steps

Local Strategy

Add username/password authentication

OAuth Strategy

Enable social login with OAuth