views:

49

answers:

1

Currently, I have some code as follows:

protected override void OnLoad(EventArgs e)
{
    if(IsAuthorized(param1, param2, ...))
    {
        //snip
    }
    else
    {
        Response.Write("Not authorized");
    }
}

protected void MyButton1_Click(object sender, EventArgs e)
{
    //snip
}

protected void MyButton2_Click(object sender, EventArgs e)
{
    //snip
}

When the user is logged in, they can go to the page and OnLoad runs. Now, if they let their session expire with the page still open, then try to click MyButton1, they will be greeted with "Not authorized", but the code inside MyButton1_Click will still run. Could anyone point me in the direction of how I would correctly handle this type of situation? I assumed I could just throw new SecurityException(), then display whatever error I wanted in the catch(SecurityException), however the event handler still runs. Thanks in advance.

+1  A: 

You can throw an authentication check around your code such as this code from MSDN:

private void Page_Load(object sender, EventArgs e)
{
    // Check whether the current request has been
    // authenticated. If it has not, redirect the 
    // user to the Login.aspx page.
    if (!Request.IsAuthenticated)
    {
        Response.Redirect("Login.aspx", true);
    }
}

I believe this is cleaner than the Response.Write() since the user clearly sees that they're no longer authenticated.

Gavin Miller
That is actually what I'm doing, I just wrote it as is to simplify the question. I was trying to get around putting authentication blocks around each event handler. I was hoping this could be achieved by throwing some sort of exception in the OnLoad() when the user is no longer authenticated and not continue onto the event handler in this scenario.
lush
Missed the important part of the Response.Redirect... Change it to Response.Redirect("Login.aspx", true); It's an overload that causes the page to stop executing
Gavin Miller
Got it. Thanks.
lush