Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get User Info From Access Token WebApi Asp.net Core

I'm using the new ASP.NET Core Identity API Authorization found in dotnet-core3-preview, the docs are found here https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-3.0

I'm succesfully running the typical login process, and the token are set and sent in the Bearer token. However rightnow I have an api end point that should return some user details from the database, so I'm trying to extract the user id from the token to query the database.

Yet, I'm not able to find the id in any of the claims, as per my screenshot below, how can I accomplish this?

enter image description here

        [HttpGet]
        [Authorize]
        public async Task<IActionResult> GetUserByToken(){


            var ls = User.Claims.AsQueryable();
            return Ok(ls);

        }
like image 911
Yehia A.Salam Avatar asked Aug 02 '19 18:08

Yehia A.Salam


People also ask

Does access token have user info?

Sample access tokenThe token does not contain any information about the user except for the user ID (located in the sub claim). In many cases, you may find it useful to retrieve additional user information. You can do this by calling the userinfo API endpoint with the Access Token.

How do I call API access token?

The other way to make an API call with an access token is to add it to the request header. If using curl (a command line program that can be used for running API requests) you would specify the access token like this. Notice that the access_token is not in the URL at all. See the example on the API documentation site.


2 Answers

The user id could be find in claim : http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier :

var userID = User.Claims.Where(a => a.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value;

That id value equals Id column in AspNetUsers table which created by ASP.NET Identity .

like image 113
Nan Yu Avatar answered Oct 28 '22 20:10

Nan Yu


I prefer using this instead which is shorter:

var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value
like image 30
Maven Avatar answered Oct 28 '22 19:10

Maven