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.
- 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;
}
}
- Set
passReqToCallback
totrue
, and get token as string from request invalidate
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();
}
}
- 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
版权声明:本文标题:Nestjs, passport refresh access token strategy, graphql context - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741538740a2384188.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论