I am new to Nestjs and I am using guards, strategies and passport for authentification. I don't understand what's going on under the hood.
I have a guard for a refreshToken mutation:
import { AuthGuard } from '@nestjs/passport';
import { ExecutionContext } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
export class RtGuard extends AuthGuard('jwt-refresh') {
constructor() {
super();
}
getRequest(context: ExecutionContext) {
const ctx = GqlExecutionContext.create(context);
console.log('REFRESH');
return ctx.getContext().req;
}
}
What does this guard exactly do? Somehow it calls my strategy right? But it only does it, if I provide a correct refreshToken.
This is my Strategy:
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, ForbiddenException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtPayloadWithRt } from '../types/jwtPayloadWithRt.type';
import { JwtPayload } from 'src/auth/types/jwtPayload.type';
import { Request } from 'express';
@Injectable()
export class RefreshTokenStrategy extends PassportStrategy(
Strategy,
'jwt-refresh',
) {
constructor(config: ConfigService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: config.get<string>('REFRESH_TOKEN_SECRET'),
passReqToCallback: true,
});
}
validate(req: Request, payload: JwtPayload): JwtPayloadWithRt {
const refreshToken = req.get('authorization')?.replace('Bearer', '').trim();
if (!refreshToken) throw new ForbiddenException('Refresh token malformed');
return {
...payload,
refreshToken,
};
}
}
How is the guard able to decide whether my refresh token is the one in my database and if so, then it calls my strategy?
If I use a wrong refreshToken, not the one I got when I signed in, I get this error:
when providing the correct key, I get this:
Using console.log, I can see that my strategy is not called, whenever the refreshtoken is invalid. How does the validation work exactly? How do guard and strategy work together under the hood?
Thanks a lot for help!