Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get current user in .NET Core Web API (from JWT Token)

After a lot of struggling (and a lot of tuturials, guides, etc) I managed to setup a small .NET Core REST Web API with an Auth Controller issuing JWT tokens when stored username and password are valid.

The token stores the user id as sub claim.

I also managed to setup the Web API to validate those tokens when a method uses the Authorize annotation.

 app.UseJwtBearerAuthentication(...)

Now my question: How do I read the user id (stored in the subject claim) in my controllers (in a Web API)?

It is basically this question (How do I get current user in ASP .NET Core) but I need an answer for a web api. And I do not have a UserManager. So I need to read the subject claim from somewhere.

like image 999
monty Avatar asked Sep 08 '17 08:09

monty


1 Answers

The accepted answer did not work for me. I'm not sure if that's caused by me using .NET Core 2.0 or by something else, but it looks like the framework maps the Subject Claim to a NameIdentifier claim. So, the following worked for me:

string userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value; 

Note that this assumes the Subject sub Claim is set in the JWT and its value is the user's id.

By default, the JWT authentication handler in .NET will map the sub claim of a JWT access token to the System.Security.Claims.ClaimTypes.NameIdentifier claim type. [Source]

There is also a discussion thread on GitHub where they conclude this behavior is confusing.

like image 154
Honza Kalfus Avatar answered Sep 25 '22 19:09

Honza Kalfus