我有多种身份验证策略,例如其中之一:
@Injectable()
export class EmployeeStrategy extends PassportStrategy(Strategy, 'employee') {
constructor(
private authService: AuthService,
@Inject(appConfig.KEY)
configService: ConfigType<typeof appConfig>,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: configService.EMPLOYEE_KEY,
});
}
async validate({ phone }: JwtPayload) {
const employee = await this.authService.authByRole(phone, Role.Employee);
if (!employee) {
throw new UnauthorizedException('insufficient scope');
}
return employee;
}
还有一些人大多喜欢这个。但是因为我在里面抛出了未经授权的异常,所以我不能在同一个路由/ Controller 上使用它们中的多个。例如。 @UseGuards(AuthGuard(['employee', 'admin']))
第一个崩溃导致错误。如何解决这个问题?
最佳答案
@xxx_coder_noscope 您对策略的看法有点错误。这里的策略是一种如何从定义的位置(HTTP header 、查询、参数、cookie 等)获取特殊 token 、 key 等的方法。从 validate()
返回的实体方法将作为 user
注入(inject)到请求对象中属性(property)。
稍后通过创建 EmployeeGuard
如EmployeeGuard implements CanActivete
并覆盖 canActivate()
方法按类型检查用户角色并返回 bool 值以允许或拒绝访问端点
关于具有多种策略的 Nestjs 护照身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62670332/