I was working on an api for events management and I was using passport with the default express adapter
Then I tried to switch to fastify I got cannot set req.heades error I installed some packages for fastify but still no luck I was wondering if there is a way to handle auth with fastify using passport or is it better to implement it manually?
#How are you handling auth when using fastify
4 messages · Page 1 of 1 (latest)
I'm not sure what the benefit of passport would be, so I can't compare options. But I can say that using @fastify/secure-session along with the method of your choice (email/password-hash or oauth) is pretty simple to set up. See https://github.com/fastify/fastify-oauth2 and https://github.com/fastify/fastify-secure-session
Your bootstrap will look something like this:
const app = await NestFactory.create<NestFastifyApplication>(
AdminModule.forRoot(mergedConfig),
new FastifyAdapter({
...mergedConfig.admin.fastify,
http: mergedConfig.admin.http || undefined,
http2: mergedConfig.admin.http2 || undefined,
https: mergedConfig.admin.https || undefined
}),
{ rawBody: true } // not needed for all routes?
)
app.enableShutdownHooks()
app.useGlobalPipes(new ValidationPipe({ ...mergedConfig.admin.validationPipeOptions }))
app.register(require('@fastify/helmet'), { ...mergedConfig.admin.fastifyHelmet })
app.register(require('@fastify/cors'), { ...mergedConfig.admin.fastifyCors })
app.register(require('@fastify/secure-session'), { ...mergedConfig.admin.fastifySecureSession })
app.register(require('@fastify/csrf-protection'), { ...mergedConfig.admin.fastifyCsrfProtection })
And on a login resolver or controller, you might have something like this (roughly):
const user = await this.authService.validateUser(email, password)
if (user) {
context.req.session.set('userId', user.id)
context.req.session.options({ maxAge: 3600 })
context.req.session.touch()
} else {
...
}