C# 用户登录后更新声明
是否可以在用户登录后更新声明?我在我的网站上有前端和管理面板,基本上我是用C# 用户登录后更新声明,c#,asp.net-mvc,asp.net-mvc-5,asp.net-identity,asp.net-identity-2,C#,Asp.net Mvc,Asp.net Mvc 5,Asp.net Identity,Asp.net Identity 2,是否可以在用户登录后更新声明?我在我的网站上有前端和管理面板,基本上我是用声明来实现这一点的。如果用户在前端以Susan身份登录,我在代码中执行了如下操作: var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); userIdentity.AddClaim(new Claim("Id", this.UserName)); ... //oth
声明来实现这一点的。如果用户在前端以Susan
身份登录,我在代码中执行了如下操作:
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
userIdentity.AddClaim(new Claim("Id", this.UserName));
... //other claims here
所以,当用户最终登录到管理面板时(仍然登录到前端),我只想添加更多声明,例如:
userIdentity.AddClaim(new Claim("BackEndId", this.UserName));
如何实现这一点?要能够读取cookie上的声明,您需要为我们的用户签名,并在同一请求期间再次将其重新登录:
idenityt.AddClaim(new Claim("myClaimType", "myClaimValue"));
var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
authenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, idenityt);
将函数添加到Identity.Config.cs中的ApplicationSignInManager类
以您发布的代码行为例有什么不对?
public override Task SignInAsync(ApplicationUser user, bool isPersistent, bool rememberBrowser)
{
var claims = new List<Claim>()
{
new Claim("Id", this.UserName),
new Claim("BackEndId", this.UserName)
};
this.AuthenticationManager.User.AddIdentity(new ClaimsIdentity(claims));
return base.SignInAsync(user, isPersistent, rememberBrowser);
}
private ClaimsPrincipal GetCurrentUser()
{
var context = HttpContext.GetOwinContext();
if (context == null)
return null;
if (context.Authentication == null || context.Authentication.User == null)
return null;
return context.Authentication.User;
}
private string GetUserId()
{
var user = GetCurrentUser();
if (user == null)
return null;
var claim = user.Claims.FirstOrDefault(o => o.Type == "Id");
if (claim == null)
return null;
return claim.Value;
}
private string GetBackEndId()
{
var user = GetCurrentUser();
if (user == null)
return null;
var claim = user.Claims.FirstOrDefault(o => o.Type == "BackEndId");
if (claim == null)
return null;
return claim.Value;
}