5

So I replaced ExpressJS with Fastify, but my problem is Nest-Passport doesn't support fastify, do we have an alternative for Nest-Passport? or any solutions on how to secure RestAPI in nestJS using a token?

BinaryButterfly
  • 18,137
  • 13
  • 50
  • 91
Dan
  • 69
  • 2
  • 8

3 Answers3

5

I dont kown if this is the correct manner. But if I change the default jwt extractor

ExtractJwt.fromAuthHeaderAsBearerToken

(described within the doc ) by a custom one it works.

const fromFastifyAuthHeaderAsBearerToken = (request: FastifyRequest): string => {
const auth = request.headers['authorization'];
const token = auth?.split(' ')[1];
return token;
}
jarjar
  • 359
  • 4
  • 10
  • This would be the correct link https://github.com/mikenicholson/passport-jwt#writing-a-custom-extractor-function – adkstar May 16 '21 at 21:18
  • You can also use it like in code like JWT strategy ```jwtFromRequest: (request: fastify.FastifyRequest) => { console.log('As it is if not signed', request?.cookies?.Authentication); console.log('After unsigning the cookie', request?.unsignCookie(request.cookies?.Authentication)); }``` – adkstar May 16 '21 at 21:19
4

There's no immediate Fastify NestJJS authentication package I'm aware of (I'm sure there's something out there), but I do have a sample of JWT authentication with Fastify and NestJS without Passport. The idea is to make use of Nest's @nestjs/jwt package or just jsonwebtoken directly, and create the auth tokens with that instead of delegating to Passport. This is actually the kind of approach I prefer, as I find Passport to be a bit too mystical sometimes.

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
0

I had similar issue and found the following workaround do the trick for me:

At the main.ts file in src directory I just added the following code after creating the app object (NestFactory.create...)

app.getHttpAdapter()
        .getInstance()
        .addHook('onRequest', (request, reply, done) => {
            reply.setHeader = function (key, value) {
                return this.raw.setHeader(key, value);
            };
            reply.end = function () {
                this.raw.end();
            };
            request.res = reply;
            done();
        });

This solved my issue.

I found it at : https://github.com/nestjs/nest/issues/5702

Pini Cheyni
  • 5,073
  • 2
  • 40
  • 58