Ala*_*ley 4 e2e-testing angular-cli azure-ad-msal angular angular-e2e
我想为我的 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 { }
Run Code Online (Sandbox Code Playgroud)
预期结果:删除 MSAL 身份验证模块应该允许我们的应用程序运行而无需登录。
实际结果:应用程序仍在提示登录,或未正确呈现。
小智 7
我通过enableMsal在我的environment.test.ts 中添加一个属性(以及true在 prod 环境中具有值的相同属性)解决了这个问题:
export const environment = {
production: false,
enableMsal: false,
};
Run Code Online (Sandbox Code Playgroud)
然后在路由模块中使用它(默认称为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},
];
//...
Run Code Online (Sandbox Code Playgroud)
如果您不知道如何配置多个环境,angular 有一个很好的指南here。
要绕过 MSAL,您可以模拟 的实现MsalGuard,MsalService其中MsalInterceptor包含文件main-skip-login.ts的副本main.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
}
};
};
Run Code Online (Sandbox Code Playgroud)
然后在里面创建一个名为 e2e 的配置angular.json并替换main.ts为main-skip-login.ts.
"configurations": {
"e2e": {
"fileReplacements": [
{
"replace": "src/main.ts",
"with": "src/main-skip.login.ts"
}
]
}}
Run Code Online (Sandbox Code Playgroud)
现在,您可以使用此配置运行项目,并使用真实令牌设置 localStorage 以绕过 MSAL 身份验证流程。您还可以使用模拟逻辑来获得所需的结果。
| 归档时间: |
|
| 查看次数: |
3762 次 |
| 最近记录: |