node.js - NestJS - 从 Guard 访问用户
问题描述
我一直在关注 NestJS 官方文档。我已成功设置 JWT 护照身份验证。我可以从控制器中的@Req 访问用户详细信息,但我在从自定义防护中访问用户详细信息时遇到问题。
这工作正常
@UseGuards(RolesGuard)
@Get('me')
getProfile(@Request() req) {
return req.user;
}
这不(当前记录调试)
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
const roles = this.reflector.get<string[]>('roles', context.getHandler());
if (!roles) {
console.log('No Roles');
return true;
}
const request = context.switchToHttp().getRequest();
// Returns Undefined
console.log(request.user);
return true;
}
}
这就是我在控制器中声明每个条目的方式
@Get()
@UseGuards(RolesGuard)
@Roles('admin')
findAll() {
return this.usersService.findAll();
}
角色元数据的传递工作正常,只是看起来用户没有在正确的步骤附加到上下文中。
任何帮助都会很棒,谢谢!
编辑:更新了@UseGuards(RolesGuard),复制并粘贴了错误的版本
解决方案
看起来我已经修好了,必须把它们锁起来
@Get()
@Roles('admin')
@UseGuards(JwtAuthGuard, RolesGuard)
findAll() {
return this.usersService.findAll();
}
推荐阅读
- python - 为什么使用 django python 时 cv2.imread 没有返回?
- python - 在 ML 分类器中编码文本
- swift - 如何在 SwiftUI 中制作具有某种风格的文本编辑器?
- google-chrome - 请求标头中存在缓存时的 Chrome 浏览器和 CORS 问题
- r - 在 R 中绘制移动/滚动模式
- python - Django - OperationalError,没有这样的表:accounts_user
- c# - .NET c#ConvertTimeToUtc 在使用 TimeZone UTC+0 时无法发送到 Firestore
- javascript - 使用 Javascript Fetch 对 Amadeus Test Flight Api 进行身份验证
- reactjs - react ag-grid服务器端无限行模型是否可以制作graphql
- spring-cloud-config - Spring Cloud 配置服务器客户端未检测到来自配置服务器的内容