Individual Account Athentication on ASP.NET Core 6 ReactJS template returns Null for User in Controller, but works in ReactJS menu

Viewed 47

So, I have a bit of an annoying issue. It seems that when using the ASP.NET Core 6 ReactJS template, I can log in, log out, register accounts etc, and the ReactJS menu shows the active username, but am having issues reaching the active user in a controller.

Also, Authorize does not work for controllers (no scope or specific claim defined) as it always returns Unauthorized.

I have tried injecting the HTTPContextAccessor, SigninManager, Usermanager in a controller like so;

    [Authorize]
    [ApiController]
    [Route("/api/[controller]")]
    public class MyController : ControllerBase
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly ILogger<MyController> _logger;
        private readonly ApplicationDbContext _applicationDbContext;

        public MyController(
            ILogger<MyController> logger,
            ApplicationDbContext applicationDbContext,
            UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager,
            IHttpContextAccessor httpContextAccessor)
        {
            _applicationDbContext = applicationDbContext;
            _logger = logger;
            _userManager = userManager;
            _signInManager = signInManager;
            _httpContextAccessor = httpContextAccessor;
        }

And using it in the controller method like so, where ALL testX variations return null on the user identity, rendering me unable to retrieve the active username and/or Id. Test4 generates an error as it cannot return .Value of null.

        [HttpGet]
        public IEnumerable<Something> Get()
        {
            var test1 = User.Identity!.Name!;
            var test2 = HttpContext.Request;
            var test3 = await _userManager.GetUserAsync(User);
            var test4 = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            var test5 = _applicationDbContext.Users.Find(test4);
            var test6 = user.UserName;

            return Something;
        }

into the controller and loading it in Program.cs like so

builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Any takers? Note, this is just using the base template without adding complexity, functionality etc...

Thanks in advance for your help!

0 Answers
Related