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
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1741538741a4352386.html
评论列表(0条)