1

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.

Bilal Mehrban
  • 577
  • 3
  • 13
ConanCode
  • 252
  • 2
  • 4
  • 15
  • Which claims are you seeing in the token? Which one contains the value that you wish to retrrieve? – mason Jan 28 '21 at 13:46
  • @mason I would like to use the email. But it's not written in stone, I'm flexible. My last try was with Nameidentifier and the key in the payload was "nameid". – ConanCode Jan 28 '21 at 15:22
  • Do you have `.AddOpenIdConnect()` in your startup.cs? I was able to map it so that HttpContext.User.Identity.Name gets its value from the "name" claim via `options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "name" };` so perhaps if you set NameClaimType to "nameid" it would work. – mason Jan 28 '21 at 15:27
  • I do not fully understand where you want to call that AddOpenIdConnect() method. IServiceCollection and IApplicationBuilder don't have this method? – ConanCode Jan 28 '21 at 15:36
  • AddOpenIdConnect would be an extension method that you call on AuthenticationBuilder, like `services.AddAuthentiction().AddOpenIdConnect()` for example. But perhaps you're using a different library. You should share your relevant configuration from Startup.cs. The AddOpenIdConnect method comes from `Microsoft.AspNetCore.Authentication.OpenIdConnect` library. – mason Jan 28 '21 at 15:53

1 Answers1

0

You can try this:

         var username = _httpContextAccessor.HttpContext.User.Identity.Name;

Follow the official document for more information.

Akif
  • 4,586
  • 6
  • 13
  • 36
  • This requires that the name claim gets successfully mapped. Given that they're saying there's no claims on the User property, I doubt it got successfully mapped. – mason Jan 28 '21 at 13:50
  • Yes @mason is right. I don't see any claims. I've tried this also. – ConanCode Jan 28 '21 at 15:24