首页 > 解决方案 > 在 Blazor 页面中找不到 Startup 中添加的声明

问题描述

为了在基于 Azure B2C 的 Blazor 应用程序中获得组成员资格功能,我在 Startup.cs 的 Server 项目中添加了一些声明。当我检查剃刀页面中的用户对象时,我添加的声明不存在。

Startup.cs,公共无效配置():

            app.Use(async (context, next) =>
        {
            if (context.User != null && context.User.Identity.IsAuthenticated)
            {
                var groups = GetGroupsFromAzureB2c(context.User);
                
                // Attempt A, separate Identity
                ClaimsIdentity i = new(context.User.Identity);
                i.AddClaims(groups.Select(g => new Claim("Group", g)));
                context.User.AddIdentity(i);

                // Attempt B: Adding claims to the existing Identity
                ((ClaimsIdentity)context.User.Identity).AddClaims(groups.Select(g => new Claim("Group", g));
            }
            await next();
        });

page.razor,受保护的覆盖异步任务 OnInitializedAsync():

        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
    var user = authState.User;

    if (user.Identity.IsAuthenticated)
    {
        var _claims = user.Claims;
    }

_claims 仅包含自动添加的 12 个声明,而不是我在 Startup.cs 中添加的 4 个声明。

User 对象有不同的实例吗?我是否错误地添加了声明?

标签: c#blazorazure-ad-b2cblazor-webassemblyasp.net-core-5.0

解决方案


显然,在 Blazor 应用程序中有两个不同的身份在起作用。一个在客户端代码中,一个在服务器代码中。

我们通过添加一个CustomUserFactory继承自AccountClaimsPrincipalFactory<RemoteUserAccount>. 我们使用客户端的 Graph API 从中心方法检索 AzureB2C 角色,我们在 Program.cs 中调用

    builder.Services.AddMsalAuthentication(options =>
    {
        builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
        options.ProviderOptions.DefaultAccessTokenScopes.Add("xxx");
    })
        // here we hook up our custom factory
        .AddAccountClaimsPrincipalFactory<CustomUserFactory>(); 

对于服务器端代码,我们使用相同的中心方法从 AzureB2C 获取角色,我们从 Startup.cs 调用

    services.Configure<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme, options => {
        options.Events.OnTokenValidated = async context => {/*add roles here*/}

推荐阅读