我需要能够在应用程序控制器中随时向用户添加/删除声明。这怎么可能,步骤是什么?
我正在使用ASP.NET CORE RC1并使用Microsoft.AspNet.Authorization
。
例如:
public IActionResult ChangeUserInfo(int id, User user)
{
var mUser = db.Users.Where(d => d.UserId == id).First();
mUser.Email = user.Email;
// change claims, How?
db.SaveChanges();
return View();
}
I'm using the new Authentication API and NOT Identity!
编辑:
这是我为获取其他声明所做的一种方法,将它们添加到claimsidentity并将用户注销,然后再次登录用户,但它不起作用。 (如果用户手动注销,则可以使用)
public async Task<IActionResult> SingInAsync(HttpContext httpContext, string rememberme, bool forceSingOut = false, List<System.Security.Claims.Claim> additionalClaims = null)
{
var userIdentity = new ClaimsIdentity("SecureLogin");
userIdentity.AddClaims(_claims);
if(additionalClaims != null)
{
userIdentity.AddClaims(additionalClaims);
}
var userPrincipal = new ClaimsPrincipal(userIdentity);
if(forceSingOut)
{
await httpContext.Authentication.SignOutAsync("Cookie");
}
await httpContext.Authentication.SignInAsync("Cookie", userPrincipal,
new AuthenticationProperties
{
ExpiresUtc = (rememberme != null) ? DateTime.UtcNow.AddDays(int.Parse(_config["AppOptions:RememberMeDuration"])) : DateTime.UtcNow.AddMinutes(20),
IsPersistent = false,
AllowRefresh = false,
});
return null;
}
然后它被称为:
await customUserManager.SingInAsync(HttpContext, null, true, additClaims);
答案 0 :(得分:2)
您可以添加此类声明
public async Task<bool> AddClaim(string type, string value)
{
var username = User.GetUserName();
var user = await _userManager.FindByNameAsync(username);
Claim claimToAdd = new Claim(type, value);
var result = await _userManager.AddClaimAsync(user, claimToAdd);
return result.Succeeded;
}
删除声明非常相似,您只需使用_userManager.RemoveClaimAsync。
_userManager是UserManager的一个实例,您可以通过依赖注入将其注入控制器。
public ClaimController(UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
ILoggerFactory loggerFactory)
{
_userManager = userManager;
_roleManager = roleManager;
_logger = loggerFactory.CreateLogger<ClaimController>();
}