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;
}
}
// In create-post.controller.ts
@Controller()
export class CreatePostController {
@UseGuards(AuthGuard(['jwt', 'anonymous'])) // first success wins
@Post('/posts')
async createPost(@Req() req: Request, @Body() dto: CreatePostDto) {
const user = req.user as ExpressUser
if (user.email) {
// Do something if user is authenticated
} else {
// Do something if user is not authenticated
}
...
}
}
3条答案
按热度按时间toiithl61#
没有内置的装饰器,但您可以轻松地自己创建一个。请参阅docs的示例:
由于内置的
AuthGuard
会抛出异常,因此您可以创建自己的版本并覆盖请求处理程序:请确保您没有在
JwtStrategy
中抛出错误:然后你可以像这样在
Controller
中使用它:wydwbb8l2#
另一种方法是创建匿名护照策略:
然后,在控制器中链接此策略:
vdzxcuhz3#
您可以添加一个公共装饰器
然后在你的 JWT 卫士
现在可以在控制器中允许匿名访问,以便在用户经过身份验证时将用户包括在请求中