我在MVC项目中使用FederatedAuthentication
类。
要创建Cookie,我使用FederatedAuthentication.SessionAuthenticationModule.CreateSessionCookie(...);
,但如果用户想要更改其名字,我似乎找不到更新它们的方法。
如何在不注销的情况下访问和更新声明?
答案 0 :(得分:1)
这个过程非常简单
正常验证,传递声明列表。
var claims = FederatedAuthentication.SessionAuthenticationModule
.ContextSessionSecurityToken.ClaimsPrincipal.Claims.ToList();
var givenNameClaim = claims.Single(x => x.Type == "given_name");
var familyNameClaim = claims.Single(x => x.Type == "family_name");
var timeZoneClaim = claims.Single(x => x.Type == "time_zone_string");
var newName = new Claim(givenNameClaim.Type.ToString(), model.FirstName, givenNameClaim.ValueType, givenNameClaim.Issuer);
var familyName = new Claim(familyNameClaim.Type.ToString(), model.LastName, familyNameClaim.ValueType, familyNameClaim.Issuer);
var timeZone = new Claim(timeZoneClaim.Type.ToString(), model.SelectedTimeZone, timeZoneClaim.ValueType, timeZoneClaim.Issuer);
UpdateClaims(newName, familyName, timeZone);
public void UpdateClaims(params Claim[] updatedClaims)
{
var currentClaims = FederatedAuthentication.SessionAuthenticationModule.ContextSessionSecurityToken.ClaimsPrincipal.Claims.ToList();
foreach (var claim in updatedClaims)
{
currentClaims.Remove(currentClaims.Single(x => x.Type == claim.Type));
currentClaims.Add(claim);
}
var principal = new ClaimsPrincipal(new ClaimsIdentity[] { new ClaimsIdentity(currentClaims, "Auth0") });
var session = FederatedAuthentication.SessionAuthenticationModule.CreateSessionSecurityToken(
principal,
null,
DateTime.UtcNow,
DateTime.MaxValue.ToUniversalTime(),
true);
FederatedAuthentication.SessionAuthenticationModule.AuthenticateSessionSecurityToken(session, true);
}