How to retrieve Claims Value in .Net Core 2.0

cedPound picture cedPound · Mar 12, 2018 · Viewed 18.6k times · Source

As it says in the title I have already assigned claims to the registered user, I am now trying to retrieve the claim value when the user logs into the application within the UserClaims table in sql server which I find a bit difficult to do as this is my first time using claims.

Looking for directions on our to achieve this, thank you in advance.

     public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.UserName, Email = model.Email, UserRoleId = model.RoleId };
            var result = await _userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                _logger.LogInformation("User created a new account with password.");

                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);

                await _signInManager.SignInAsync(user, isPersistent: false);
                _logger.LogInformation("User created a new account with password.");

                await addUserClaims(model.CusomterId, model.UserName);
                return RedirectToLocal(returnUrl);
            }
            AddErrors(result);
        }

        List<UserRole> roles = _userRoleRepo.GetAll();
        model.CreateRoleList(roles);

        List<Customer> customers = await _customerRepository.GetAll();
        model.SetupCustomerOptionList(customers);

        // If we got this far, something failed, redisplay form
        return View(model);
    }

        private async Task addUserClaims(string CustomerID ,string username)
    {



        // Customer customer = _customerRepository.GetById(customerid);
        List<Customer> customers = await _customerRepository.GetAll();
        Customer customer = _customerRepository.GetById(CustomerID);




        var user = await _userManager.FindByNameAsync(username);
;
        await _userManager.AddClaimAsync(user, new Claim(ClaimTypes.Name, CustomerID));
    }

Answer

Irfan Ashraf picture Irfan Ashraf · May 21, 2018

Set

var claims = new List<Claim>
{
  new Claim("Currency", "PKR")
};

Get

@User.Claims.FirstOrDefault(c => c.Type == "Currency").Value