Home > Net >  ASP.net MVC Custom Claims
ASP.net MVC Custom Claims

Time:09-17

I'm calling the user access when the user login to the system. In my user access includes UserName,UserRole,UserId,ReqAccess,ViewAccess etc.

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?

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

CodePudding user response:

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.

CodePudding user response:

you can probably try something like this claims.Add(new Claim("customClaim", "claimValue"));

So the Claim class should have an overloaded constructor which takes a string value as the claim type

  • Related