繁体   English   中英

ASP.net MVC 自定义声明

[英]ASP.net MVC Custom Claims

当用户登录系统时,我正在调用用户访问权限。 在我的用户访问中包括 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;
            }
        }

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

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();
}

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

你可以试试这样的东西 claim.Add(new Claim("customClaim", "claimValue"));

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM