我正在尝试拒绝某个特定用户登录系统的管理区域,此后它获得的FormsAuthenticationTicket将在30天后到期。我正在手动完成所有操作,并且我正在使用asp.net webforms。
我的登录代码如下:
protected void btnLogin_Click(object sender, EventArgs e)
{
User u = LoginDataAccess.CheckLogin(txtEmail.Text, txtPassword.Text);
if (u.Id == 0)
{
lbInfo.Text = "Invalid credentials.";
lbInfo.CssClass = "label-warning";
}
else
{
LoginDataAccess.Authenticate(u, Response.Cookies, cbRememberMe.Checked);
}
}
LoginDataAccess.Authenticate方法是这样的:
public static void Authenticate(User user, HttpCookieCollection cookies, bool remember)
{
GenericIdentity gi = new GenericIdentity(user.Name);
string role = UserRoles.GetRole(user.Roles);
GenericPrincipal gp = new GenericPrincipal(gi, new string[] { role });
FormsAuthentication.RedirectFromLoginPage(user.Name, true);
if (remember)
{
cookies.Clear();
DateTime expiryDate = DateTime.Now.AddDays(30);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, user.Nome, DateTime.Now, expiryDate, true, String.Empty);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
authenticationCookie.Expires = ticket.Expiration;
cookies.Add(authenticationCookie);
}
}
我的检查登录方法搜索用户的数据库。对我来说很明显,每次用户启动会话时我都需要这样做。怎么做?
答案 0 :(得分:1)
如果要将自定义身份验证逻辑注入应用程序,请在Global.asax中创建一个名为Application_AuthenticateRequest的方法。代码在内部认证机制之后立即执行。
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
var context = HttpContext.Current;
if (context.User != null && context.User.Identity != null && context.User.Identity.IsAuthenticated)
{
if (SomeClass.UserIsExpired(context.User))
{
// Clear cookies or whatever you need to do
// Throw a 401 to deny access
throw new HttpException(401, "User account is expired");
}
}
}
有关身份验证方式的详细信息,请参阅此帖子: