The authenticate method returns a preValidation hook used to validate users and sign them in. It is typically used on login routes.
Behavior:
- It applies the specified strategy (or array of strategies) to the request.
- On success: The user is populated at
request.user and a session is established (if session: true). - On failure: An unauthorized response is sent (unless
failWithError: true is used).
Strategies:
- You can pass a strategy name (string) or the Strategy instance itself.
- You can pass an array of names/instances to try multiple strategies in order.
- Warning: Do not use multiple OAuth2 strategies in a single
authenticate call, as the first one that triggers a redirect will prevent the others from running. Instead, create separate routes for each OAuth provider.
Options:
session: (Boolean, default true) Save login state in session.successRedirect: (String) URL to redirect to after successful login.failureRedirect: (String) URL to redirect to after failed login.successReturnToOrRedirect: (Boolean) Redirect to the URL stored in session under returnTo if available, otherwise to the provided URL.keepSessionInfo: (Boolean) If true, preserves existing session properties after authentication.failWithError: (Boolean) Throws an AuthenticationError instead of sending a failure response, allowing your Fastify error handler to catch it.authInfo: (Boolean, default true) Whether to store the strategy's info object at request.authInfo.assignProperty: (String) Assign the verify callback result to a specific property.state: (Object) Pass state through to the strategy (e.g., for Google OAuth).successMessage / successFlash: (String | Boolean) Override success messages.failureMessage / failureFlash: (String | Boolean) Override failure messages.
Custom Callback:
You can provide a callback to override default handling:
async (request, reply, err, user, info, status) => { ... }
If a callback is provided, you are responsible for logging in the user and managing the session.
// Authenticate using a registered strategy named 'local'
fastifyPassport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' });
// Authenticate using multiple strategies in order
fastify.get(
'/',
{ preValidation: fastifyPassport.authenticate(['bearer', 'basic', 'google'], { authInfo: false }) },
async (request, reply, err, user, info, status) => {
if (err !== null) {
console.warn(err)
} else if (user) {
console.log(`Hello ${user.name}!`)
}
}
)
// Use a strategy instance directly without registering it globally
fastify.get(
'/',
{
preValidation: fastifyPassport.authenticate([new BearerTokenStrategy(), new BasicAuthStrategy()], {
authInfo: false,
}),
},
async (request, reply, err, user, info, status) => { /* ... */ }
)