0

I'm trying do deny a specific user to login in the administrative area of the system, after it gets a FormsAuthenticationTicket with expiration of 30 days from now. I'm doing all manually and I'm using asp.net webforms.

My login code is as follows:

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);
    }            
}

And the LoginDataAccess.Authenticate method is this:

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);
    }
}

My check login method search into the database for the user. It's clear for me that I need to do this every time that a user starts a session. How to do this?

Guilherme
  • 5,143
  • 5
  • 39
  • 60

1 Answers1

1

If you want to inject custom authentication logic into your application, in the Global.asax create a method called Application_AuthenticateRequest. Code there gets executed right after the internal authentication mechanisms.

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");
        }
    }
}

See this post for detailed information on how authentication occurs:

AuthenticateRequest event

Community
  • 1
  • 1
DVK
  • 2,726
  • 1
  • 17
  • 20