Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

JWT claims in Blazor web app do not get taken over

$
0
0

The purpose of this app is to have a template app I can use for multiple applications in the future, so I don't have redo all the authentication (and some database stuff) to focusing on building web apps in the future more easily and faster. I have a problem that I can't really wrap my head around. It has to do with creating JWT for authentication.

I have two claims (also others, but that's not in the scope of the problem) for the web app I'm building: (User)Name and Role.

The name is being used to identify the user with @context.User.Identity?.Name to display his user name.

The role is to distinguish between users and page administrators. Mainly to use with making a page only usable by admins with the @attribute [Authorize(Roles=nameof(UserRoles.admin))] but also an <Authorize View (Roles=...)> tag.

There are two (main) NuGet packages which can assist in creating the JWTs:

  • Microsoft.IdentityModels.Tokens
  • System.IdentityModel.Tokens.Jwt (this is marked as legacy and should be replaced with the above)

I generate my token with the following code:

creating jwt with Microsoft.IdentityModels.Tokens

The problem with this creation method is that the Name claim does not get "saved". context.User.Identity?.Name is null when I create the JWT, even though I clearly add the name in claims.

Screenshot of the context in the debugger using Microsoft.IdentityModels.Tokens

I have a NameClaimType, but the Name property is null and the name claim didn't get added to my claims. As a result the name is not displayed in my Blazor app (should be in top right corner --> Hello <username>!.

Role based access is possible, name is not shown

I played around a lot and couldn't find a satisfying answer on the internet, so I tried creating the JWT with the legacy tool. This is the code that produces the JWT:

creating jwt with System.IdentityModel.Tokens.Jwt

The following context is created:

Screenshot of the context in debugger using System.IdentityModel.Tokens.Jwt

Now I do get the users name, but the Role claim is missing, even though a RoleClaimType is set. I can't see anything in the authorized view anymore:

Code of authorized view

Name is shown, but Role based access is impossible.

I would like the solution to be able to see the name, and have role based access in my app. I honestly have no clue on how to wrap my head around this, as it doesn't really make sense to me.

Thank you in advance!


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>