我想知道是否有一个装饰器可以制作 req.user
Controller 方法中可用的对象,如果用户已登录(已发送授权 header ),如果没有,则让 req.user
为空。AuthGuard
如果用户未登录,装饰器将返回 401,因此它不适合我的情况。
最佳答案
没有内置的装饰器,但您可以轻松地自己创建一个。参见 docs 中的示例:
import { createParamDecorator } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
export const User = createParamDecorator((data, req) => {
return req.user;
});
由于内置
AuthGuard
抛出异常,您可以创建自己的版本并覆盖请求处理程序:@Injectable()
export class MyAuthGuard extends AuthGuard('jwt') {
handleRequest(err, user, info) {
// no error is thrown if no user is found
// You can use info for logging (e.g. token is expired etc.)
// e.g.: if (info instanceof TokenExpiredError) ...
return user;
}
}
确保您没有在
JwtStrategy
中抛出错误。 :@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(private readonly authService: AuthService) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: 'secretKey',
});
}
async validate(payload) {
const user = await this.authService.validateUser(payload);
// in the docs an error is thrown if no user is found
return user;
}
}
然后你可以在你的
Controller
中使用它像这样:@Get()
@UseGuards(MyAuthGuard)
getUser(@User() user) {
return {user};
}
关于javascript - nestjs 中的可选身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53249800/