【发布时间】:2020-09-01 05:41:00
【问题描述】:
我正在实施刷新令牌,我使用的是 passportjs。我不完全理解的是我应该在哪里以及如何检查访问令牌的有效性,如果无效令牌到达,则抛出TokenExpiredException。
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private readonly authService: AuthService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET,
});
}
public async validate(payloadDto: PayloadDto): Promise<PayloadDto> {
const validUser = await this.authService.validateUser(payloadDto);
return { id: validUser.id, phone: validUser.phone };
}
}
validateUser 方法目前如下所示:
public async validateUser(payload: PayloadDto): Promise<UserEntity> {
const retrievedUser: UserEntity = await this.userService.retrieveOne(payload.phone);
if (retrievedUser) {
return retrievedUser;
} else {
throw new HttpException('Invalid User', HttpStatus.UNAUTHORIZED);
}
}
我想知道这样检查是否安全:
@Injectable()
export class RefreshAuthGuard extends AuthGuard('jwt') {
public handleRequest(err: any, user: any, info: Error): any {
if (info) {
if (info.name === 'TokenExpiredError') {
throw new HttpException('TokenExpired', HttpStatus.UNAUTHORIZED);
} else {
throw new HttpException('Unauthorized', HttpStatus.UNAUTHORIZED);
}
}
}
}
【问题讨论】:
标签: typescript nestjs