我正在嘗試使用 Angular 前端和 Core MVC API 來實作 Microsoft 的 MSAL。
我已經能夠在 Angular 應用程式上成功進行身份驗證并呼叫 Graph API 端點。Angular 應用程式使用以下代碼:
app.module.ts
@NgModule({
declarations: [...],
imports: [
...
MsalModule.forRoot(
new PublicClientApplication({
auth: {
clientId: '47...',
authority: 'https://login.microsoftonline.com/6d...',
redirectUri: 'https://localhost:4200',
},
cache: {
cacheLocation: 'localStorage',
storeAuthStateInCookie: false
},
}),
{
interactionType: InteractionType.Redirect,
authRequest: { scopes: ['user.read'] },
},
{
interactionType: InteractionType.Redirect,
protectedResourceMap: new Map([
['https://graph.microsoft.com/v1.0/me', ['user.read']],
['https://localhost:44333/Auth/Index', ['user.read']]
]),
},
),
RouterModule,
],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true,
}],
bootstrap: [AppComponent, MsalRedirectComponent],
})
export class AppModule {}
我可以通過使用 HttpClient 和配置的 MsalInterceptor 成功呼叫 Graph API
this.http.get('https://graph.microsoft.com/v1.0/me')
.subscribe(profile => { this.profile = profile; });
接下來我嘗試用類似的代碼呼叫我自己的 API
this.http.get('https://localhost:44333/Auth/Index')
.subscribe(token => { this.token = token; });
但是,此請求失敗并出現以下錯誤:
處理請求時發生未處理的例外。
例外:關聯失敗。
未知位置
例外:處理遠程登錄時遇到錯誤。
Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler.HandleRequestAsync()
我假設問題出在我的 API 上。我已經在我的 .Net 5.0 MVC API 中配置了身份驗證,如下所示:
啟動檔案
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddOptions();
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi(new[] { "user.read" })
.AddInMemoryTokenCaches();
}
appsettings.json
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com",
"TenantId": "6d...",
"ClientId": "47...",
"ClientSecret": "..."
},
}
AuthController.cs
namespace Auth.Services
{
[Route("{controller}/{action}")]
[Authorize]
public class AuthController : Controller
{
private readonly ITokenAcquisition tokenAcquisition;
public AuthController(ITokenAcquisition tokenAcquisition) => this.tokenAcquisition = tokenAcquisition;
[HttpGet]
public async Task<IActionResult> Index()
{
var scopes = new string[] { "user.read" };
var accessToken = await tokenAcquisition.GetAccessTokenForUserAsync(scopes);
//...
return Ok(...);
}
}
}
It doesn't seem like the application ever reaches the controller. None of the breakpoints are ever hit and when I examine the Events, there are two exceptions that are thrown:
Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler: Warning: '.AspNetCore.Correlation.XXX' cookie not found.
System.Exception: An error was encountered while handling the remote login. ---> System.Exception: Correlation failed. --- End of inner exception stack trace --- at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync() at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
讓我感興趣的部分是“cookie not found”例外。我發送的不是 cookie,而是不記名令牌。

我的猜測是我的 API 配置中缺少一些東西,它會告訴中間件查找 Bearer 令牌而不是 cookie。但是,當我嘗試配置要使用的中間件時,AddJwtBearer(...)我最終遇到了一系列全新的錯誤。所以問題是,從 Angular 前端獲取身份驗證 MSAL 令牌以在 API 后端上作業我缺少什么?
uj5u.com熱心網友回復:
@weichch 的評論讓我走上了正確的道路,但該示例使用了過時的代碼。我需要做的就是將 Startup.cs 檔案更改為類似于以下內容:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddOptions();
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
// Note: the middleware is Api not App... I accidentally called App, and it took
// me a minute to realize my mistake.
services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
services.AddControllers();
}
我的 Angular 應用程式中也有一個錯誤需要更正。我的 API 的范圍需要更改為我在 Azure 門戶中注冊的 API 在'api://47.../access_as_user'范圍更改之前,我收到了“Bearer error="invalid_token", error_description="The signature is invalid"” 錯誤。因此, app.module.ts 類似于以下內容:
@NgModule({
declarations: [...],
imports: [
...
MsalModule.forRoot(
new PublicClientApplication({
auth: {
clientId: '47...',
authority: 'https://login.microsoftonline.com/6d...',
redirectUri: 'https://localhost:4200',
},
cache: {
cacheLocation: 'localStorage',
storeAuthStateInCookie: false
},
}),
{
interactionType: InteractionType.Redirect,
// !!! Changed Here !!!
authRequest: { scopes: ['user.read', 'api://47.../access_as_user'] },
},
{
interactionType: InteractionType.Redirect,
protectedResourceMap: new Map([
['https://graph.microsoft.com/v1.0/me', ['user.read']],
// !!! Changed Here !!!
['https://localhost:44333/Auth/Index', ['api://47.../access_as_user']]
]),
},
),
RouterModule,
],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true,
}],
bootstrap: [AppComponent, MsalRedirectComponent],
})
export class AppModule {}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/345135.html
標籤:C# 有角的 asp.net-mvc .net-5 msal
