問題描述
我目前正在將 Azure AD 身份驗(yàn)證集成到 Angular - .Net core 3.1 項(xiàng)目.這是一個(gè)從 Visual Studio 2019 模板(ASP.NET Core Web App)生成的項(xiàng)目.
在 Azure 門戶中,我注冊了 2 個(gè)應(yīng)用程序并由 MS教程和這個(gè).
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.
兩個(gè)注冊的應(yīng)用程序:
- frontend_app(客戶端 ID:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx16e3)
- backend_api(客戶端ID:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxfcc1)
但我只發(fā)布了一個(gè) App 服務(wù),其中包含 SPA 和 API.登錄后,我得到一個(gè)令牌,它附加到每個(gè)使用 MSAL 攔截器的 api 調(diào)用.
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.
問題是所有的調(diào)用返回都是: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.
我該如何解決才能接受觀眾?只為一個(gè)應(yīng)用服務(wù)使用2個(gè)應(yīng)用注冊是否正確?
How can I solve to accept the the audience? Is it correct to use 2 app registration for only one app service?
推薦答案
我遇到了和你一樣的問題,相信我已經(jīng)找到了解決方案.我最初遵循的所有指南都使用隱式流程.正如卡爾在他的回答中指出的那樣(我認(rèn)為這不能正確解決您的問題),有一個(gè) auth flow 這是推薦的方式.不幸的是,所有示例和指南中的標(biāo)準(zhǔn) MSAL 庫都是 1.x,不支持身份驗(yàn)證流程.相反,您需要使用 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.
首先,您創(chuàng)建后端 api 應(yīng)用注冊(您可能不需要更改).以下是相關(guān)文檔:注冊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"部分下的授權(quán)應(yīng)用程序.我們將使用身份驗(yàn)證流程以不同方式處理.
- 不需要重定向 URI,因?yàn)槟暮蠖瞬粫層脩舻卿?/li>
- 您至少需要一個(gè)示波器才能正常工作
然后按照 MSAL.js 2.0 文檔來創(chuàng)建前端應(yīng)用注冊.重要說明如下:
Then follow the MSAL.js 2.0 documentation to create the frontend app registration. The important notes are as follows:
- 確保選擇 SPA 平臺并輸入有效的重定向 URI
- 請勿選中隱式授予"復(fù)選框
- 在API 權(quán)限"下,為您的前端應(yīng)用授予對后端 API 的訪問權(quán)限:
- 在API 權(quán)限"下點(diǎn)擊添加權(quán)限",然后點(diǎn)擊我的 API"標(biāo)簽
- 找到您的后端應(yīng)用程序并選擇適當(dāng)?shù)姆秶?
- 點(diǎn)擊添加權(quán)限"
- 可選擇為您的 API 授予同意
您的應(yīng)用注冊應(yīng)類似于以下內(nèi)容:
Here's what your app registrations should look similar to:
后端應(yīng)用注冊公開一個(gè)api
前端應(yīng)用注冊認(rèn)證
前端應(yīng)用注冊api權(quán)限
現(xiàn)在是代碼.對于您的 Angular 應(yīng)用,首先安裝必要的模塊:
Now for the code. For your angular app, first install the necessary modules:
npm install @azure/msal-browser @azure/msal-angular@alpha
然后將其添加到您的應(yīng)用模塊中:
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
扔到您想要保護(hù)的任何路線上.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 中的相關(guān)代碼:
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>" }
這篇關(guān)于如何配置.net core angular azure AD 身份驗(yàn)證?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!