问题描述
我目前正在将 Azure AD 身份验证集成到 Angular - .Net core 3.1 项目.这是一个从 Visual Studio 2019 模板(ASP.NET Core Web App)生成的项目.
在 Azure 门户中,我注册了 2 个应用程序并由 MS教程和这个.
I'm currently working on Azure AD authenticaton integration to Angular - .Net core 3.1 project. This is a project which was generated from Visual Studio 2019 template (ASP.NET Core Web App).
In Azure portal, I registered 2 application and configured by MS tutorial and this.
两个注册的应用程序:
- frontend_app(客户端 ID:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx16e3)
- backend_api(客户端ID:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxfcc1)
但我只发布了一个 App 服务,其中包含 SPA 和 API.登录后,我得到一个令牌,它附加到每个使用 MSAL 拦截器的 api 调用.
But I published only one App service, which contains both SPA and API. After login, I got a token, which append to every api call with MSAL interceptor.
问题是所有的调用返回都是:401,由于观众无效".在 auth 令牌中,观众重视 frontend_app 的客户端 ID.
The problem is all of the calls return is: 401, due to 'audience is invalid'. in the auth token the audience value the client id of frontend_app.
我该如何解决才能接受观众?只为一个应用服务使用2个应用注册是否正确?
How can I solve to accept the the audience?Is it correct to use 2 app registration for only one app service?
推荐答案
我遇到了和你一样的问题,相信我已经找到了解决方案.我最初遵循的所有指南都使用隐式流程.正如卡尔在他的回答中指出的那样(我认为这不能正确解决您的问题),有一个 auth flow 这是推荐的方式.不幸的是,所有示例和指南中的标准 MSAL 库都是 1.x,不支持身份验证流程.相反,您需要使用 MSAL.js 2.0.问题是角度库仍在 阿尔法
I was having the same problem as you and believe I have come up with a solution. All the guides I originally followed were using the implicit flow. As Carl pointed out in his answer (which I don't believe properly addresses your issue), there's an auth flow which is the recommended way to go. Unfortunately the standard MSAL libraries from all the samples and guides are 1.x and don't support auth flow. Instead, you'll need to use MSAL.js 2.0. The catch is that the angular library is still in alpha
所以,这就是我所做的一切.我正在使用带有 ASP.NET Core 3.1 后端的 Angular 10 前端.
So, here's what I did to make it all work. I'm using an Angular 10 front-end with an ASP.NET Core 3.1 backend.
首先,您创建后端 api 应用注册(您可能不需要更改).以下是相关文档:注册Web API.重要说明:
First, you create your backend api app registration (which you may not need to change). Here's the documentation for that: Register Web API. Important notes:
- 使用此方法,您无需将前端客户端 ID 添加为公开 API"部分下的授权应用程序.我们将使用身份验证流程以不同方式处理.
- 不需要重定向 URI,因为您的后端不会让用户登录
- 您至少需要一个示波器才能正常工作
然后按照 MSAL.js 2.0 文档来创建前端应用注册.重要说明如下:
Then follow the MSAL.js 2.0 documentation to create the frontend app registration. The important notes are as follows:
- 确保选择 SPA 平台并输入有效的重定向 URI
- 请勿选中隐式授予"复选框
- 在API 权限"下,为您的前端应用授予对后端 API 的访问权限:
- 在API 权限"下点击添加权限",然后点击我的 API"标签
- 找到您的后端应用程序并选择适当的范围.
- 点击添加权限"
- 可选择为您的 API 授予同意
您的应用注册应类似于以下内容:
Here's what your app registrations should look similar to:
现在是代码.对于您的 Angular 应用,首先安装必要的模块:
Now for the code. For your angular app, first install the necessary modules:
npm install @azure/msal-browser @azure/msal-angular@alpha
然后将其添加到您的应用模块中:
Then add this to your app module:
import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { APP_INITIALIZER, NgModule } from '@angular/core'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { tap } from 'rxjs/operators'; import { IPublicClientApplication, PublicClientApplication, InteractionType, BrowserCacheLocation, LogLevel, } from '@azure/msal-browser'; import { MsalGuard, MsalInterceptor, MsalBroadcastService, MsalInterceptorConfiguration, MsalModule, MsalService, MSAL_GUARD_CONFIG, MSAL_INSTANCE, MSAL_INTERCEPTOR_CONFIG, MsalGuardConfiguration, } from '@azure/msal-angular'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; const PROTECTED_RESOURCE_MAP: Map<string, Array<string>> = new Map([ ['https://graph.microsoft.com/v1.0/me', ['user.read']], [ 'api/admin/users', ['api://<backend app id>/access_as_admin'], ], ]); const IS_IE = window.navigator.userAgent.indexOf('MSIE ') > -1 || window.navigator.userAgent.indexOf('Trident/') > -1; export function loggerCallback(logLevel, message) { console.log(message); } export function MSALInstanceFactory(): IPublicClientApplication { return new PublicClientApplication({ auth: { clientId: '<frontend app id>', authority: 'https://login.microsoftonline.com/<azure ad tenant id>', redirectUri: 'http://localhost:4200', postLogoutRedirectUri: 'http://localhost:4200/#/logged-out', }, cache: { cacheLocation: BrowserCacheLocation.LocalStorage, storeAuthStateInCookie: IS_IE, // set to true for IE 11 }, system: { loggerOptions: { loggerCallback, logLevel: LogLevel.Verbose, piiLoggingEnabled: false, }, }, }); } export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration { return { interactionType: InteractionType.Redirect, protectedResourceMap: PROTECTED_RESOURCE_MAP, }; } export function MSALGuardConfigFactory(): MsalGuardConfiguration { return { interactionType: InteractionType.Redirect, }; } export function initializeApp(appConfig: AppConfigService) { const promise = appConfig .loadAppConfig() .pipe(tap((settings: IAppConfig) => {})) .toPromise(); return () => promise; } @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, BrowserAnimationsModule, AppRoutingModule, HttpClientModule, MsalModule, ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true, }, { provide: MSAL_INSTANCE, useFactory: MSALInstanceFactory, }, { provide: MSAL_GUARD_CONFIG, useFactory: MSALGuardConfigFactory, }, { provide: MSAL_INTERCEPTOR_CONFIG, useFactory: MSALInterceptorConfigFactory, }, MsalService, MsalGuard, MsalBroadcastService, ], bootstrap: [AppComponent], }) export class AppModule {}
然后您可以简单地将
MsalGuard
扔到您想要保护的任何路线上.Then you can simply toss the
MsalGuard
onto any route you want to protect.对于后端,首先安装 Microsoft.Identity.Web 包:
For the backend, first install the Microsoft.Identity.Web package:
dotnet add package Microsoft.Identity.Web --version 1.3.0
这是我的 Startup.cs 中的相关代码:
Here's the relevant code in my Startup.cs:
public void ConfigureServices(IServiceCollection services) { // other stuff... services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(options => { Configuration.Bind("AzureAd", options); }) .AddInMemoryTokenCaches(); services.AddCors((options => { options.AddPolicy("FrontEnd", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); })); // other stuff... } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // other stuff... app.UseCors("FrontEnd"); app.UseAuthentication(); app.UseAuthorization(); // other stuff... }
appsettings.json 包含:
appsettings.json contains:
"AzureAd": { "Instance": "https://login.microsoftonline.com/", "Domain": "<azure ad domain>", "TenantId": "<azure ad tenant id>", "ClientId": "<backend app id>" }
这篇关于如何配置.net core angular azure AD 身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!