首页 > 解决方案 > 在应用程序中禁用 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

标签: angulartypescriptangular8

解决方案


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,这样就不会忘记任何需要跳过的内容。


推荐阅读