Home > Net >  How to get Jwt token Claim from a blazor page?
How to get Jwt token Claim from a blazor page?

Time:12-03

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)

CodePudding user response:

You could write an extension method:

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

usage

@context.User.GetClaimValue("FirstName")
  • Related