简体   繁体   English

Blazor WASM 中的 Azure b2c 授权返回 401(未授权)

[英]Azure b2c authorization return 401 (Unauthorized) in Blazor WASM

I'm using Azure AD B2C as the authentication provider for ASP.NET Blazor WASM application and API .我正在使用 Azure AD B2C 作为 ASP.NET Blazor WASM 应用程序和API的身份验证提供程序So the problem is that I'm not able to access the API endpoints from the client which is Blazor WASM.所以问题是我无法从client访问API端点,即 Blazor WASM。 When I make the request to the API I get 401 (Unauthorized) response.当我向 API 发出请求时,我收到 401(未经授权)响应。

Here is the console error这是控制台错误

crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: Response status code does not indicate success: 401 (Unauthorized).
System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at System.Net.Http.Json.HttpClientJsonExtensions.<GetFromJsonAsyncCore>d__13`1[[Organizer.Web.Shared.Models.SuccessResultModel`1[[Organizer.Web.Shared.DTOs.UserDto, Organizer.Web.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], Organizer.Web.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
   at Organizer.Web.Pages.Authentication.AccountProfile.OnInitializedAsync() in A:\Software_Development\2022\Organizer\Organizer.Web.Pages\Authentication\AccountProfile.razor.cs:line 57
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)

B2C Client settings B2C 客户端设置Azure 客户端设置

B2C API settings B2C API 设置在此处输入图像描述

Blazor Client Appsettings and Program.cs Blazor 客户端 Appsettings 和 Program.cs

builder.Services.AddHttpClient("Organizer.API", client => client.BaseAddress = new Uri("https://localhost:7149"))
    .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("Organizer.API"));

builder.Services.AddMsalAuthentication(options =>
{
    builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
    options.ProviderOptions.DefaultAccessTokenScopes.Add(
        "https://mydomain.onmicrosoft.com/60dbe9eb-056c-400d-a98d-c5c95b2bb000/Data.Read");
    options.ProviderOptions.LoginMode = "redirect";
});
{
  "AzureAdB2C": {
    "Authority": "https://mydomain.b2clogin.com/mydomain.onmicrosoft.com/B2C_1_susi",
    "ClientId": "f2161189-4bc6-4c26-99ae-a82b6729ab33",
    "ValidateAuthority": false
  }
}

API API

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAdB2C"));
"AzureAdB2C": {
    "Instance": "https://mydomain.b2clogin.com/",
    "ClientId": "60dbe9eb-056c-400d-a98d-c5c95b4bb176",
    "Domain": "mydomain.onmicrosoft.com",
    "TenantId": "1a5a2799-8dde-4236-901f-c37b3d2b9b39",
    "Scopes": "Data.Read",
    "SignUpSignInPolicyId": "B2C_1_susi",
    "CallbackPath": "/authentication/login-callback"
}

Note: I have changed the guids and URLs for security reasons.注意:出于安全原因,我更改了 guid 和 URL。

  • Please make sure scope is correct.scope not configured properly may be the reason prevent client app cannot access web API endpoints请确保 scope 正确。scope 未正确配置可能是阻止客户端应用程序无法访问 web ZDB974238714CA8DE4FZA 端点的原因
  • If appId uri is jus api:// client id, use client id or if it custom uri place that while adding scopes like below in place of clientId in Program.cs of the Client app:如果 appId uri 是 jus api:// 客户端 ID,请使用客户端 ID,或者如果它自定义 URI,则在客户端应用程序的 Program.cs 中添加如下范围代替 clientId 时:
 options.ProviderOptions.DefaultAccessTokenScopes.Add("https://{TENANT}.onmicrosoft.com/{ API app CLIENTID OR custom value}/{DEFAULT Scope}");

For ex:例如:

.Add("https://contoso.onmicrosoft.com/41xxxa7xxxx-4xxx3-8fxx-6xxxxxxxfd/API.Access");

And then please try if you can set API app for a matching audience in the API app settings file (appsettings.json) which is nothing but "Audience": https://{TENANT}.onmicrosoft.com/{ API APP CLIENT ID OR CUSTOM VALUE if present} And then please try if you can set API app for a matching audience in the API app settings file (appsettings.json) which is nothing but "Audience": https://{TENANT}.onmicrosoft.com/{ API APP CLIENT ID OR CUSTOM VALUE if present}

Ex:前任:

{
  "AzureAdb2c": {
    "Authority": " ",
    "ClientId": "xxxxxxxxxx1fdxx",
    "ValidateAuthority": true,
    "Audience": "https://contoso.onmicrosoft.com/<client/appId>"
     ...
  }
}

the end of the Audience need not be scope /{DEFAULT SCOPE}.观众的结尾不必是 scope /{DEFAULT SCOPE}。

  • Just to recheckt,please make sure Instance,Authority, Tenant ID, Tenant domain, Client ID, or Redirect URI, are all configured correct in your application and that matches the ones in azure portal只是为了重新检查,请确保实例、权限、租户 ID、租户域、客户端 ID 或重定向 URI 在您的应用程序中都配置正确,并且与 azure 门户中的匹配
  • Also please check all API permissions which are required are granted to access web API endpoints.另请检查所有API permissions ,这些权限已授予访问 web API 端点所需的权限。

Reference : Secure an ASP.NET Core Blazor WebAssembly standalone app with Azure Active Directory B2C |参考使用 Azure Active Directory B2C 保护 ASP.NET 核心 Blazor WebAssembly 独立应用程序 | Microsoft Docs 微软文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET Core 3.1 如何使用 Azure AD B2C 返回 401 Unauthorized 而不是 Challenge - ASP.NET Core 3.1 how to return 401 Unauthorized instead of Challenge with Azure AD B2C 401 在 Xamarin.Forms 上未经 Azure b2c 授权 - 401 Unauthorized with Azure b2c on Xamarin.Forms Blazor WASM + AAD B2C + 自定义授权 - Blazor WASM + AAD B2C + Custom Authorisation Azure B2C Active Directory OpenIDConnect和授权代码 - Azure B2C Active Directory OpenIDConnect and Authorization Codes 通过 REST API 创建 B2C 租户返回 401/Unauthorized - Creating a B2C Tenant via the REST API returns 401/Unauthorized Blazor WA 托管 - 401 在 Azure AppService 上未经授权 - Blazor WA hosted - 401 Unauthorized on Azure AppService Blazor ServerApp Azure b2C - 如何允许匿名访问网站并且不显示 SigninSignUp B2C 登录页面 web 开始 - Blazor ServerApp Azure b2C - how to Allow Anonymous Access To Website and not display SigninSignUp B2C Login page on web start Blazor 服务器端和 Azure B2C 使用邀请登录,如何使用返回的令牌进行身份验证? - Blazor Server Side and Azure B2C Login using invite, how to authenticate with returned token? 无法使用 Blazor 服务器应用程序调用安全下游 Web API 使用 Azure AD B2C - Cannot get a Blazor Server App to call a secure downstream Web API using Azure AD B2C 如何从blazor app调用Azure AD B2C edit profile user flow? - How to call Azure AD B2C edit profile user flow from blazor app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM