Search code examples
c#.net-corejwtclaims

How to get a value from claims JWT C#


How can I get a BasketId from claims in UserContextService? userId work, but basket isn't standard type. So I need help to get it. That's my try:

accountservice:

var claims = new List<Claim>()
{
    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
    new Claim(ClaimTypes.Name, $"{user.FirstName} {user.LastName}"),
    new Claim(ClaimTypes.Role, $"{user.Role.Name}"),
    new Claim("DateOfBirth", user.DateOfBirth.Value.ToString("yyyy-MM-dd")),
    new Claim("Basket", user.BasketId.ToString()),
    new Claim("Address", user.AddressId.ToString()),
};

UserContextService:

public class UserContextService : IUserContextService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public UserContextService(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public ClaimsPrincipal User => _httpContextAccessor.HttpContext?.User;
    public int? GetUserId => User is null ? null :
        (int?)int.Parse(User.FindFirst(x => x.Type == ClaimTypes.NameIdentifier).Value);
    public int? GetBasketId => User is null ? null :
        (int?)int.Parse(User.FindFirst(x => x.Type == "Basket").Value);
}

Solution

  • Try this

    public int? GetBasketId(ClaimsPrincipal user)
    {
    int? bucketId = null;
    var identity = User.Identity as ClaimsIdentity;
    var basketIdObj = identity == null ? null : identity.Claims.FirstOrDefault(x => x.Type == "Bucket");
    if (basketIdObj != null) bucketId = Convert.ToInt32(basketIdObj.Value);
    return bucketId;
    }