简体   繁体   English

ASP.net MVC 自定义声明

[英]ASP.net MVC Custom Claims

I'm calling the user access when the user login to the system.当用户登录系统时,我正在调用用户访问权限。 In my user access includes UserName,UserRole,UserId,ReqAccess,ViewAccess etc.在我的用户访问中包括 UserName、UserRole、UserId、ReqAccess、ViewAccess 等。

In my claims, I can add User Id and User Names but I wanna add other access to the separate claims, but when I type claims.Add(new Claim(ClaimTypes. the list only shows the listed Items. How do I add my own claims and add them?在我的声明中,我可以添加用户 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;
            }
        }

I did this and it is working fine:我这样做了,它工作正常:

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

Getting user details and saving it in claims.获取用户详细信息并将其保存在声明中。

you can probably try something like this claims.Add(new Claim("customClaim", "claimValue"));你可以试试这样的东西 claim.Add(new Claim("customClaim", "claimValue"));

So the Claim class should have an overloaded constructor which takes a string value as the claim type所以 Claim 类应该有一个重载的构造函数,它接受一个字符串值作为声明类型

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

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