angular - 在应用程序中禁用 Angular AuthGuard 和拦截器安全性,切换功能?
问题描述
我们正在使用 Angular 8,但我们的 JWT 令牌无法正常工作。目前需要处理其他项目,在应用程序中禁用 AuthGuard、AuthService 和 Http Intercept(Angular 安全)的最佳方法是什么?Angular 是否提供任何切换功能?
// src/app/app.routes.ts
import { Routes, CanActivate } from '@angular/router';
import { ProfileComponent } from './profile/profile.component';
import {
AuthGuardService as AuthGuard
} from './auth/auth-guard.service';
export const ROUTES: Routes = [
{ path: '', component: HomeComponent },
{
path: 'profile',
component: ProfileComponent,
canActivate: [AuthGuard]
},
{ path: '**', redirectTo: '' }
];
https://medium.com/@ryanchenkie_40935/angular-authentication-using-route-guards-bf7a4ca13ae3
解决方案
Angular 本身没有包含用于服务、守卫或拦截器的功能切换解决方案。您可以自己实现它,我建议您使用能够随时打开/关闭功能的运行时解决方案(不仅在构建时)。
您只需要在关闭时跳过实际的身份验证功能。假设您创建了将在资产、LocalStorage 中或从服务器获取的配置 JSON。它可能看起来像这样{"skipAuth": true}
,请注意true === off
逻辑,因为它会在默认情况下启用所有未提及的功能时创建一个很好的场景。
将功能配置包装在某些服务中或将其放入您的应用程序状态/商店。
使用拦截器,您必须执行以下操作:
@Injectable()
export class MyAuthInterceptor implements HttpInterceptor {
constructor(private toggles: FeatureTogglesService) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
if (this.toggles.features.skipAuth) {
return next.handle(req); // do what you need to do when skipping (use mock token / nothing / return original request)
}
// code that is executed when Auth is turned on
}
}
使用 Guard,您必须执行以下操作:
@Injectable()
class CanActivateTeam implements CanActivate {
constructor(private toggles: FeatureTogglesService) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
) {
if (this.toggles.features.skipAuth) {
return true; // let everyone access the route
}
// code that is executed when Auth is turned on
}
}
并重复与同一skipAuth
标志相关的所有 Auth,这样就不会忘记任何需要跳过的内容。
推荐阅读
- android - 在谷歌商店发布应用程序:covid19 选项问题
- wix - WiX 的 MSI 安装程序显示“应用转换时出错”
- spring-boot-actuator - 如何在 Spring Boot 中为 /.metrics 端点添加前缀
- python - Python max 函数在我自己的函数中不起作用 / TypeError: 'bool' object is not callable
- file-upload - PrimeNG p-file上传定制
- gitlab - Gitlab config.toml 在哪里
- javascript - 样式化组件的性能问题
- tkinter - 尝试使用 FBI 在第二个 hdmi 端口上显示图像时,Raspberry pi 4 触摸显示器进入控制台
- c - else-if 如何在 C 中工作?
- python - 如何提高可以访问集群的 Python 脚本的计算时间