[HttpPost]
public IActionResult VerifyOTP(string otp)
{
if(IsValidOTP(otp))
{
return RedirectToAction("Index", "Home");
}
else
{
ViewBag.ErrorMessage = "Invalid OTP code. Please try again.";
return View("OTPVerification");
}
}
private bool IsValidOTP(string otpCode)
{
// code to check if the OTP code is valid
}
private bool IsValidOTP(string otpCode)
{
var sessionOTP = HttpContext.Session.GetString("OTPCode");
if (string.IsNullOrEmpty(sessionOTP))
{
return false;
}
var parts = sessionOTP.Split('|');
var timestamp = long.Parse(parts[1]);
var code = parts[0];
// check if OTP code is valid and timestamp is within 30 seconds
if (timestamp > DateTimeOffset.UtcNow.ToUnixTimeSeconds() - 30 && otpCode == code)
{
return true;
}
return false;
}
private string GenerateOTP()
{
// generate random 6-digit code
var otp = new Random().Next(1000000, 9999999).ToString("D6");
// append timestamp to OTP to verify it's within 30 seconds
var sessionCode = $"{otp}|{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}";
HttpContext.Session.SetString("OTPCode", sessionCode);
return otp;
}
[RequireHttps]
[HttpGet]
public IActionResult OTPVerification()
{
var otp = GenerateOTP();
return View(new OTPViewModel { OtpCode = otp });
}
[HttpPost]
public IActionResult VerifyOTP(string otp)
{
if(IsValidOTP(otp))
{
// remove OTP code from session to prevent reuse
HttpContext.Session.Remove("OTPCode");
return RedirectToAction("Index", "Home");
}
else
{
ViewBag.ErrorMessage = "Invalid OTP code. Please try again.";
return View("OTPVerification");
}
}
这种解决方法将确保仅在