ASP.NET Core Identity invalid token on confirmation email

前端 未结 7 1511
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 12:11

This is a very similar question to this aspnet identity invalid token on confirmation email but the solutions are not valid because I am using the new ASP.NET Core 1.0 that

7条回答
  •  既然无缘
    2021-01-01 12:54

    This answer https://stackoverflow.com/a/31297879/2948212 pointed me in the right direction. But as I said it was for a different version and now it is slightly different solution.

    The answer is still the same: encode the token in base 64 url, and then decode it in base 64 url. That way both Angular and ASP.NET Core will retrieve the very same code.

    I needed to install another dependency to Microsoft.AspNetCore.WebUtilities;

    Now the code would be something like this:

    public async Task SendPasswordResetEmailAsync(string email)
    {
        //_userManager is an instance of UserManager
        var userEntity = await _userManager.FindByNameAsync(email);
        var tokenGenerated = await _userManager.GeneratePasswordResetTokenAsync(userEntity);
        byte[] tokenGeneratedBytes = Encoding.UTF8.GetBytes(tokenGenerated);
        var codeEncoded = WebEncoders.Base64UrlEncode(tokenGeneratedBytes);
        var link = Url.Action("MyAction", "MyController", new { email = email, code = codeEncoded }, protocol: HttpContext.Request.Scheme);
         //this is my service that sends an email to the user containing the generated password reset link
         await _emailService.SendPasswordResetEmailAsync(userEntity , link);
    }
    

    and when receiving back the code during the PUT request

    [HttpPut]
    [AllowAnonymous]
    [Route("api/password/{email}")]
    public async Task SendPasswordEmailResetRequestAsync(string email, [FromBody] PasswordReset passwordReset)
    {
        //some irrelevant validatoins here
        await _myIdentityWrapperService.ResetPasswordAsync(email, passwordReset.Password, passwordReset.Code);
        return Ok();
    }
    
    //in MyIdentityWrapperService
    public async Task ResetPasswordAsync(string email, string password, string code)
    {
        var userEntity = await _userManager.FindByNameAsync(email);
        var codeDecodedBytes = WebEncoders.Base64UrlDecode(code);
        var codeDecoded = Encoding.UTF8.GetString(codeDecodedBytes);
        await _userManager.ResetPasswordAsync(userEntity, codeDecoded, password);
    }
    

提交回复
热议问题