'How to get user JWT token in JWTStrategy (NestJS)?
My problem is that I want to check if the login token is invalidated in the database (after changing password). However, the validate function in JWTStrategy only has access to the payload of the JWT, not the token. I would like to know if there is a way I can get the JWT token from the request in this class or JWTAuthGuard. Thanks!
async validate(payload: LoginPayload) {
const { email, firstName, lastName, sub } = payload;
return {
id: sub,
email,
firstName,
lastName,
};
}
Solution 1:[1]
To get access to the token specifically, you need to pass passReqToCallback: true
in the super
call of the JwtStrategy
's constructor
. Now the first parameter of the JwtStrategy#validate
method is req
and the second if the token payload, so you can call `req.headers['authorization'].split(' ')[1] to get the token itself. Something like:
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: jwtConstants.secret,
passReqToCallback: true
});
}
async validate(req: e.Request, payload: LoginPayload) {
const rawToken = req.headers['authorization'].split(' ')[1];
const { email, firstName, lastName, sub } = payload;
return {
id: sub,
email,
firstName,
lastName,
};
}
}
Solution 2:[2]
I enjoy it because passReqToCallback
works fine.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jay McDoniel |
Solution 2 | taoliujun |