Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User.Identity.Name is empty in Asp.NET Core 2.0 API Controller

I am new to ASP.NET core itself. However, I am creating WebAPIs in ASP.NET Core 2.0. I have configured JWT Bearer Token based authentication. Below is my Controller which return token.

    [AllowAnonymous]
[Route("api/[controller]")]
public class TokenController : Controller
{
    private readonly UserManager<UserEntity> userManager;
    private readonly SignInManager<UserEntity> signInManager;

    public TokenController(UserManager<UserEntity> userManager, SignInManager<UserEntity> signInManager)
    {
        this.userManager = userManager;
        this.signInManager = signInManager;
    }

    // GET: api/values
    [HttpGet]
    public async Task<IActionResult> Get(string username, string password, string grant_type)
    {
        {
            var user = await userManager.FindByEmailAsync(username);

            if (user != null)
            {
                var result =await signInManager.CheckPasswordSignInAsync(user, password, false);
                if (result.Succeeded)
                {

                    var claims = new[]
                    {
                        new Claim( JwtRegisteredClaimNames.Sub, username),
                        new Claim( JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                        new Claim( JwtRegisteredClaimNames.GivenName, "SomeUserID")
                    };

                    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secretesecretesecretesecretesecretesecrete"));
                    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                    var token = new JwtSecurityToken( issuer: "test",
                                                     audience: "test",
                                                     claims: claims,
                                                      expires: DateTime.Now.AddDays(15),
                                                      signingCredentials: creds);

                    return Ok(new { access_token = new JwtSecurityTokenHandler().WriteToken(token), expires_on=DateTime.Now.AddDays(15) });

                }
            }
        }

        return BadRequest("Could not create token");
    }


}

But when calling ValuesController API which is decorated with [Authorize] attributes. I am getting User.Identity.Name is empty. I am not getting any information about user. I am not sure, My token controller is correctly written. As long as it is protecting my ValuesController, I assume, it is correct. However, I might be missing something. Please help.

Note: I am developing using Visual Studio 2017 with Mac Community addition

like image 749
Nps Avatar asked Oct 18 '17 23:10

Nps


2 Answers

Yes, you need to specify the claim for the unique name which is translated into the user.identity.name:

new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
like image 132
Shawn Wildermuth Avatar answered Oct 19 '22 12:10

Shawn Wildermuth


I've also been having this problem with ASP.Net Core 2, and I'm really surprised no one's discovered the other cause of this problem.

When my webapp is deployed to IIS, "User.Identity.Name" always returns null. The IIS site has anonymous access disabled, and windows authentication is enabled.

BUT.

I didn't realise that my ASP.Net Core 2 has a "launchSettings.json" file, quietly hidden under the Properties folder, and in there, there's also some iisSettings, and in here "windowsAuthentication" was, strangely, set as false by default.

enter image description here

Changing "windowsAuthentication" to true, and "anonymousAuthentication" to false solved the problem for me.

After doing this, "User.Identity.Name" did finally contain the correct username.

But what the heck is this setting ? Why would this get priority over the actual settings we've setup in IIS Manager ?!

like image 25
Mike Gledhill Avatar answered Oct 19 '22 13:10

Mike Gledhill