简体   繁体   English

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

[英]Get Current User From ASP.NET CORE 2

I create update user in my App and then I test my app in Postman and in Web App but create different result. 我在App中创建了更新用户,然后在Postman和Web App中测试了我的应用,但创建了不同的结果。 When I tried this code in postman it work but web app doesn't work (Code in ASP.NET CORE 2.0, Web App using Angular 5) 当我在邮递员中尝试此代码时,它可以工作,但Web应用程序不起作用(ASP.NET CORE 2.0中的代码,使用Angular 5的Web App)

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

From the WebApp it produce error: "Object reference not set to an instance of an object." 从WebApp产生错误:“对象引用未设置为对象的实例。”

When I debug the app it seems the line caused that 当我调试应用程序时,似乎是由线引起的

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

I check and it produce null. 我检查,它产生空值。

Any idea where the User was set ? 知道在哪里设置用户吗?

My Login 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 });

    }

If an api method contains [Authorize] then an authorization header is sent along with the request. 如果api方法包含[Authorize],则将与请求一起发送授权标头。 If no header is sent then you have no user. 如果未发送头,则您没有用户。

[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
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ASP.NET Core Identity - 获取当前用户 - ASP.NET Core Identity - get current user 如何在ViewComponent Asp.Net Core中获取当前登录用户 - How get current login user in ViewComponent Asp.Net Core asp.net core中如何获取当前用户 - How to get current user in asp.net core 如何在 ASP.NET Core 中删除当前用户的声明? - How to remove claims from current user in ASP.NET Core? 如何在不通过 controller asp.net 核心的情况下获取任何 Class 中的当前用户 ID 和用户声明 - How to get current user Id and user claim in any Class without pass by controller asp.net core 如何使用 ASP.NET Core RC2 MVC6 和 IIS7 获取当前的 Windows 用户 - How to get the current Windows user with ASP.NET Core RC2 MVC6 and IIS7 如何在ASP.NET Core中获取Active Directory当前用户显示名称? - How to get Active Directory current user Display Name in ASP.NET Core? ASP.NET Core 3.0 中获取当前经过身份验证的用户用户名的方法是什么? - What is the way in ASP.NET Core 3.0 to get current authenticated User username? 如何在 ASP.Net Core 服务层的基础 class 中获取当前用户? - How to get current User in base class of service layer in ASP.Net Core? ASP.NET 核心 MVC 身份 - 如何查看当前登录的用户? - ASP.NET Core MVC Identity - how to get current logged in user in view?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM