c# - 在 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 对象有不同的实例吗?我是否错误地添加了声明?
解决方案
显然,在 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*/}
推荐阅读
- html - 按索引删除不起作用。角
- if-statement - If语句具有多个agruments来捕获鼠标位置
- mysql - sql-query 获取包含事务计数的报告
- django - django 使用自定义公司字段创建个人资料
- docplex - Docplex:构建表达式以从数组中获取值
- django - 使用 Docker 在本地运行 Django/Gunicorn 应用程序失败并显示 ERR_CONNECTION_REFUSED
- java - 将每个子字符串存储到不同的变量中
- python - 如何让 Selenium 切换到页面上的不同活动选项卡?
- r - R中的条件概率模拟
- javascript - 多个 HTML5 音频播放器 - 启动另一个时停止播放一个