Context User does not return username Asp Net Core 3.1 C#

Asked

Viewed 27 times

2

I’m trying to get the username logged in by the User context inside a controller. I’m using Identity to manage login and JWT to authenticate requests in my controller. I can get the values: "User.Identity.Isauthenticated" and "User.Identity.Authenticationtype" normally, but "User.Identity.Name" always comes as null. The name is already stored in the bank normally.

I tried to take the Name another way, using Httpcontextaccessor:

Within the Configureservices() method of the Startup file:

// Obs: using Microsoft.AspNetCore.Http;
// Declarando o HttpContextAccessor na Startup para ser utilizado em
// outras partes do programa
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

Inside of my Controller:

    [Authorize]
    [Route("[controller]")]
    public class TesteController : ControllerBase
        {
            // Injetando o HttpContextAccessor no construtor:
            private readonly IHttpContextAccessor _httpAccessor;
    
            public TesteController(IHttpContextAccessor httpAccessor)
            {
                _httpAccessor = httpAccessor;
            }

            [HttpGet]
            public ActionResult Index()
            {
                // Sempre retorna null, assim como o User.Identity.Name
                return Ok(_httpAccessor.HttpContext.User.Identity.Name);
            }
        }
  • 1

    look it happened to me in a project here, basically opitei for taking the email, that always has (in my case) :(

  • 1

    What I am doing is along with JWT, I added more information (Claimsidentity). Then you can use this information as you wish. Note that this information is attached to the token and is public and static You cannot store sensitive or dynamic data.

  • What can you get from User.Identity and what have you persisted in the bank? tried the property DisplayName?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.