Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve Claims Value in .Net Core 2.0

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));
    }
like image 241
cedPound Avatar asked Mar 12 '18 10:03

cedPound


People also ask

Where are user claims stored?

By default, a user's claims are stored in the authentication cookie. If the authentication cookie is too large, it can cause the app to fail because: The browser detects that the cookie header is too long.

What are claims .NET core?

A claim is a name value pair that represents what the subject is, not what the subject can do. For example, you may have a driver's license, issued by a local driving license authority. Your driver's license has your date of birth on it.


2 Answers

Set

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

Get

@User.Claims.FirstOrDefault(c => c.Type == "Currency").Value
like image 128
Irfan Ashraf Avatar answered Sep 19 '22 12:09

Irfan Ashraf


Very easy

public static class IdentityExtension
{
    public static string GetId(this IIdentity identity)
    {
        ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;

        Claim claim = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

        return claim.Value;
    }
}

Example

User.Identity.GetId();
like image 45
Fatih Erol Avatar answered Sep 21 '22 12:09

Fatih Erol