C# 在FormsAuthentication对用户进行身份验证后,撤消身份验证并重定向到登录页面
在表单验证机制已经从浏览器接收到验证cookie并对其进行验证之后,如果用户不再存在(或其他条件),我需要撤销验证cookie。即,以下是使用场景:C# 在FormsAuthentication对用户进行身份验证后,撤消身份验证并重定向到登录页面,c#,asp.net,forms-authentication,C#,Asp.net,Forms Authentication,在表单验证机制已经从浏览器接收到验证cookie并对其进行验证之后,如果用户不再存在(或其他条件),我需要撤销验证cookie。即,以下是使用场景: 用户已通过身份验证,并被授予非过期身份验证cookie 几天后,用户再次尝试访问我的web应用,由于cookie有效,表单身份验证机制将授予访问权限 现在,我想执行第二次检查(无论我想要什么条件),并决定是让用户继续,还是撤销身份验证 问题是——有没有一种官方的自动化方法?到目前为止,我已经提出了一些可能性,但我不知道哪一个更好。我可以在globa
我不认为有一种自动化的方法来实现这一点。 我认为最好的方法是在auth cookie中添加一个日期,这将是您最后一次检查用户是否存在。 因此,当用户登录时,您将:
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
name, // Username associated with ticket
DateTime.Now, // Date/time issued
DateTime.Now.AddMonths(1), // Date/time to expire
true, // "true" for a persistent user cookie
DateTime.Now.ToUniversalTime(), // last time the users was checked
FormsAuthentication.FormsCookiePath);// Path cookie valid for
// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
cookie.HttpOnly = true;
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
//cookie.Secure = FormsAuthentication.RequireSSL;
Response.Cookies.Add(cookie);
然后,每次对用户进行身份验证时,您都可以检查传递给身份验证票证的附加日期,并在10分钟或更短的时间间隔内根据数据库再次检查该用户是否存在。
代码可能如下所示:
public void FormsAuthentication_OnAuthenticate(object sender,
FormsAuthenticationEventArgs args)
{
if (FormsAuthentication.CookiesSupported)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(
Request.Cookies[FormsAuthentication.FormsCookieName].Value);
DateTime lastCheckedTime = DateTime.TryParse(ticket.UserData);
TimeSpan elapsed = DateTime.Now - lastCheckedTime;
if (elapsed.TotalMinutes > 10)//Get 10 from the config
{
//Check if user exists in the database.
if (CheckIfUserIsValid())
{
//Reset the last checked time
// and set the authentication cookie again
}
else
{
FormsAuthentication.SignOut();
FormsAuthentication.RedirectToLoginPage();
return;
}
}
}
catch (Exception e)
{
// Decrypt method failed.
}
}
}
}
您甚至可以缓存过去10分钟内删除的用户,并根据该集合进行检查
希望这会有所帮助。如果您出于除过期会话以外的其他原因拒绝cookie,那么我认为您应该将用户重定向到一个页面,该页面描述了他们需要做什么才能获得访问权限。如果再次登录就足够了,那么登录页面就足够了。然而,听起来好像在某些情况下,简单地再次登录是不可能的。在这种情况下,最好将用户重定向到一个合适的错误页面,该页面描述了用户无法访问该站点的原因,并解释了如何再次获得访问权限(如果可能)。是的,RedirectToLoginPage就是我要找的东西。。。我没有找到它,因为这是1.1项目。我需要迁移。谢谢。为什么要麻烦把发行的日期存储在两个地方呢?你已经在写日期时间了。现在在发布日期。建议:只需测试issuedate是否大于10分钟前。