【发布时间】: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<IUserStore<MyUser>, MyUserManager>();那样做些事情吗? -
@JHBonarius 是的,我玩得更多,结果发现一种解决方案是完全避免 services.AddIdentity() 方法调用......在这种情况下,我手动添加我的应用程序声明(角色,等)在 Azure GetAuthenticationStateAsync() 成功完成后发送给委托人。在这种情况下,我可以根据需要只添加范围内的商店。感谢您抽出宝贵时间回复!
标签: c# azure authentication blazor identity