JWT token/claims in controller.

jay8anks

Active member
Joined
May 6, 2022
Messages
31
Programming Experience
5-10
So, just a general question. From what I have read, it looks like you can add variables to a JWT token. From a controller, how would you go about reading the variable?

I guess I am having a hard time understanding the claims vs. token aspects here.

Here is what I am doing. Generate user token. Debug shows everything is correct at this point:

UserToken.EntityId = model.EntityId;
UserToken.EmailId = model.EmailId;
UserToken.UserName = model.UserName;
UserToken.Id = model.Id;
UserToken.GuidId = Id;

On controller:

C#:
var identity = HttpContext.User.Identity as ClaimsIdentity;

            if (identity != null)

            {

                IEnumerable<Claim> claims = identity.Claims;

                // or

                // var test = identity.FindFirst("EntityId").Value;


            }

If I debug this, claims has everything in it except EntityId. Pretty sure EntityId is going into the token. Is claims not storing the same information as the token? Everything else is the same in claims as when I set a breakpoint while generating a user token.

Thanks.
 
Solution
But you can do: new Claim("EntityId", userAccounts.EntityId) assuming that userAccounts.EntityId is a string. Notice line number 5 in the sample you have above.
What is the type of UserToken?
 
What is the type of UserToken?

UserToken.Token = new JwtSecurityTokenHandler().WriteToken(JWToken);

Actually, all the code I'm using is pretty much this: GitHub - CodeMazeBlog/dapper-aspnetcore-webapi: This repo contains the source code for the "Using Dapper with ASP.NET Core Web API" article on Code Maze

The only thing I have changed with the authentication is it had a hard coded user, and I have added a user table and I'm pulling the user/passwordHash from it using Dapper instead of the hard coded user.
 
That's the type for UserToken.Token. I was asking about the type for UserToken itself. Now I have to go dig through the code you linked to. *sigh*
 
Downloaded the repo and searched for UserToken. Not present.
 
Well, unless someone says something different, I think I have to do this:


I kind of thought I was putting things in a token, and I could read those things back out of it when a client sent them back
That's the type for UserToken.Token. I was asking about the type for UserToken itself. Now I have to go dig through the code you linked to. *sigh*


Well, in my head I was just adding things in a JWT token and I could decrypt the token when the client sent it back and get those things back out.

If I am getting it from claims, I think I have to do this:


...and add a custom claim for EntityId.

There are tons of docs and web pages on this stuff, but some of it really isn't clear, at least for me, between claims and the actual token.

Also, just go searching on where claims are actually stored at. It has to be caching the info somewhere, but I have yet to find a simple explanation that just says where exactly this cache is at.

Thanks,
 
Basically what I was trying to lead up to was: "How is your UserToken getting encoded into a JWT token? Do you have (custom?) code to ensure that UserToken.EntityId is added as a claim?"
 
Downloaded the repo and searched for UserToken. Not present.

Sorry. I got the JWT tokens working from this: JWT Token Authentication And Authorizations In .Net Core 6.0 Web API

And then added it to the above repo because it didn't have much in the way of authentication. And even the JWT example just had hard-coded users. I had to add the Repository/Service layer to pull from my db.

The code posted in my first post should be the EntityId being added to the token. At least when I set a breakpoint there, it appears to be:

UserToken.EntityId = model.EntityId;

And yes, I think it is not being added to the claim. And if I am reading MS docs correctly, I have to add a custom field to it.

C#:
 public static IEnumerable<Claim> GetClaims(this UserTokens userAccounts, Guid Id)
        {
            IEnumerable<Claim> claims = new Claim[]
                    {
                new Claim("Id",userAccounts.Id.ToString()),
                new Claim(ClaimTypes.Name, userAccounts.UserName),
                new Claim(ClaimTypes.Email, userAccounts.EmailId),
                new Claim(ClaimTypes.NameIdentifier,Id.ToString()),
                new Claim(ClaimTypes.Expiration,DateTime.UtcNow.AddDays(1).ToString("MMM ddd dd yyyy HH:mm:ss tt") )
                    };
            return claims;
        }

I cannot do something like: new Claim(ClaimTypes.EntityId, userAccounts.EntityId), because ClaimTypes.EntityId is not valid.

I really should just set up a cache and pull the EntityId from the current user name, but I wanted to learn how to do it this way. I mean, the claim does seem to be just a cache made for what I'm trying to do here...right?

Thanks,
 
But you can do: new Claim("EntityId", userAccounts.EntityId) assuming that userAccounts.EntityId is a string. Notice line number 5 in the sample you have above.
 
Solution
But you can do: new Claim("EntityId", userAccounts.EntityId) assuming that userAccounts.EntityId is a string. Notice line number 5 in the sample you have above.

Yes. I found this link about five minutes ago and I came here to post working code, which is exactly as your answer:


I can't believe in the two+ days I spent digging through stackoverflow and blogs, only you and one link provided a simple answer. I mean, Microsoft wanted to create a new service to add a custom claim.

Thanks,
 
Welcome to the darkside of Microsoft's open source revolution. Although MS has opened up most of its stuff to be open source and given the community a chance to delve into and contribute into the guts of its various technologies, frameworks, platforms, etc., the downside has been a much less coordinated effort to disseminate information about it. One has to already be deep in the weeds and interested in a particular area to learn more about it. You can see how that leads to very deep specialization. You need someone who in specialized in that field to write, blog, or create videos about that field in the hopes of documenting stuff and simplifying stuff to make it more accessible for others.
 
Welcome to the darkside of Microsoft's open source revolution. Although MS has opened up most of its stuff to be open source and given the community a chance to delve into and contribute into the guts of its various technologies, frameworks, platforms, etc., the downside has been a much less coordinated effort to disseminate information about it. One has to already be deep in the weeds and interested in a particular area to learn more about it. You can see how that leads to very deep specialization. You need someone who in specialized in that field to write, blog, or create videos about that field in the hopes of documenting stuff and simplifying stuff to make it more accessible for others.

Well, I just spent a few more hours reading through some identity docs, and I still am not quite sure where the claims are actually being stored. Not that it really matters, but I'm not sure why this isn't easier information to find.

I mean, I was putting EntityId into the token correctly. It was going out to my client and being passed back correctly. But I couldn't read the EntityId out of the token, because it wasn't in the "claim". So where is the claim stored at?

Can I query this black box to see how many valid tokens are in my site at any given time?

Most of what I read looks something like this:


Answer: Oh, it is stored in the token, but then gets deleted when the token expires.

OK, deleted from where?

Thanks,
 
Welcome to the darkside of Microsoft's open source revolution. Although MS has opened up most of its stuff to be open source and given the community a chance to delve into and contribute into the guts of its various technologies, frameworks, platforms, etc., the downside has been a much less coordinated effort to disseminate information about it. One has to already be deep in the weeds and interested in a particular area to learn more about it. You can see how that leads to very deep specialization. You need someone who in specialized in that field to write, blog, or create videos about that field in the hopes of documenting stuff and simplifying stuff to make it more accessible for others.

I listened to this book a few weeks back: Amazon.com: Coders at Work: Reflections on the Craft of Programming (Audible Audio Edition): Peter Seibel, Mitchell Dorian, full cast, Upfront Books: Books

One thing I bookmarked was, one guy said that at almost every level of the .net world, the "how to" for that technology was a big fat book. And if you are a full stack guy, at every level, what you are expected to know takes a big fat book to know it well. (Paraphrased).

As a "full stack" guy, I'm not going to lie. One of the reasons I have used Web Forms past their usefulness is because with them, I spend most of my time getting work done. When I get into these other areas, I spend a great deal of time on something trivial, but none the less complicated.

Still, I have been playing with VUE.js and webAPIs and it has kind of grown on me. Fixing to take an online course at UC Santa Barbara for React. Class starts in a few days.

Thanks,
 
Back
Top Bottom