Prabir Choudhury
Prabir Choudhury

Reputation: 335

Unable to add to Claims of jWT corresponding to property of Enum type -

In my project, a model class has a enum type property, Like So,

eCulinaryUser.cs -

public class eCulinaryUser
{
    public int Id { get; set; }
    public CookType CookType { get; set; }
    public string FirstName { get; set; } = string.Empty;
    public string LastName { get; set; } = string.Empty;
    .....
    .....
    public DateTime CreatedAt { get; set; } = DateTime.Now;
}

where

CookType.cs -

public enum CookType
{
    Hobbyist,
    Professional
}

The code block where I am fetching user data and generating the claims for the logged in user is like so,

IConfigurationSection? authSettings .....
.....
.....
var claims = new List<Claim>
{
    new Claim(JwtRegisteredClaimNames.Aud, authSettings.GetSection("validAudience").Value!),
    .....
    .....
    new Claim(JwtRegisteredClaimNames.NameId, user.Id ?? "")
};
if (user.SubscriptionType != null)
{
    claims.Add(new Claim("subscriptiontype", user.SubscriptionType.ToString()));
}
var eCulinaryUser=_dbContext.eCulinaryUsers.Where(eu=>eu.UserId==user.Id)
                    .Select(eu=>new eCulinaryUser
                    {
                        CookType=eu.CookType
                    }).ToList();

if(eCulinaryUser != null)
{
    //this line trying to add to the claims
    claims.Add(new Claim("cooktype", eCulinaryUser.ToString()));
}
.....
.....
SecurityToken token = tokenHandler.CreateToken(descriptor);

return tokenHandler.WriteToken(token);

I inspected jWT token that my service is generating using the debugger at www.jwt.io. For the claim 'cooktype' there is no value. Nothing. Blank. Mind you, the eCulinaryUser variable contains the perfect value for the CookType corresp. to the loggedin user. How do I add the value of the fetched cooktype to its corresponding claim key? How do I manipulate the enum?

Can you give me a neat solution for this? Or a workaround maybe?

Upvotes: 0

Views: 19

Answers (0)

Related Questions