首页 > 解决方案 > 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://docs.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);

        }

标签: asp.net-coreidentityserver4asp.net-core-identity

解决方案


用户 ID 可以在声明中找到: http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier:

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

该 id 值等于由 ASP.NET Identity 创建的表中的Id列。AspNetUsers


推荐阅读