带有ASP.NET Core Web API的Angular msal_Angular返回无效令牌无效签名AzureAD



我按照这个例子构建了一个Angular应用程序:https://github.com/microsoftgraph/msgraph-training-angularspa

我可以从Angular应用程序登录甚至验证MS Graph。

我正在尝试将令牌传递给我创建的API服务。然而,我不断得到以下错误:

WWW身份验证:承载错误="invalid_token",errordescription="签名无效">

到目前为止,我已经尽了一切可能,但运气不佳。我继续收到这个错误。我试过AzureADBearer库:

services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options => 
{
options.Authority += "/v2.0";
options.TokenValidationParameters.ValidAudiences = new string[]
{
options.Audience, $"api://{options.Audience}"
};
options.TokenValidationParameters.ValidateIssuer = false;
options.TokenValidationParameters.IssuerValidator = AadIssuerValidator.GetIssuerValidator(options.Authority).Validate;
});

我也尝试过Microsoft.Identity.Web库,但我得到了相同的错误:

services.AddProtectedWebApi(Configuration);

我已经搜索了几天了,我发现其他人也有同样的问题,但到目前为止还没有明确的解决方案。如有任何帮助,我们将不胜感激。

编辑

我正在尝试为我的组织构建一个使用我们的AzureAD进行身份验证的应用程序。该应用程序的前端是Angular,后端是aspnetcore webapi。我对如何实现这一目标并不太挑剔。只是想把它做完。

因此,经过Junnas和NanYu的一些帮助和一些旧帖子,我解决了这个问题。在我之前的设置中,我将Api和MS Graph的作用域放在一起,但问题是每个作用域返回的令牌不同。当到达不同的Api时,我需要获得不同的代币(mine vs Graph(。在分离作用域并独立获取令牌之后,我能够同时对两者进行身份验证。此外,如果设置正确,MsalInterceptor也能很好地工作,使我不用编写单独的调用来获取令牌。这是我的代码:

oauth.ts

export const OAuthSettings = {
appId: '{client Id}',
authority: 'https://login.microsoftonline.com/{tenant Id}',
apiScopes: [
'api://{api id}/access_as_user'
],
graphScopes: [
'user.read'
]
}

应用程序模块.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MsalModule, MsalInterceptor } from '@azure/msal-angular';
import { LogLevel } from 'msal';
import { AppComponent } from './app.component';
import { OAuthSettings } from '../oauth';
// this is only for logging and tracing
export function msalLogCallBack(level: LogLevel, message: string, containsPii: boolean) {
console.log('[MSAL]:' + message);
}
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule,
MsalModule.forRoot({
clientID: OAuthSettings.appId,
authority: OAuthSettings.authority,
unprotectedResources: ['{angular app uri}'],
protectedResourceMap: [
['{api endpoint}', OAuthSettings.apiScopes],
['https://graph.microsoft.com/v1.0/me', OAuthSettings.graphScopes]
],
level: LogLevel.Verbose,
logger: msalLogCallBack
})
],
providers: [ {
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
}],
bootstrap: [AppComponent]
})
export class AppModule { }

从这一点开始,对Api的任何调用都将被截获,并且MsalInterceptor将在调用的头中附加正确的令牌。

最新更新