"Authorization failed. AuthenticationScheme: AzureADJwtBearer was challenged" 在 ASP.NET Core 3.1 Web API - 401 未经授权

"Authorization failed. AuthenticationScheme: AzureADJwtBearer was challenged" in ASP.NET Core 3.1 Web API - 401 Unauthorized

我正在尝试使用 Azure AD 对我的网站 api 进行身份验证。

我正在关注这个 tutorial 并且我使用我的 Angular 应用程序成功通过了身份验证。

问题是,当我将 Authorize 属性放入我的控制器时,它会在我的 angular 控制台甚至我的 post 人员中出现 401 Unauthorized 错误。

当我查看我的网络 api 日志时,它显示如下:

Image here

这是我的 Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // removed because this doesn't work either
    // services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)           
    //          .AddAzureADBearer(options => Configuration.Bind("AzureActiveDirectory", options));

    services.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme)
            .AddAzureADBearer(options => Configuration.Bind("AzureActiveDirectory", options));

    services.Configure<JwtBearerOptions>(AzureADDefaults.JwtBearerAuthenticationScheme, options =>
    {
                // This is a Microsoft identity platform web API.
        options.Authority += "/v2.0";
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
   if (env.IsDevelopment())
   {
        app.UseDeveloperExceptionPage();
   }

   app.UseRouting();

   app.UseAuthentication();
   app.UseAuthorization();

   app.UseEndpoints(endpoints =>
   {
        endpoints.MapControllers();
   }
}

在我的 appsettings.json:

"AzureActiveDirectory": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "myorg.onmicrosoft.com",
    "TenantId": "241234-12ad-1234-1234-123412341234", // sample only
    "ClientId": "8786687-12ad-1234-1234-2341432341" // sample only client id from the webapi in the ad
},

在我的 App Client 中,这是我的 app.module.ts

// MSAL Imports
import {
   MsalModule,
   MsalInterceptor,
   MSAL_CONFIG,
   MSAL_CONFIG_ANGULAR,
   MsalService,
   MsalAngularConfiguration
 } from '@azure/msal-angular';
import { Configuration } from 'msal';

// MSAL Configs
export const protectedResourceMap:[string, string[]][]=[['https://localhost:5000/', ['api://WEB-API-CLIENTID/api-access']] ];

const isIE = window.navigator.userAgent.indexOf("MSIE ") > -1 || window.navigator.userAgent.indexOf("Trident/") > -1;

function MSALAngularConfigFactory(): MsalAngularConfiguration {
   return {
     popUp: !isIE,
     consentScopes: [
       "user.read",
       "openid",
       "profile",
       "api://WEBAPI-CLIENT-ID/api-access"
     ],
     unprotectedResources: ["https://www.microsoft.com/en-us/"],
     protectedResourceMap,
     extraQueryParameters: {}
   };
 }

 function MSALConfigFactory(): Configuration {
   return {
     auth: {
       clientId: 'ANGULAR-CLIENT-ID',
       authority: "https://login.microsoftonline.com/TENANT-ID", /// with tenant id
       validateAuthority: true,
       redirectUri: "http://localhost:4200/",
       postLogoutRedirectUri: "http://localhost:4200/",
       navigateToLoginRequestUrl: true,
     },
     cache: {
       cacheLocation: "localStorage",
       storeAuthStateInCookie: isIE, // set to true for IE 11
     },
   };
 }

@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      AppRoutingModule,
      HttpClientModule,
      RouterModule.forRoot(appRoutes),
      NgHttpLoaderModule.forRoot(),

      FormsModule,
      // msal angular
      MsalModule
   ],
   providers: [
      {
         provide: HTTP_INTERCEPTORS,
         useClass: MsalInterceptor,
         multi: true
       },
       {
         provide: MSAL_CONFIG,
         useFactory: MSALConfigFactory
       },
       {
         provide: MSAL_CONFIG_ANGULAR,
         useFactory: MSALAngularConfigFactory
       },
       MsalService
   ],
   bootstrap: [
      AppComponent
   ]
})
export class AppModule { }

其他信息:我已经看到了这个 但它无助于解决我的问题。

我期待有人的帮助。

BearerAuthenticationScheme Azure Active Directory B2C Bearer 的默认方案。如果您正在使用,AddAzureADB2CBearer(AuthenticationBuilder, Action<AzureADB2COptions>) 然后使用 JwtBearerAuthenticationScheme 否则,使用默认承载方案。

services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
            .AddAzureADBearer(options => Configuration.Bind("AzureActiveDirectory", options));

请仔细检查您的 clientId 是否已正确分配给您的应用。如果它不符合其安全要求,抛出 401 unauthorized 是正常的。

如果您可以获得 accessToken,请尝试它是否是有效的访问令牌。访问这个 jwt.ms。如果有效,它应该可以使用 Postman。确保使用 Authorization Bearer your_accessToken_here

你应该期待邮递员 200 Ok。现在,在您的 angular 应用程序上尝试一下。