Search code examples
c#asp.net-coreasp.net-identitychange-password

Getting Current User in Controller


Hope somebody can help me with this. I am trying to create a Change Password Post Request in the Account controller, but my user is always returning null. I'm new to .NET, could someone help up me figure out the best way to retrive the current user Id? Here is the code I have thus far.

[HttpPost("changePassword")]
    public async Task<ActionResult<ChangePasswordDTO>> ChangePassword([FromBody] ChangePasswordDTO changePassword) {

        var currentUserId = User.Claims.ToList()
        .FirstOrDefault(x => x.Type == "").Value;

         var user = await _userManager.FindByIdAsync(currentUserId);

        var result = await _userManager.ChangePasswordAsync(user, changePassword.Password, changePassword.NewPassword);

        if (result.Succeeded) {
            return Ok("Password changed succesfully");
        } else return Unauthorized("An error occurred while attempting to change password");


    }

When I change the "currentUserId" to a hard coded value, everything works fine, of course. Every user has a generated jwt token with his name, id, roles etc. I'm unsure how to proceed, everything I've tried retrieves the user as null. Let me know if you need extra information, I'm pretty new to all of this and appreciate whatever help I can get, thanks!

Solution

JamesS pointed me in the right direction, this code works:

var currentUserId =this.User.FindFirstValue(ClaimTypes.NameIdentifier);


Solution

  • You can get the current user id in your controller using the UserManager such as:

    ASP.NET CORE >= 2.0

    var currentUserId = User.FindFirstValue(ClaimTypes.NameIdentifier);
    

    or Name using:

    var currentUserId = User.FindFirstValue(ClaimTypes.Name);
    

    If you want to get the current user in some other class, you can use the IHttpContextAccessor, passing it into the class's constructor and using the HttpContext to access the User