再会,
由于IdentityOption 中没有SecurityStampValidationInterval,我如何验证安全戳以防止Asp.Net Core 2 中的单个用户多次登录。
提前致谢。
我已经使用 Microsoft.Extensions.Caching.Memory.IMemoryCache 来实现相同的。(将用户名存储在缓存中)
登录时(我们可以在验证密码之前执行此操作) 步骤 1:使用内存缓存作为控制器的 DI。
private IMemoryCache SiteCache = null;
public LoginHelper(IMemoryCache Cache)
{
SiteCache = Cache;
}
Run Code Online (Sandbox Code Playgroud)
第2步:
在您的登录验证中,如果用户已存在于缓存中,请运行此检查。
private bool VerifyDuplicateLogin(string UserName, bool InsertKey)
{
String sKey = UserName.ToLower();
String sUser = Convert.ToString(SiteCache.Get<string>(sKey));
if (string.IsNullOrEmpty(sUser))
{
if (InsertKey)
{
string cookieTimeout = appSettingsData.LoginCookieTimeout;
int timeout = (string.IsNullOrEmpty(cookieTimeout)) ? 3 : int.Parse(cookieTimeout);
int sessionTimeOut = 5; // HttpContext.Current.Session.Timeout;
sUser = string.Format("{0}^^^{1}", sKey, DateTime.Now.AddMinutes(sessionTimeOut).ToString("yyyy-MM-dd HH:mm:ss"));
// No Cache item, so session is either expired or user is new sign-on, Set the cache item and Session hit-test for this user
TimeSpan SlidingTimeOut = new TimeSpan(0, 0, timeout, 0, 0); //(HttpContext.Current.Session.Timeout / 2)
MemoryCacheEntryOptions cacheOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = SlidingTimeOut
};
SiteCache.Set(sKey, sUser, cacheOptions); //OnCachedItemRemoved
session.LoggedInUser = sKey;
}
//Let them in - redirect to main page, etc.
return false;
}
else
{
// cache item exists, means... "User already in"
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
第三步:注销时使用以下方法从缓存中删除用户名
public void RemoveLogin(string userName)
{
//Clear the cache
if ((!string.IsNullOrEmpty(userName)) && SiteCache != null)
{
String sUser = Convert.ToString(SiteCache.Get<string>(userName));
if (!string.IsNullOrEmpty(sUser))
{
SiteCache.Remove(userName.ToLower());
session.LoggedInUser = "";
}
}
}
Run Code Online (Sandbox Code Playgroud)
由于我使用了内存缓存,每当服务器和应用程序重置时,用户缓存也会重置,我们可以获得快速响应。
我们可以使用数据库来实现相同的功能,将登录的用户临时存储在类似的逻辑中,但我觉得这种方法虽然更快,更令人窒息。
这种方法的一个缺点是,如果用户关闭浏览器并希望立即重新登录,他将收到一个用户已经登录的响应(意味着他被锁定,直到缓存密钥过期。(我们在设置时必须小心)过期超时)
谢谢
| 归档时间: |
|
| 查看次数: |
1871 次 |
| 最近记录: |