I have a .net 6 web api, and when i try to get current user id with configurations below always return null.
//in api controller
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
//in Program.cs
services.Configure<IdentityOptions>(options =>
options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);
services.AddHttpContextAccessor();
Any idea to solve?
Thanks in advance.
CodePudding user response:
Since you configure IdentityOptions options, I assume you are using Asp.net Core Identity for authentication and authorization, right?
I create a Asp.net core application and use Asp.net core Identity, after configuring the Identity Options using your code, I could get the User Id. The result as below:
Why User.FindFirstValue(claimtypes.nameidentifier) always return null?
As regards this question, it could cause by the following reasons:
When you request the API endpoint, the request does not include the JWT token or cookies that have the name identifier claim. You need to add the JWT token or cookie when request the API endpoint.
In this scenario, you can use F12 developer Network tools to check whether the request header has the cookies or the Authorization header, refer to this screenshot (it uses cookies to store the identity information):
The JWT token or the cookies doesn't contain the name identifier claim.
You can set a break point to check User's Claims, whether you can find the name identifier claim or not. In this screenshot, I'm using Asp.net core Identity, and just add the following code:
services.Configure<IdentityOptions>(options => options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier);
If the User's claims don't contain the name identifier claim, perhaps the issue relate the Login part of code, it is better to share the relate code.
Check the
app.UseAuthentication()
andapp.UseAuthorization()
middleware, make sure you have added them properly in the Program.cs or Startup.cs. Code like this:
If above methods still not working, please share the details steps and code, or you can create a minimal, complete sample to reproduce the problem.