5

我想为我的 Angular 应用程序设置一些端到端测试,这需要使用 MSAL 库对一些下游服务进行身份验证。当我尝试在本地运行我的 e2e 测试时,MSAL 库强制我使用用户名/密码进行身份验证。

这是一个问题,因为我们的 CI/CD e2e 测试不应该有任何人为干预;因此,我正在寻找一种绕过 MSAL 身份验证或设置服务帐户登录的方法。不幸的是,关于 Angular 的 MSAL 的文档并不多(尤其是在 e2e 测试方面),但这似乎是其他人可能遇到的常见问题。

我试图从我们的 app.module.ts 文件中禁用 MsalModule,但是当我尝试运行应用程序时,仍然提示我登录。我还看到一些文章试图以编程方式登录,但这对我们不起作用,因为 MSAL 在技术上不是我们能够接触到的 Angular 组件。

app.module.ts:

@NgModule({
  ...
  imports: [
    ...
    MsalModule.forRoot({
      clientID: '<client_id>',
      authority: <microsoft_authority_url>,
      validateAuthority: true,
      redirectUri: "http://localhost:4200/",
      cacheLocation : "localStorage",
      postLogoutRedirectUri: "http://localhost:4200/",
      navigateToLoginRequestUrl: true,
      popUp: true,
      consentScopes: [ "user.read"],
      unprotectedResources: ["https://www.microsoft.com/en-us/"],
      protectedResourceMap: protectedResourceMap,
      logger: loggerCallback,
      correlationId: '1234',
      level: LogLevel.Info,
      piiLoggingEnabled: true
    })
  ],
  entryComponents: [SaveDialogComponent,
                    GenericDialog, MassChangeDialogComponent],
  providers: [TitleCasePipe,
    {provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true}],
  bootstrap: [AppComponent]
})
export class AppModule { }

预期结果:删除 MSAL 身份验证模块应该允许我们的应用程序无需登录即可运行。

实际结果:应用程序仍在提示登录,或未正确呈现。

4

3 回答 3

11

我通过enableMsal在我的environment.test.tstrue中添加一个属性(以及在 prod 环境中具有值的相同属性)解决了这个问题:

export const environment = {
  production: false,
  enableMsal: false,
};

然后在路由模块中使用它(默认称为app-routing.module.ts,如下所示:

//... 
const guards: any[] = environment.enableMsal ? [MsalGuard] : [];

const routes: Routes = [
  {path: '', redirectTo: '/main', pathMatch: 'full'},
  {path: 'main', component: MainComponent, canActivate: guards},
  {path: 'other', component: OtherComponent, canActivate: guards},
];
//...

如果您不知道如何配置多个环境,Angular在这里有一个很好的指南。

于 2019-11-24T19:22:10.883 回答
3

要绕过MSAL ,您可以模拟 的实现MsalGuardMsalService其中是文件的副本。MsalInterceptormain-skip-login.tsmain.ts

import { MsalGuard, MsalInterceptor, MsalService } from '@azure/msal-angular';

MsalGuard.prototype.canActivate = () => true;

MsalInterceptor.prototype.intercept = (req, next) => {
  const access = localStorage.getItem('access_token');
  req = req.clone({
    setHeaders: {
      Authorization: `Bearer ${access}`
    }
  });
  return next.handle(req);
};

MsalService.prototype.getAccount = (): any => {
  if (!localStorage.getItem('access_token')) return undefined;
  return {
    idToken: {
      scope: [],
      // other claims if required
    }
  };
};

然后在里面创建一个名为 e2e 的配置angular.json并替换main.tsmain-skip-login.ts.

"configurations": {
            "e2e": {
              "fileReplacements": [
                {
                  "replace": "src/main.ts",
                  "with": "src/main-skip.login.ts"
                }
              ]
}}

现在您可以使用此配置运行项目并使用真实令牌设置 localStorage 以绕过 MSAL 身份验证流程。您还可以使用模拟逻辑来获得所需的结果。

于 2020-06-24T16:54:30.950 回答
1

为了解决这个问题,我们设置了另一个配置文件来运行 e2e 测试。

我们使用了一个不包含属性 canActivate 的自定义 ngular.routing.module:[MsalGuard]

于 2019-09-03T13:13:06.503 回答