JWT How to add custom claims and decode claims
Asked Answered
F

1

11

I am trying to retrieve some custom claims that I made when I created my token. However, I am not sure on what I should write to retrieve those claims.

This is my token creation function

public String createToken(AuthenticationDTO Input)
{
    //Set issued at date
    DateTime issuedAt = DateTime.UtcNow;
    //set the time when it expires
    DateTime expires = DateTime.UtcNow.AddDays(7);

    //https://mcmap.net/q/440302/-how-to-encrypt-jwt-security-token
    var tokenHandler = new JwtSecurityTokenHandler();

    //create a identity and add claims to the user which we want to log in
    ClaimsIdentity claimsIdentity = new ClaimsIdentity(new[]
    {
        new Claim("UserName", Input.UserName),
        new Claim("Email",Input.Email),
        new Claim("PhoneNumber",Input.PhoneNumber),
        new Claim("FirstName",Input.FirstName),
        new Claim("LastName",Input.LastName),
        new Claim("Id",Input.Id)
    });

    const string sec = HostConfig.SecurityKey;
    var now = DateTime.UtcNow;
    var securityKey = new SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));
    var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);


    //create the jwt
    var token =(JwtSecurityToken)
            tokenHandler.CreateJwtSecurityToken(issuer: HostConfig.Issuer, audience: HostConfig.Audience,
                subject: claimsIdentity, notBefore: issuedAt, expires: expires, signingCredentials: signingCredentials);
    var tokenString = tokenHandler.WriteToken(token);

    return tokenString;
}

Instead of using the standard ones that are provided, I decided to name my own claims. However, I do not know how to retrieve them. This is what I have currently:

public AuthenticationDTO DecodeToken(String Input)
{
    var key = Encoding.ASCII.GetBytes(HostConfig.SecurityKey);
    var handler = new JwtSecurityTokenHandler();
    var tokenSecure = handler.ReadToken(Input) as SecurityToken;
    var validations = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ValidateIssuer = false,
        ValidateAudience = false
    };
    var claims = handler.ValidateToken(Input, validations, out tokenSecure);
    return null;
}

EDIT:

I noticed that my claims are coming in like this

enter image description here

How can I extract them?

EDIT2:

Added AuthentcationDTO

public class AuthenticationDTO
{
    public String Id { get; set; }
    public String UserName { get; set; }
    public String Email { get; set; }
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public String PhoneNumber { get; set; }
}
Feverous answered 23/9, 2018 at 3:47 Comment(3)
use ClaimsPrincipalLeoni
Can you provide AuthenticationDTO class also?Leoni
Added AuthenticationDTOFeverous
L
8

If you want to gets claims i.e, preferred_username you can get that from ClaimsPrincipal.

var user = User as ClaimsPrincipal;
string username = user.Claims.Where(c => c.Type == "preferred_username")
    .Select(x => x.Value).FirstOrDefault();

User will come from Claims. For that write

using System.Security.Claims;

It seems that User is not available in all versions. Another way to get claims will be something similar.

var prinicpal = (ClaimsPrincipal)Thread.CurrentPrincipal;
var email = prinicpal.Claims.Where(c => c.Type == ClaimTypes.Email)
    .Select(c => c.Value).SingleOrDefault();

Assign all the values for AuthenticationDTO.

public AuthenticationDTO DecodeToken(String Input)
{
    var key = Encoding.ASCII.GetBytes(HostConfig.SecurityKey);
    var handler = new JwtSecurityTokenHandler();
    var tokenSecure = handler.ReadToken(Input) as SecurityToken;
    var validations = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ValidateIssuer = false,
        ValidateAudience = false
    };
    var claims = handler.ValidateToken(Input, validations, out tokenSecure);
    var prinicpal = (ClaimsPrincipal)Thread.CurrentPrincipal;
    if (principal is ClaimsPrincipal claims)
    {
         return new ApplicationDTO
             {
                 Id = claims.Claims.FirstOrDefault(x => x.Type == "sub")?.Value ?? "",
                 UserName = claims.Claims.FirstOrDefault(x => x.Type == "preferred_username")?.Value ?? "",
                 Email = claims.Claims.FirstOrDefault(x => x.Type == "email")?.Value ?? ""
             };
    }
    return null;
}
Leoni answered 23/9, 2018 at 4:13 Comment(7)
Sorry where did you get User as ClaimsPrincipal from? I can't get User to appearFeverous
User comes from using System.Security.ClaimsLeoni
I don't have User in System.Security.Claims for some reasonFeverous
If you view the image I added in my question, it looks like I have to loop through this and split them into key value items instead?Feverous
you can get all the values using linq. Are you able to get email using principal?Leoni
Ok, I added prinicpal in my answer. This is how you can get Id, UserName, Email and the rest.Leoni
I used var userId = User.Claims.FirstOrDefault(v => v.Type == "Id").Value; in my controller action. dotnet version : 8 (in preview now)Chairwoman

© 2022 - 2024 — McMap. All rights reserved.