我遵循了 NestJs 文档并添加了以下不工作的基于角色的身份验证防护。
我总是得到未定义的标题或 context.switchToHttp().getRequest() 未定义。
我正在使用带有nestjs的graphql。
我的解析器:
@Resolver(() => User)
export class UsersResolver {
constructor(private readonly usersService: UsersService) {}
@UseGuards(AuthGuard('jwt'))
@Roles(ROLES.ADMIN)
@Query(() => [User], { name: 'users' })
findAll(): Promise<UserDto[]> {
return this.usersService.findAll();
}
}
用户模块:
@Module({
imports: [TypeOrmModule.forFeature([User, Role]), AuthModule],
providers: [UsersResolver, UsersService, AuthResolver],
})
export class UsersModule {}
角色守卫:
import { Injectable, CanActivate, ExecutionContext, Logger } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { GqlExecutionContext } from '@nestjs/graphql';
@Injectable()
export class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(context: ExecutionContext): boolean {
Logger.log('RolesGuard Called');
const requiredRoles = this.reflector.getAllAndOverride<string[]>('roles', [context.getHandler(), context.getClass()]);
if (!requiredRoles) {
return true;
}
const request = context.switchToHttp().getRequest();
const user = request.user;
return requiredRoles.some(role => user.roles?.includes(role));
}
}
认证模块:
@Module({
imports: [
ConfigModule,
PassportModule.register({
defaultStrategy: 'jwt',
}),
JwtModule.register({
secret: 'THIS_IS_A_SECRET',
signOptions: {
expiresIn: 3600,
},
}),
],
providers: [AuthenticationService, JwtStrategy],
exports: [AuthenticationService],
})
export class AuthModule {}
我在 app.module 中添加了 RolesGuard。
{ 提供:APP_GUARD,useClass:RolesGuard }