【问题标题】:Using ASP.Net Core Identity and Azure authentication together in Blazor在 Blazor 中同时使用 ASP.Net Core Identity 和 Azure 身份验证
【发布时间】:2021-05-28 07:25:25
【问题描述】:

我有一个服务器端 Blazor 应用程序,它已成功与 Azure 集成以进行身份​​验证。标准方法在这里有效,我将 Startup.cs 修改如下:

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                    .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
            services.AddControllersWithViews()
                    .AddMicrosoftIdentityUI();
            services.AddAuthorization(options => {
                // By default, all incoming requests will be authorized 
                // according to the default policy
                options.FallbackPolicy = options.DefaultPolicy;
            });

然后我在 MainLayout.razor 中检查身份验证,如下所示:

    protected override async Task OnInitializedAsync()
    {
        AuthenticationState authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        System.Security.Claims.ClaimsPrincipal user = authState.User;
        System.Security.Principal.IIdentity userIdent = user.Identity;
        if (userIdent.IsAuthenticated)
        {
            doMoreStuff(user);
        }
        ...
    }

我还想通过 Identity 使用自定义 UserStore 和 RoleStore 实现启用授权(不使用实体框架核心)。我开始实现用户存储和角色存储,并将它们添加到 Startup.cs:

IdentityBuilder builder = services.AddIdentity<MyUser, MyRole>()
                .AddDefaultTokenProviders();            
builder.Services.AddScoped(typeof(IUserStore<>).MakeGenericType(builder.UserType), typeof(MyUserManager));
builder.Services.AddScoped(typeof(IRoleStore<>).MakeGenericType(builder.RoleType), typeof(MyRoleManager));

但是一旦我添加了这些自定义身份添加,我立即看到 MainLayout 中调用 AuthorizationStateProvider.GetAuthenticationStateAsync() 的代码现在返回 null。

关于如何实现自定义身份和 Azure 身份验证的任何建议?他们不想和我一起玩得很好。

【问题讨论】:

  • 附注你不能像services.AddScoped&lt;IUserStore&lt;MyUser&gt;, MyUserManager&gt;();那样做些事情吗?
  • @JHBonarius 是的,我玩得更多,结果发现一种解决方案是完全避免 services.AddIdentity() 方法调用......在这种情况下,我手动添加我的应用程序声明(角色,等)在 Azure GetAuthenticationStateAsync() 成功完成后发送给委托人。在这种情况下,我可以根据需要只添加范围内的商店。感谢您抽出宝贵时间回复!

标签: c# azure authentication blazor identity


【解决方案1】:

回答了我自己的问题,其实我找到了一些好的建议here

该方法似乎只是获取 Azure 返回的 ClaimsPrincipal,然后从应用程序中添加您自己的其他 Claims。

【讨论】:

  • 改版的程序员是个不错的博客,顺带一提。他知道他的东西。
猜你喜欢
  • 2018-07-06
  • 1970-01-01
  • 1970-01-01
  • 2020-05-28
  • 2018-12-30
  • 2018-03-10
  • 2019-10-08
  • 2022-06-13
  • 2015-10-18
相关资源
最近更新 更多