User.Identity.Name在Asp.NET Core 2.0 API Controller中为空

Nps*_*Nps 8 bearer-token asp.net-core-webapi asp.net-core-identity asp.net-core-2.0

我是ASP.NET核心的新手.但是,我在ASP.NET Core 2.0中创建WebAPI.我已经配置了基于JWT Bearer Token的身份验证.下面是我的Controller返回令牌.

    [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");
    }


}
Run Code Online (Sandbox Code Playgroud)

但是在调用使用[Authorize]属性修饰的ValuesController API时.我收到 User.Identity.Name为空.我没有收到有关用户的任何信息.我不确定,我的令牌控制器是否正确写入.只要它保护我的ValuesController,我认为,这是正确的.但是,我可能会遗漏一些东西.请帮忙.

注意:我正在使用Visual Studio 2017开发Mac OS社区

Sha*_*uth 22

是的,您需要指定转换为user.identity.name的唯一名称的声明:

new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName)
Run Code Online (Sandbox Code Playgroud)


Mik*_*ill 12

我也一直在使用ASP.Net Core 2这个问题,我真的很惊讶没有人发现这个问题的其他原因.

当我的webapp部署到IIS时," User.Identity.Name"始终返回null.IIS站点已禁用匿名访问,并启用了Windows身份验证.

但.

我没有意识到我的ASP.Net Core 2有一个" launchSettings.json"文件,悄悄地隐藏在Properties文件夹下,并且在那里,还有一些iisSettings,并且在这里" windowsAuthentication奇怪地,"默认设置为false.

在此输入图像描述

将" windowsAuthentication" 更改为true,将" " 更改anonymousAuthentication为false可以解决问题.

执行此操作后," User.Identity.Name"最终包含正确的用户名.

但这个设置到底是什么?为什么会优先于我们在IIS管理器中设置的实际设置?

  • 为什么这被否决了?这与所提出的问题完全相关,并且该答案在其他任何地方都没有提出过。这不是StackOverflow的重点吗? (3认同)

Ger*_*ard 6

使用“DefaultIdentity”(个人用户帐户)也有这个问题(Core 3.1)。User.Identity.Name 为空,User.Identity.IsAuthenticated = true。通过使用 httpContextAccessor,您可以获得带有该 ID 的用户 ID,您可以找到用户和用户名。在您的控制器中添加

using System.Security.Claims;
...
private readonly IHttpContextAccessor _httpContextAccessor;
public MyController(MyContext context, IHttpContextAccessor httpContextAccessor)
{
  _context = context;
  _httpContextAccessor = httpContextAccessor;
}

// Any method username needed
[HttpGet("{id}")]
public async Task<ActionResult<MyInfo>> GetMyInfo(int id)
{
  var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
  var user = _context.AspNetUsers.Find(userId);
  var userName = user.UserName;
  ...
}
Run Code Online (Sandbox Code Playgroud)

在 Startup.cs 中添加以下行:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Run Code Online (Sandbox Code Playgroud)

  • 您不需要在控制器中使用 HttpContextAccessor。您在控制器中已经有了 HttpContext.User 。 (2认同)