我正在使用 ASP.NET Core 身份在 ASP.NET Core 8 中开发一个 API,该身份将 2FA 与身份验证器应用程序结合使用,供已启用它的用户使用。
问题是这样的。我已经在 Razor 页面中使用 Authenticator 应用程序实现检查了 2FA,当用户使用启用了 2FA 的用户名和密码登录时,它会创建一个名为
Identity.TwoFactorUserId
的 cookie,并具有值 CfDJ8MEoYd_uBmxNsdLp...
。此 cookie 用于识别用户并验证来自 Authenticator 应用程序的 2FA 代码
就我而言,我使用 JWT 作为我的 API。因此,一旦使用身份验证器应用程序启用了 2FA 的用户使用用户名和密码登录,系统将提示他从身份验证器应用程序输入代码。但使用我的 API,在验证 2FA 代码时无法识别用户。我如何在 cookie 中生成类似上面的代码,该代码类似于
Identity.TwoFactorUserId
并且在我的 API 中具有值 CfDJ8MEoYd_uBmxNsdLp...
?或者是否有其他更好的方法,以便一旦用户输入用户名和密码,我就可以向他发送Identity.TwoFactorUserId
之类的代码,以便前端再次传递带有2FA代码的相同代码来识别用户?
您不能使用 cookie,因为 api 是无状态的。相反,您可以尝试使用 API 端点。
对于临时令牌,您可以生成带有过期时间的随机字符串。通过使用此令牌,您可以维护登录和 2FA 验证之间的状态。
示例代码:
2FA启动:
public IActionResult Login(LoginModel model)
{
// ... Login code
if (IsTwoFactorRequired(user))
{
var twoFactorToken = GenerateTwoFactorToken(user.Id);
// Save the token somewhere e.g database, with expiration time
StoreTwoFactorToken(twoFactorToken);
// Return this token to the client
return Ok(new { twoFactorToken });
}
// ... Generate JWT if not using 2FA
}
为用户生成令牌,可以是 GUID,或包含用户 ID 的加密值:
private string GenerateTwoFactorToken(string userId)
{
return Convert.ToBase64String(RandomNumberGenerator.GetBytes(64));
}
2FA验证:
public IActionResult VerifyTwoFactor(string twoFactorToken, string twoFactorCode)
{
if (ValidateTwoFactorToken(twoFactorToken))
{
// Get the user based on the Token
var userId = GetUserIdFromToken(twoFactorToken);
if (ValidateTwoFactorCode(userId, twoFactorCode))
{
// Generate JWT and return to the client
var token = GenerateJwtToken(userId);
return Ok(new { token });
}
}
return Unauthorized();
}
验证格式以及数据库或缓存中令牌(可选)是否存在:
private bool ValidateTwoFactorToken(string twoFactorToken)
{
// Token validation code
}