ASP.NET Core 3.1 Web API中的“授权失败。AuthenticationScheme:AzureADJwtBearer受到挑战”-401未经授权

时间:2020-03-19 15:05:35

标签: c# angular azure-active-directory asp.net-core-webapi openid-connect

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

我正在遵循此tutorial,并且已成功使用我的Angular应用程序进行了身份验证。

问题是,当我在控制器中放置Authorize属性时,它在我的角度控制台甚至邮递员中出现了401 Unauthorized错误。

当我查看Web 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客户端中,这是我的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 { }

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

我期待有人的帮助。

1 个答案:

答案 0 :(得分:1)

BearerAuthenticationScheme Azure Active Directory B2C承载的默认方案。如果您使用的是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的邮递员。现在,在您的角度应用程序上尝试一下。