admin管理员组

文章数量:1291619

I use nestjs with graphql and passport with fastify adapter. I try to implement refresh token logic as additional logic to local strategy.

My problem is: when i set passReqToCallback to true, in my mutation context (step 3 - ctx arg) i get only request (from step 1), without decoded token data. When i set passReqToCallback to false i cant get encoded token as string from request. Possible solution is decode token in mutation function and get user data from it, but i want to find better one.

  1. Get request from context and pass it to passport
@Injectable()
export class JwtAuthRefreshGuard extends AuthGuard('jwt-refresh') {
  getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    return ctx.getContext().req;
  }
}
  1. Set passReqToCallback to true, and get token as string from request in validate function, check this token is valid (exist in db), and then return to context data from token (code below) if ok, otherwise throw error.
@Injectable()
export class JwtRefreshStrategy extends PassportStrategy(Strategy, 'jwt-refresh') {
  constructor(
    private readonly $config: ConfigService,
    private readonly $users: UsersService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: $config.getOrThrow('JWT_REFRESH_SECRET'),
      passReqToCallback: true,
    });
  }
  async validate(req: FastifyRequest, tokenDecoded: Token) {
  // simplified logic
  const tokenEncoded = req.header.authorization;
  const user = this.$users.findUser({ id: tokenDecoded.id });
  const isValid = user.refreshToken === tokenEncoded;
  if(isValid) return { token: tokenDecoded };
  throw new UnauthorizedException();
  }
}
  1. Get user data from decoded token that i passed to context ctx in previous step and then make some refresh logic
  @Mutation(() => TokensOutput)
  @UseGuards(JwtAuthRefreshGuard)
  async refreshToken(@Context() ctx) {
    const token = ctx.token;
    // some refresh logic after...
    // but only request in ctx, if passReqToCallback is true
  }

本文标签: NestJspassport refresh access token strategygraphql contextStack Overflow