如何在.Net Core 2.0中检索声明值

问题描述 投票:0回答:2

正如标题中所说,我已经向注册用户分配了声明,我现在尝试在用户登录到 sql server 中的 UserClaims 表中的应用程序时检索声明值,我发现这有点困难这是我第一次使用索赔。

正在寻找实现这一目标的指导,提前谢谢您。

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));
    }
asp.net-core-2.0 claims-based-identity claims asp.net-core-identity
2个回答
35
投票

设置

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

获取

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

3
投票

非常简单

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

示例

User.Identity.GetId();
© www.soinside.com 2019 - 2024. All rights reserved.