【问题标题】:ASP.net MVC Custom ClaimsASP.net MVC 自定义声明
【发布时间】:2021-09-09 20:48:08
【问题描述】:

当用户登录系统时,我正在调用用户访问权限。在我的用户访问包括 UserName,UserRole,UserId,ReqAccess,ViewAccess 等。

在我的声明中,我可以添加用户 ID 和用户名,但我想添加对单独声明的其他访问权限,但是当我键入 claims.Add(new Claim(ClaimTypes. 时,列表仅显示列出的项目。如何添加自己的声明并添加它们?

public void SignInUser(string username, string userRole, string userid, bool isPersistent)
        {
            // Initialization.    
            var claims = new List<Claim>();
            try
            {
                // Setting    
                claims.Add(new Claim(ClaimTypes.Name, username));
                claims.Add(new Claim(ClaimTypes.Role, userRole));
                claims.Add(new Claim("UserId", userid));
                

                var claimIdenties = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
                var ctx = Request.GetOwinContext();
                var authenticationManager = ctx.Authentication;
                // Sign In.    
                authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, claimIdenties);

               
                var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
                var claimsPrincipal = new ClaimsPrincipal(identity);
                Thread.CurrentPrincipal = claimsPrincipal;
            }
            catch (Exception ex)
            {
                // Info    
                throw ex;
            }
        }

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    我这样做了,它工作正常:

    var user = await UserManager.FindAsync(model.Email, model.Password);
    if (user != null)
    {
        var identity = UserManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
        identity.AddClaims(new[] 
        { 
            new Claim("FullName", user.FullName),
            new Claim("roleId", user.Roles.FirstOrDefault().RoleId),
        });
        
        AuthenticationManager.SignIn( new AuthenticationProperties() { IsPersistent = true }, identity);
        return View();
    }
    

    获取用户详细信息并将其保存在声明中。

    【讨论】:

    • 谢谢@AribYousuf 我也会检查一下
    【解决方案2】:

    您可能可以尝试类似这样的方法 claim.Add(new Claim("customClaim", "claimValue"));

    所以 Claim 类应该有一个重载的构造函数,它接受一个字符串值作为声明类型

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 2018-04-26
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      相关资源
      最近更新 更多