Azure AD B2C远程用户配置编辑:redirect-uri处理难题
解决Blazor WASM + Azure AD B2C Profile编辑后声明不更新的问题
核心问题原因
Azure AD B2C Profile Editing用户流完成后会返回带code的重定向请求,你的应用未正确处理这个回调请求完成token交换,导致本地用户会话的ClaimsPrincipal未更新,只能等下次登录刷新token才会显示新属性。
具体解决步骤
1. 配置Azure AD B2C的重定向URI
- 进入Azure AD B2C的应用注册,添加新的重定向URI:
https://你的应用域名/authentication/profile-callback - 打开Profile Editing用户流的配置,在「应用程序」设置中,将「回复URL」设置为上述URI
2. 确保Authentication页面支持Profile回调处理
你的Authentication.razor页面已经使用RemoteAuthenticatorView,无需额外新增页面,只需确保它能接收profile-callback动作:
@page "/authentication/{action}" @using Microsoft.AspNetCore.Components.WebAssembly.Authentication <RemoteAuthenticatorView Action="@Action" /> @code { [Parameter] public string Action { get; set; } }
3. 完善MSAL认证配置
在Program.cs中,确保AddMsalAuthentication的配置正确关联Profile流程:
builder.Services.AddMsalAuthentication(options => { builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication); // 添加你的API权限 scope options.ProviderOptions.DefaultAccessTokenScopes.Add("https://你的租户ID.onmicrosoft.com/api/access_as_user"); // 指定Profile编辑的触发路径 options.UserOptions.RemoteProfilePath = "/authentication/profile"; }) // 可选:自定义声明映射,确保更新的属性能同步到ClaimsPrincipal .AddAccountClaimsPrincipalFactory<CustomAccountClaimsPrincipalFactory>();
4. 自定义声明映射(可选)
如果需要将B2C返回的自定义属性同步到用户声明,实现AccountClaimsPrincipalFactory:
public class CustomAccountClaimsPrincipalFactory : AccountClaimsPrincipalFactory<RemoteUserAccount> { public CustomAccountClaimsPrincipalFactory(IAccessTokenProviderAccessor accessor) : base(accessor) { } public override async ValueTask<ClaimsPrincipal> CreateUserAsync(RemoteUserAccount account, RemoteAuthenticationUserOptions options) { var user = await base.CreateUserAsync(account, options); if (user.Identity is not ClaimsIdentity identity) return user; // 示例:同步displayName属性 if (account.AdditionalProperties.TryGetValue("displayName", out var displayName)) { identity.AddClaim(new Claim(ClaimTypes.Name, displayName.ToString())); } // 同步其他自定义属性 if (account.AdditionalProperties.TryGetValue("extension_你的自定义属性", out var customProp)) { identity.AddClaim(new Claim("extension_你的自定义属性", customProp.ToString())); } return user; } }
5. 测试流程
- 用户访问
/authentication/profile,自动跳转至Azure AD B2C的Profile编辑页面 - 修改属性并保存后,B2C会重定向到
/authentication/profile-callback RemoteAuthenticatorView自动处理code,交换获取包含新属性的ID Token- 应用自动更新本地用户的ClaimsPrincipal,无需重新登录即可看到新数据
- 处理完成后,会自动跳转到应用的默认回调后页面(可通过配置修改跳转目标)
内容的提问来源于stack exchange,提问作者Roberto Ferraris
相关产品推荐
相关产品推荐

