如何从声明 JWT C# 中获取值

How to get a value from claims JWT C#

如何从 UserContextService 中的声明中获得 BasketId? userId 有效,但篮子不是标准类型。所以我需要帮助才能得到它。这是我的尝试:

账户服务:

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()),
};

用户上下文服务:

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

试试这个

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