如何从核心项目重新生成开放ID连接自定义声明 asp.net?
我已经设置了手动映射到声明类型名称,但有时我需要从事件 OnTicketReceived 外部更新其他声明,即从控制器更新,因此在该阶段我确实需要以某种方式重新生成声明。我通过以下方式设置了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(。
这是在登录事件之外更新声明的方法。更新是一种控制器方法。
public async Task Update()
{
AuthenticateResult authenticateResult = await HttpContext.AuthenticateAsync();
// Make a copy of the principal so we can modify it's claims
ClaimsPrincipal newPrincipal = new ClaimsPrincipal(User.Identity)
ClaimsIdentity claimsIdentity = (ClaimsIdentity)newPrincipal.Identity;
// Add/remove claims
claimsIdentity.AddClaim(new Claim("name", "value"));
Claim toRemove = claimsIdentity.Claims.FirstOrDefault(c => string.Equals(c.Type, "claimnametoremove", StringComparison.Ordinal));
if (toRemove != null)
claimsIdentity.RemoveClaim(toRemove);
// If these aren't updated, calls to "User" will pull the old principal value
HttpContext.User = newPrincipal;
Thread.CurrentPrincipal = newPrincipal;
// Sign in the user with the new principal to "refresh" our logged-in user
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, newPrincipal, authenticateResult.Properties);
}
如果要在
init 登录后在控制器中添加声明,则应使身份验证管理器使用新标识:
if (HttpContext.User.Identity is ClaimsIdentity identity)
{
identity.AddClaim(new Claim("userId", "1234"));
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(HttpContext.User.Identity));
}