.net 如何从blazor页面获取Jwt令牌声明?

ohtdti5x  于 2022-12-05  发布在  .NET
关注(0)|答案(1)|浏览(131)

I've built and application which uses JWT authentication. When creating a profile page for a customer I want to get relative information of the customer such as: First Name, Last Name, credits etc.
I found that by using @context.User.FindFirst("FirstName") inside a .razor page I can get the values from the token BUT on the web page it shows in this format FirstName:Bob , when I just want to get the name Bob .

How can I get the values from a token in a more elegant/eficient way?

Something similar like we would use for @context.User.Identity.Name

Generate Claims Method:

private List<Claim> GenerateClaims(Shared.Models.User user)
{
    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, config["Jwt:Subject"]),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
        new Claim(ClaimTypes.Name, user.userName),
        new Claim(ClaimTypes.Role, user.type),
        new Claim("FirstName", user.FirstName),
        new Claim("LastName", user.LastName),
        new Claim("Credits", user.Credits.ToString())
    };
    return claims.ToList();
}

As you see from the method above, I want to get all the new Claim("Example", user.Example)

0mkxixxg

0mkxixxg1#

您可以编写一个扩展方法:

public static class ClaimsPrincipalExtension
{
    public static string GetClaimValue(this ClaimsPrincipal claimsPrincipal, string type)
        => claimsPrincipal.FindFirst(type)?.Value ?? string.Empty;
}

用法

@context.User.GetClaimValue("FirstName")

相关问题