我在使用谷歌身份验证器的两因素身份验证中使用以下代码。此验证的问题在于,谷歌身份验证器代码在我的本地机器上正确验证,但在服务器上却没有。服务器时间设置为:(UTC-05:00)东部时间(美国和加拿大)我的系统时间设置为:(UTC-06:00)中部时间(美国和加拿大)
在服务器上 - 当我尝试多次点击验证按钮时,它有时会正确验证有时不会。我不确定它为什么这样做。
任何人都可以帮助我提出想法/建议来解决这个问题
public static class TimeBasedOneTimePassword
{
public static readonly DateTime UNIX_EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static MemoryCache _cache;
static TimeBasedOneTimePassword()
{
_cache = new MemoryCache("TimeBasedOneTimePassword");
}
public static string GetPassword(string secret)
{
return GetPassword(secret, GetCurrentCounter());
}
public static string GetPassword(string secret, DateTime epoch, int timeStep)
{
long counter = GetCurrentCounter(DateTime.UtcNow, epoch, timeStep);
return GetPassword(secret, counter);
}
public static string GetPassword(string secret, DateTime now, DateTime epoch, int timeStep, int digits)
{
long counter = GetCurrentCounter(now, epoch, timeStep);
return GetPassword(secret, counter, digits);
}
private static string GetPassword(string secret, long counter, int digits = 6)
{
return HashedOneTimePassword.GeneratePassword(secret, counter, digits);
}
private static long GetCurrentCounter()
{
return GetCurrentCounter(DateTime.UtcNow, UNIX_EPOCH, 30);
}
public static long GetCurrentRemaining()
{
return (long)(DateTime.UtcNow - UNIX_EPOCH).TotalSeconds % 30;
}
private static long GetCurrentCounter(DateTime now, DateTime epoch, int timeStep)
{
return (long)(now - epoch).TotalSeconds / timeStep;
}
public static bool IsValid(string secret, string password, int checkAdjacentIntervals = 1)
{
if (password == GetPassword(secret))
return true;
for (int i = 1; i <= checkAdjacentIntervals; i++)
{
if (password == GetPassword(secret, GetCurrentCounter() + i))
return true;
if (password == GetPassword(secret, GetCurrentCounter() - i))
return true;
}
return false;
}
}