#Passport and Fastify

15 messages · Page 1 of 1 (latest)

jolly nimbus
jolly nimbus
#

Thank you. So it's not surprising that the regular Passport works fine for me?

rare girder
#

Does `@tawdry tusk/passport support fastify

Yes and no. If just local or jwt, yes. If oauth, extra is necessary.. Check the linked post

jolly nimbus
#

Ok, this is very helpful.

#
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { UsersService } from '../users/users.service';
import TokenPayload from './tokenPayload.interface';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly configService: ConfigService,
    private readonly userService: UsersService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromExtractors([
        (request: { cookies: Record<string, string> }) => {
          return request?.cookies?.Authentication;
        },
      ]),
      secretOrKey: configService.get('JWT_SECRET'),
    });
  }

  async validate(payload: TokenPayload) {
    return this.userService.getById(payload.userId);
  }
}

I'm doing regular JWT authentication

rare girder
#

Yeah, passport-jwt should be fine

jolly nimbus
#

request: { cookies: Record<string, string> } does not look great, but request: FastifyRequest would cause an error

 Type '(request: FastifyRequest) => string' is not assignable to type 'JwtFromRequestFunction'.
  Types of parameters 'request' and 'req' are incompatible.
    Type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' is missing the following properties from type 'FastifyRequest<RouteGenericInterface, RawServerDefault, IncomingMessage, FastifySchema, FastifyTypeProviderDefault, unknown, FastifyBaseLogger, ResolveFastifyRequestType<...>>': id, raw, log, server, and 13 more.
#

That's because of

export interface JwtFromRequestFunction {
    (req: express.Request): string | null;
}
rare girder
#

Yeeaaahh that's a fun part of dealing with fastify in libraries designed for express

jolly nimbus
#

Would you say that { cookies: Record<string, string> } is acceptable here?

rare girder
#

I don't think cookies would ever deserialize to something else so yes

jolly nimbus
#

Ok, thank you. I was wondering if using the regular Passport with Fastify makes any kind of sense, and it looks like it does (with some caveats).

#

I know there is @fastify/passport, but it's not very popular and I try to stay away from libraries like that
https://www.npmjs.com/package/@fastify/passport