You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor Server+Azure B2C邀请注册:Token认证及名称为空问题

Blazor Server Azure B2C邀请注册后User.Identity.Name为空的解决方案

问题根源

邀请注册流程返回的id_token中缺失User.Identity.Name对应的声明,或者认证配置未正确映射该声明(常规登录的用户流已配置正确,所以正常)。

具体解决步骤

1. 确认Azure B2C用户流/自定义策略的声明输出

  • 登录Azure B2C门户,找到邀请注册对应的用户流(或自定义策略)
  • 进入应用程序声明页面,确保勾选了显示名称(对应name声明),或者你期望作为用户名的其他字段(如名字+姓氏)
  • 保存用户流并重新运行注册测试

2. 配置OpenIdConnect的声明映射

在Program.cs(或Startup.cs)的认证配置中,手动指定NameClaimType,或添加声明转换逻辑:

services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
    // 其他Azure B2C相关配置(如Authority、ClientId等)
    options.TokenValidationParameters = new TokenValidationParameters
    {
        // 指定Name对应的声明类型,根据Azure B2C返回的声明调整
        NameClaimType = "name", 
        RoleClaimType = "roles"
    };

    // 若需要组合given_name和family_name作为用户名,添加以下事件逻辑
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = context =>
        {
            var givenName = context.Principal.FindFirstValue("given_name");
            var familyName = context.Principal.FindFirstValue("family_name");
            if (!string.IsNullOrWhiteSpace(givenName) && !string.IsNullOrWhiteSpace(familyName))
            {
                var fullName = $"{givenName} {familyName}";
                context.Principal.Identities.First().AddClaim(new Claim(ClaimTypes.Name, fullName));
            }
            return Task.CompletedTask;
        }
    };
});

3. 正确在Blazor组件中获取用户信息

Blazor Server中避免直接依赖HttpContext,通过AuthenticationStateProvider获取用户状态:

@inject AuthenticationStateProvider AuthStateProvider

<p>当前用户名: @userName</p>

@code {
    private string? userName;

    protected override async Task OnInitializedAsync()
    {
        var authState = await AuthStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;
        userName = user.Identity?.Name;
    }
}

4. 调试验证声明内容

在OnTokenValidated或TicketReceived事件中打印所有声明,确认邀请注册返回的声明是否包含目标字段:

options.Events = new OpenIdConnectEvents
{
    OnTokenValidated = context =>
    {
        foreach (var claim in context.Principal.Claims)
        {
            Console.WriteLine($"声明类型: {claim.Type}, 值: {claim.Value}");
        }
        // 其他逻辑...
        return Task.CompletedTask;
    }
};

若缺失目标声明,回到Azure B2C配置补充输出声明。

内容的提问来源于stack exchange,提问作者Gaz83

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 06:35:26