c# - 如何使 Asp.Net Core Identity 与 OpenIdConnect 一起使用
问题描述
如何从 asp.net 核心项目重新生成 open id connect 自定义声明?
我已经设置手动映射到声明类型名称,但有时我需要从事件 OnTicketRecieved 之外更新其他声明,即来自控制器,所以在那个阶段我确实需要以某种方式重新生成声明。我通过以下方式设置了 openIdConnect:
_services
.AddAuthentication(options =>
{
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddOpenIdConnect(options =>
{
options.ClientId = clientId;
options.ClientSecret = clientSecret;
options.Authority = $"{baseAuthorityUrl}/{tenantId}";
options.CallbackPath = new PathString(callBackPath);
options.Scope.Add("email");
options.Scope.Add("profile");
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name"
};
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Events = new OpenIdConnectEvents
{
OnRedirectToIdentityProvider = e =>
{
return Task.CompletedTask;
},
OnTicketReceived = e =>
{
e.Principal.Identities.First().AddClaim(new Claim(ClaimTypes.Name, e.Principal.FindFirstValue("name")));
return Task.CompletedTask;
}
};
})
我怎样才能从控制器重新生成索赔?我在想以某种方式覆盖 signInManager.RefreshSignInAsync(user)。
解决方案
如果要在初始化登录后在控制器中添加声明,则应使身份验证管理器使用新身份:
if (HttpContext.User.Identity is ClaimsIdentity identity)
{
identity.AddClaim(new Claim("userId", "1234"));
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(HttpContext.User.Identity));
}
推荐阅读
- typescript - 打字稿、复杂对象和联合类型
- reactjs - React 仅针对具有省略号的文本显示 Material-UI 工具提示
- directus - 无法在 Directus 中访问用户令牌
- angular - 如何比较和访问 Angular 8+ HTML 模板中的枚举变量?
- php - wordpress url中的非英文字符导致404错误
- gradle - 将 Gradle 从 Groovy 转换为 Kotlin DSL(用于 liquibase-gradle-plugin)
- c++ - 实时更新VTK点
- java - 列表视图不可点击
- python - 读入文件中一行的前 4 位并存储
- python - 如何使用 Python 使用 Github Markdown API