asp.net-mvc-5 – MVC 5 – 向用户添加声明

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-5 – MVC 5 – 向用户添加声明前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在开发一个MVC 5互联网应用程序,并使用Identity 2.1.

用户登录后,我如何向用户添加声明,我知道用户名

这是我有的:

  1. public void AddClaimToUser(string userName,string type,string value )
  2. {
  3. var AuthenticationManager = HttpContext.Current.GetOwinContext().Authentication;
  4. var Identity = new ClaimsIdentity(userName);
  5. Identity.AddClaim(new Claim(type,value));
  6. AuthenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(Identity),new AuthenticationProperties { IsPersistent = true });
  7. }@H_403_7@
  8. 但是,在我调用方法并检查用户的声明后,未列出添加的声明.

  9. 这是我用来在控​​制器中获取声明的代码

  10. var identity = (ClaimsIdentity)User.Identity;
  11. IEnumerable<Claim> claims = identity.Claims;@H_403_7@ 
  12.  

    提前致谢.

解决方法

首先,你必须在IdentityModels.cs类下创建一个添加声明的方法.就像这样,在下面的代码中我创建了一个对CompanyId的声明.
  1. public class ApplicationUser : IdentityUser
  2. {
  3. public string FirstName { get; set; }
  4. public string LastName { get; set; }
  5. public bool IsActive { get; set; }
  6. public int? CompanyId { get; set; }
  7.  
  8.  
  9. public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
  10. {
  11.  
  12. var userIdentity = await manager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie);
  13.  
  14. userIdentity.AddClaim(new Claim("CompanyId",(this.CompanyId + "" ?? "0")));
  15.  
  16. return userIdentity;
  17. }}@H_403_7@
  18. 在编写上面的代码之后,您需要在IdentityConfig.cs中再编写一个方法

  19. public static class IdentityExtensions{
  20. public static int CompanyId(this IIdentity identity)
  21. {
  22.  return Convert.ToInt32(((ClaimsIdentity)identity).FindFirst("CompanyId").Value);
  23. }}@H_403_7@ 
  24.  

    在此之后,只需输入即可在任何控制器中获取您创建的声明.

  25.   
  26.  
    int companyId = User.Identity.CompanyId();@H_403_7@

猜你在找的asp.Net相关文章