VerifyUserTokenAsync returns false 当用户未持久化时

VerifyUserTokenAsync returns false when the user is not persisted

考虑到 PhoneNumber 作为我的自定义用户的 Username,我只需要 phone 号码经过验证的用户才能注册。所以我创建了一个临时用户并为 him/her 生成了验证令牌并将令牌发送回提供的 phone 号码,如下所示:

public Task Handle(SendSignupSmsRequest request)
{
   var user = new CustomUser { UserName = request.PhoneNumber, PhoneNumber = request.PhoneNumber };
   var token = await _userManager.GenerateUserTokenAsync(user, TokenOptions.DefaultPhoneProvider, "sign-up");

   // send token to provided phone number
}

在注册请求处理程序中,我尝试重新创建相同的临时用户并验证令牌如下:

public Task Handle(SignupRequest request)
{
   var user = new CustomUser { UserName = request.PhoneNumber, PhoneNumber = request.PhoneNumber };
   var tokenVerified = await _userManager.VerifyUserTokenAsync(user, TokenOptions.DefaultPhoneProvider, "sign-up", request.Token);

   if (!tokenVerified)
      // do something;
   else
      // do something else
}

我看到 tokenVerified 总是 False!我尝试了以下方法来找出我的代码有什么问题:
用同一个临时用户验证token ====> 验证成功

var user = new CustomUser { UserName = request.PhoneNumber, PhoneNumber = request.PhoneNumber };
var token = await _userManager.GenerateUserTokenAsync(user, TokenOptions.DefaultPhoneProvider, "sign-up");

var tokenVerified = await _userManager.VerifyUserTokenAsync(user, TokenOptions.DefaultPhoneProvider, "sign-up", request.Token);

使用创建的新临时用户验证令牌,就像临时用户一样 ====> 验证不成功

var user = new CustomUser { UserName = request.PhoneNumber, PhoneNumber = request.PhoneNumber };
var token = await _userManager.GenerateUserTokenAsync(user, TokenOptions.DefaultPhoneProvider, "sign-up");
    
user = new CustomUser { UserName = request.PhoneNumber, PhoneNumber = request.PhoneNumber };
var tokenVerified = await _userManager.VerifyUserTokenAsync(user, TokenOptions.DefaultPhoneProvider, "sign-up", request.Token);

这一切都归结为 SecurityStamp

首先,为在发送注册短信请求处理程序中创建的用户分配一个临时安全标记。然后在注册请求处理程序中为重新创建的用户设置相同的安全标记。这样做,令牌将被成功验证。