FYI: I already had a look at this answer and the answers didn't work => How do I get current user in .NET Core Web API (from JWT Token)
Scenario:
I have an ASP.net 5 Web API which I migrated a few days ago from ASP.net core 3.1.
I've setup JWT authentication in my backend. The token issuing is working correctly. When I decode the token, every claim is there.
My frontend calls an endpoint in my backend. Inside this endpoint in the controller, I need to know who the user is. So I want to receive the claims from the JWT token.
As mentioned above, I already tried almost all of the solutions above, but none of them were working.
So my problem is, that the user inside the controller has no claims.
My current progress:
In the startup.cs class I've registered the HttpContextAccessor.
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
...
}
The controller:
namespace ...
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly IConfiguration _config;
private readonly IUserService _userService;
private readonly IHttpContextAccessor _httpContextAccessor;
public UserController(IConfiguration config, IUserService userService, IHttpContextAccessor httpContextAccessor)
{
_config = config;
_userService = userService;
_httpContextAccessor = httpContextAccessor;
}
[HttpGet("currentUser")]
public IActionResult GetCurrentUser()
{
var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
return Ok(userId);
}
After this endpoint is called, I receive the following error: System.NullReferenceException: 'Object reference not set to an instance of an object.' I guess the dependency injection should be okay.
The Claims property inside the User is empty, so I do not really know how to fix this.