Add claims on successful login and retrieve it elsewhere in the application

前端 未结 5 1939
借酒劲吻你
借酒劲吻你 2020-12-14 01:51

Please I need assistance in implementing a custom way of assigning claims to authenticated users. On successful login,

var result = await SignInManager.Pass         


        
相关标签:
5条回答
  • 2020-12-14 01:58

    Then in the view page

    @(((ClaimsIdentity)User.Identity).FindFirstValue("firstName"))
    

    It will show the authenticated user firstName.

    and import the following packages at the top of the page

    @using Microsoft.AspNet.Identity
    @using System.Security.Claims;
    
    0 讨论(0)
  • 2020-12-14 02:03

    are you not able to access User.Identity from the view?

    To retrieve claims for a user, it's been as simple as this for me:

    var identity = (ClaimsIdentity) User.Identity

    And then accessing identity.Claims and using LINQ to retrieve specific claims.

    0 讨论(0)
  • 2020-12-14 02:03

    The Claim property from IdentityUser gives you an ICollection with that collection you can call the following C# method:

        public string GetCustomClaimValue(ICollection<IdentityUserClaim> claimCollection, string customClaimType)
        {
            string claimValue = "";
            foreach (IdentityUserClaim claim in claimCollection)
            {
                if (claim.ClaimType == customClaimType)
                {
                    claimValue = claim.ClaimValue;
                    break;
                }
            }
            return claimValue;
        }
    
    0 讨论(0)
  • 2020-12-14 02:09

    You must add your claims before login not after. Consider this example:

    public async Task<ActionResult> Login(LoginViewModel model,string returnUrl)
    {
        var user = UserManager.Find(model.Email, model.Password);
        if(user!=null)
        {
            var ident = UserManager.CreateIdentity(user, 
                DefaultAuthenticationTypes.ApplicationCookie);
            ident.AddClaims(new[] {
                new Claim("MyClaimName","MyClaimValue"),
                new Claim("YetAnotherClaim","YetAnotherValue"),
            });
            AuthenticationManager.SignIn(
                new AuthenticationProperties() { IsPersistent = true }, 
                ident);
            return RedirectToLocal(returnUrl);
        }
        ModelState.AddModelError("", "Invalid login attempt.");
        return View(model);
    }
    

    Now since we have injected our claims while signing in, we have access to claims wherever we want:

    ((ClaimsIdentity)User.Identity).FindFirst("MyClaimName");
    

    Also you could add your claims in ApplicationUser.GenerateUserIdentityAsync() method. By adding your claims in this method you could use SignInManager.PasswordSignInAsync() method to sign in users without any modification to default Login action method.

    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            userIdentity .AddClaims(new[] {
                new Claim("MyClaimName","MyClaimValue"),
                new Claim("YetAnotherClaim","YetAnotherValue"),
            });
            return userIdentity;
        }
    }
    
    0 讨论(0)
  • 2020-12-14 02:10

    In identity 2, this is done very differently and simply by creating a claims principal factory and then hooking it up in your startup ConfigureServices as below...

    public class CustomClaimsPrincipalFactory : UserClaimsPrincipalFactory<IUser, IApplicationRole>
    {
        public CustomClaimsPrincipalFactory(UserManager<IUser> userManager, RoleManager<IApplicationRole> roleManager,
                                                    IOptions<IdentityOptions> optionsAccessor)
            : base(userManager, roleManager, optionsAccessor)
        {
        }
    
        public async override Task<ClaimsPrincipal> CreateAsync(IUser user)
        {
            var principal = await base.CreateAsync(user);
    
            // Add your claims here
            ((ClaimsIdentity)principal.Identity).AddClaims(new[] { new Claim(ClaimTypes.Email, user.Email),
                                                                    new Claim(ClaimTypes.Gender, user.Gender),
                                                                    new Claim(ClaimTypes.GivenName, user.FirstName),
                                                                    new Claim(ClaimTypes.Surname, user.LastName)
                                                                 });
    
            return principal;
        }
    }
    

    You would then hook it up in ConfigureServices just after calling AddIdentity like this...

             services.AddIdentity<IUser, IApplicationRole>()
             .AddDefaultTokenProviders();
    
    
            // Add Custom Claims processor
            services.AddScoped<IUserClaimsPrincipalFactory<IUser>, CustomClaimsPrincipalFactory>();
    

    Here is a very good article on the subject...

    https://www.codeguru.com/csharp/csharp/cs_misc/security/asp.net-core-and-claim-based-security.html

    0 讨论(0)
提交回复
热议问题