Dailycode.info

Short solution for short problems

Simple security in ASP.Net pages

Just use a Masterpage and add this to the page load of the masterpage:

protected void Page_Load(object sender, EventArgs e)
    {
        //Login check
        if (Session["USERObj"] == null)
        {
            Response.Redirect(@"~\login.aspx");
        }
        else
        {
            lnkLogOff.Text = "Logoff " +  ((User)Session["USERObj"]).Name;
            BuildMenu((User)Session["USERObj"]);
        }
    }
 
private void BuildMenu(CCUser cCUser)
    {
	//Here I can build the navigation menu for this user.
 

On the login page you only have to check the users credentials and write the user object to the session.

Take note of the title, its a simple solution with high flexability. There are millions of way to secure a website, this is one of the most simple ways, especially when you want to implement active directory security:

This function checks username and pasword in AD:

public bool IsAuthenticated(string domain, string username, string pwd)
    {
      string domainAndUsername = domain + @"\" + username;
      string path = "";
      DirectoryEntry entry = new DirectoryEntry(path, domainAndUsername, pwd);
      
      try
      {
          DirectorySearcher search = new DirectorySearcher(entry);
 
          search.Filter = "(SAMAccountName=" + username + ")";
          search.PropertiesToLoad.Add("cn");
          SearchResult result = search.FindOne();
 
          if (null == result)
          {
              return false;
          }
      }
      catch (Exception ex)
      {
          throw ex;
      }
 
      return true;
    }

If username and pasword are validated, then write a User object to the session. The masterpage will perform the login check. I created multiple masterpages, if a page is public, I use a different masterpage, this is not needed, but has a lot of advantages. You can enforce a differtent look for public pages and non-public pages, ...

In the public masterpage I still check for a logged in user but there will be no redirect:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["USERObj"] == null)
        {
            lnkLogOff.Text = "Login";
        }
        else
        {
            lnkLogOff.Text = "Logoff " +  ((CCPL.CC_Objects.User)Session["USERObj "]).Name;
        }
    }

Tip, make sure the login page uses the public masterpage, else it would keep rederecting or you'll have to write dirty code.