1

What is the best way to set up authentication against a custom database of users, in ASP.NET? My current setup is not great, and I am sure that there is a better way to do authentication, but all I can find are some articles that are seven or eight years old. My current setup is as follows:

  • Application uses the Windows username (via Windows Authentication), to work out whether a user is in a database of allowed users. This is done via a call to an Authenticate method in Page_Load.
  • If the user isn't in the allowed users, then the page redirects to a login screen.

The flaw with this method is that it calls:

Response.Redirect("~/login.aspx", false)

Which executes the entire body of the Page_load method. Is there a better way of doing authentication? Would something like custom Page classes, or HTTPModules do the job?

2 Answers 2

1

You could do your check earlier in the request, like in OnInit, or you could do something a little more robust, like implement your own membership provider: MSDN article / Video tutorial

Sign up to request clarification or add additional context in comments.

3 Comments

This could be shoved into a base class that all pages could inherit from, couldn't it?
Yeah, using a base page class is a great idea for this type of functionality.
Excellent, that's exactly what I will do then. Seems so obvious now that I think about it.
0

Okay, so this is basically how I done it. I wrote this class that inherits from System.Web.UI.Page. I override the OnInit event and this is where the authentication happens (looks up the Windows username against the database of users). If the user doesn't get authenticated, isTerminating gets set to true, and the OnLoad event only runs if isTerminating is false. I tried leaving a Response.Redirect with the second parameter set to false on its own, but this still ran all the subsequent page events. (even with a call to HttpApplication.CompleteRequest())

public class BasePageClass : Page
{
    private bool isTerminating = false;

    protected override void OnInit(EventArgs e)
    {
        isTerminating = !AuthenticationManager.Authenticate();

        base.OnInit(e);
    }

    protected override void OnLoad(EventArgs e)
    {
        if (!isTerminating)
        {
            base.OnLoad(e);
        }
    }
}

I have no idea whether not running the OnLoad event is the best thing to do, but it "seems" to work fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.