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

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

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
  }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1741538741a4352386.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信