我有多种身份验证策略,例如其中之一:
@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;
}
Run Code Online (Sandbox Code Playgroud)
还有一些人大多喜欢这个。但是因为我在其中抛出了未经授权的异常,所以我不能在同一个路由/控制器上使用多个异常。例如
@UseGuards(AuthGuard(['employee', 'admin']))
Run Code Online (Sandbox Code Playgroud)
第一个崩溃导致错误的。如何解决这个问题?
小智 5
@xxx_coder_nscope 你对策略的看法有点错误。这里的策略是如何从定义的位置(HTTP header、query、param、cookies 等)获取特殊令牌、密钥等的方法。从方法返回的实体validate()将作为属性注入到请求对象中user。
稍后通过创建EmployeeGuardasEmployeeGuard implements CanActivete和重写canActivate()方法按类型检查用户角色并返回布尔值以允许或拒绝对端点的访问
| 归档时间: |
|
| 查看次数: |
1818 次 |
| 最近记录: |