c# - 从 ASP.NET CORE 2 获取当前用户

标签 c# asp.net-core oauth .net-core asp.net-core-2.0

我在我的应用程序中创建更新用户,然后 我在 Postman 和 Web 应用程序中测试我的应用程序,但创建了不同的结果。 当我在 postman 中尝试此代码时,它可以工作,但网络应用程序无法工作 (ASP.NET CORE 2.0 中的代码,使用 Angular 5 的 Web 应用程序)

[HttpPut("{id}")]
    public async Task<IActionResult> UpdateUser(int id, [FromBody] UserForUpdateDto userDto) {
        if(!ModelState.IsValid)
            return BadRequest(ModelState);

        var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
        var userFromRepo = await _orgRepo.GetUser(id);
        if(userFromRepo == null) 
            return NotFound($"User not found with id: {id}");
        if (currentUserId != userFromRepo.Id)
            return Unauthorized();

        _mapper.Map<UserForUpdateDto, User>(userDto, userFromRepo);

        if (await _orgRepo.SaveAll())
            return NoContent();

        throw new Exception($"Updating user {id} failed on save");
    }

从 WebApp 产生错误: “未将对象引用设置为对象的实例。”

当我调试应用程序时,似乎是该行导致了

var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

我检查了一下,结果是 null。

知道用户设置在哪里吗?

我的登录 Controller :

[HttpPost("login")]
    public async Task<IActionResult> Login([FromBody]UserForLoginDto userForLoginDto)
    {
        var userFromRepo = await _repo.Login(userForLoginDto.Username.ToLower(), userForLoginDto.Password);

        if (userFromRepo == null)
            return Unauthorized();

        // generate token
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(_config.GetSection("AppSettings:Token").Value);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.Username),
                new Claim(ClaimTypes.Role, "RegisteredUsers")
            }),
            Expires = DateTime.Now.AddDays(3),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                SecurityAlgorithms.HmacSha512Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        var tokenString = tokenHandler.WriteToken(token);

        var user = _mapper.Map<UserForDetailDto>(userFromRepo);
        return Ok(new { tokenString, user });

    }

最佳答案

如果 api 方法包含 [Authorize],则授权 header 将随请求一起发送。如果没有发送 header ,则您没有用户。

[HttpPut("{id}")]
[Authorize(AuthenticationSchemes = "Bearer")]
public async Task<IActionResult> UpdateUser(int id, [FromBody] UserForUpdateDto userDto) 
   {    
       var sub = User.GetSubjectId();   // Subject Id is the user id
    }

关于c# - 从 ASP.NET CORE 2 获取当前用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49973251/

相关文章:

c# - OrderBy().ThenBy().ThenBy() 未在实体列表上给出预期结果

c# - asp.net core blazor webassessivecrypto - 如何使用自定义 key

c# - 仅对某些 Controller 使用 OAuth Bearer token

sharepoint - 用于 SharePoint 365 REST 的 Oauth2

azure - 如何使用 Azure OAuth 或 Azure API 网关保护 Open xpage REST API

c# - 数据绑定(bind) Int 属性到 WPF 中的枚举

c# - 为什么我的错误没有被捕获?

c# - 使用 msbuild 执行文件系统发布配置文件

c# - 动态更改 Asp.Net Core 中的连接字符串

c# - 如果使用命名空间版本路由,如何在 ASP.Net Core API 中设置 RESTful 属性路由