只需在NestJS:docs.nestjs.com中查看身份验证文档
以下是代码:
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { jwtConstants } from './constants';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: jwtConstants.secret,
});
}
async validate(payload: any) {
return { userId: payload.sub, username: payload.username };
}
}根据docs,当请求包含jwt且jwt有效时,将调用valid方法。当请求头中缺少jwt,或者jwt无效或过期时,我想知道是否存在回调方法。我想返回响应错误与消息,他们的令牌已过期或丢失.
谢谢
发布于 2022-03-18 14:48:56
您可以实现自定义策略,并检查您喜欢的标题或cookie。这是我在应用程序上使用的一个(简称)示例。
import { JwtService } from '@nestjs/jwt';
import { Strategy } from 'passport-custom';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'custom-jwt') {
constructor(private readonly jwtService: JwtService) {
super();
}
async validate(req: Request): Promise<any> {
const token = req.cookies.auth ?? req.headers.authorization;
if (!token) {
throw new UnauthorizedException();
}
const user = this.jwtService.decode(token, {
json: true
});
if (!user) {
throw new UnauthorizedException();
}
if (this.isExpired(user)) {
throw new UnauthorizedException();
}
return user;
}
private isExpired(user: JwtUserDto): boolean {
// ...
}
}该代码在"auth"-cookie或“授权”-header中检查jwt令牌,并通过返回用户,将解码用户(如果有效)附加到请求。
使用它:export class JwtAuthGuard extends AuthGuard('custom-jwt')
这只是一个例子,看看它是如何工作的。您可能需要调整它以满足您的需要。
https://stackoverflow.com/questions/71527077
复制相似问题