.Net Core Web API User.Identity.Name 为空 [重复]

Posted

技术标签:

【中文标题】.Net Core Web API User.Identity.Name 为空 [重复]【英文标题】:.Net Core Web API User.Identity.Name is null [duplicate] 【发布时间】:2019-05-13 22:44:50 【问题描述】:

目前有一个问题,我正在尝试检索当前登录用户的名称。我的登录方法调用一个令牌管理器,它构建令牌并添加适当的声明。见下文:

        [HttpPost]
        [Route("Login")]
        public async Task<IActionResult> Login([FromBody] TokenViewModel vm)
        
            try
            
                if (!ModelState.IsValid)
                
                    return BadRequest();
                

                var user = await _userManager.FindByEmailAsync(vm.Email);
                var isLoginRequestValid = await _userManager.CheckPasswordAsync(user, vm.Password);

                if (!isLoginRequestValid)
                
                    return BadRequest("Username or password is incorrect");
                

                return Ok(new TokenViewModel  Token = _tokenManager.BuildJwtToken(vm.Email) );
            
            catch(Exception ex)
            
                return BadRequest(ex);
            
        

和令牌管理器:

        public string BuildJwtToken(string email)
        
            var claims = new[]
            
                new Claim(JwtRegisteredClaimNames.Email, email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            ;

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(_config["Jwt:Issuer"],
                _config["Jwt:Audience"],
                claims,
                expires: DateTime.Now.AddMinutes(double.Parse(_config["Jwt:ExpireTime"])),
                signingCredentials: creds);

            return new JwtSecurityTokenHandler().WriteToken(token);
        

我已经查看了很多关于此问题的帖子,但仍未找到解决方案。身份验证本身工作正常。此外,如果我检查User.Identity 并检查它在请求时的声明,那么我可以看到其中包含名称的声明(在这种情况下是电子邮件test@test.com)。请参阅下面的屏幕截图,其中显示第一个声明是电子邮件声明,并且包含值 test@test.com 但是我无法直接通过 User.Identity 检索 Claims

为什么我的User.Identity.Name 尽管已经成功添加了声明,但在这里仍然为空?

【问题讨论】:

我只看到您正在填写电子邮件地址声明。您应该填写姓名声明:***.com/questions/41830898/… 是的,没有看到那个帖子——这应该作为副本关闭 【参考方案1】:

看来我需要添加声明:

new Claim(ClaimTypes.Name, email)

只使用:

new Claim(JwtRegisteredClaimNames.Email, email)

不与身份声明挂钩

这个添加是在我的BuildJwtToken(string email) 方法中。现在一切都已正确连接。希望这对将来的其他人有所帮助

【讨论】:

以上是关于.Net Core Web API User.Identity.Name 为空 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET Core Web Api 自动帮助页面

如何将 .NET Core 2.2 Web API 迁移到 .NET Core 3.0?

将 .Net Core Identity 和 OIDC 与多个 .Net Core Web API 结合使用

web API .net - .net core 对比学习-依赖注入

.NET Core API 从 Web API 返回响应,不包括 cookie

Entity Framework Core 添加到 .Net Core Web Api - IRelationalTypeMappingSource 问题