Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
89
rated 0 times [  91] [ 2]  / answers: 1 / hits: 25394  / 6 Years ago, wed, november 14, 2018, 12:00:00
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthService } from './auth.service';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtPayload } from './model/jwt-payload.model';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'secretKey',
});
}

async validate(payload: JwtPayload) {
const user = await this.authService.validateUser(payload);
if (!user) {
throw new UnauthorizedException();
}
return true;
}
}


Token is extracted from the request by PassportStrategy. I don't know how to catch the error when the token expires or gets invalid. My purpose is if there is an error because the token expired, I need to refresh the token. Otherwise do something else.


More From » node.js

 Answers
8

Instead of using the built-in AuthGuard you can create your own one and overwrite the request handler:



@Injectable()
export class MyAuthGuard extends AuthGuard('jwt') {

handleRequest(err, user, info: Error) {
if (info instanceof TokenExpiredError) {
// do stuff when token is expired
console.log('token expired');
}
return user;
}

}


Depending on what you want to do, you can also overwrite the canActivate method where you have access to the request object. Have a look at the AuthGuard sourcecode.


[#53118] Thursday, November 8, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jeffn

Total Points: 559
Total Questions: 81
Total Answers: 103

Location: Spain
Member since Thu, Dec 23, 2021
2 Years ago
;