Azure AD B2C授权在Blazor WASM调用API时返回401未授权问题
Blazor WASM 调用受Azure AD B2C保护的API返回401未授权
问题描述
使用Azure AD B2C作为ASP.NET Blazor WASM应用及API的身份认证提供者,但Blazor WASM客户端无法访问API端点,调用时收到401(Unauthorized)响应。
控制台错误信息
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配置截图
客户端设置

API设置

Blazor客户端配置
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"; });
appsettings.json
{ "AzureAdB2C": { "Authority": "https://mydomain.b2clogin.com/mydomain.onmicrosoft.com/B2C_1_susi", "ClientId": "f2161189-4bc6-4c26-99ae-a82b6729ab33", "ValidateAuthority": false } }
API配置
Program.cs
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAdB2C"));
appsettings.json
"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" }
说明:出于安全考虑,已修改GUID及URL信息。
排查解决方案
- 修正API范围与ClientID匹配问题:客户端配置中引用的API ID(60dbe9eb-056c-400d-a98d-c5c95b2bb000)与API配置的ClientId(60dbe9eb-056c-400d-a98d-c5c95b4bb176)不一致,需将客户端的
DefaultAccessTokenScopes中的API ID替换为正确的API ClientId,确保范围格式为https://mydomain.onmicrosoft.com/[API-Client-ID]/Data.Read。 - 验证令牌受众:使用JWT解码工具检查客户端获取的AccessToken,确认
aud(受众)声明与API的ClientId完全匹配,若不匹配则说明范围配置错误。 - 确认API权限授予:在Azure AD B2C客户端应用的权限设置中,检查是否已添加目标API的
Data.Read权限,且完成管理员同意操作(针对租户级权限)。 - 调整API的Scope配置:API的
appsettings.json中Scopes需设置为完整的范围值(如https://mydomain.onmicrosoft.com/[API-Client-ID]/Data.Read),而非仅Data.Read,确保验证逻辑能正确匹配令牌中的范围声明。 - 检查消息处理器关联:确认
BaseAddressAuthorizationMessageHandler绑定的API BaseAddress与实际API地址完全一致,避免因地址不匹配导致令牌未被附加到请求中。
内容的提问来源于stack exchange,提问作者Mohammed Alwedaei
相关产品推荐
相关产品推荐

