最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Nestjs, passport refresh access token strategy, graphql context - Stack Overflow

programmeradmin6浏览0评论

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
  }
发布评论

评论列表(0)

  1. 暂无评论