Securing ASP.Net Pages – Forms Authentication – C# and .Net 4

ASP.Net has a built-in feature named Forms Authentication that allows a developer to easily secure certain areas of a web site. In this post I’m going to build a simple authentication sample using C# and ASP.Net 4.0.

The security settings with ASP.Net are configured from within the web.config file. This is a standard ASCII file, with an XML format, that is located in the root of your web application. Here is a sample web.config file:

<configuration>
    <system.web>
        <authentication mode="Forms">
            <forms name="TestAuthCookie" loginUrl="login.aspx" timeout="30">
                <credentials passwordFormat="Clear">
            <user name="user1" password="pass1"/>
            <user name="user2" password="pass2"/>
        </credentials>
        </forms>
    </authentication>
    <authorization>
        <deny users="?"/>
    </authorization>
    <compilation targetFramework="4.0"/>
    <pages controlRenderingCompatibilityVersion="3.5" ClientIDMode="AutoID"/>
    </system.web>
</configuration>

The very first line is standard for a web.config file and has no bearing on the security.

The next section specifies that you are configuring the security for this web application. First we set the authentication mode to use a cookie in this specific example. You can specify a unique name for your cookie. This section also specifies the page or URL that will contain the authentication code (login.aspx in this case) and how long the authentication cookie should be persisted.

The next two lines specify valid usernames and passwords for this web application. As far as I know there is no limit to the number of user accounts you can place in the web.config, but if there were a large number – or if they change frequently – it might be better to place this information in an external file like a database or an XML file instead (I’ll show this in a future article).

Now that we have specified some valid logon accounts, we need to actually specify that we want to password protect. For this example I have decided to password protect the entire web site starting at the root, so the optional attribute will not be used. We set the authorization to deny all non-authenticated users (deny users=”?”).

That’s all that is needed for the config.web file. If someone tries to access the site and the user has not already authenticated, they will be redirected to the login.aspx page.

This is only half the required process though. We now need to create the login.aspx page to actually allow the user to authenticate to our application.

Here is the complete source of the sample login.aspx page:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" %>
<html>
<head runat="server"><title>Sample</title><head>
<body>
    <form id="form1" runat="server">
        Username: <asp:TextBox ID="txtUsername" runat="server" /><br>
        Password:<asp:TextBox ID="txtPassword" runat="server" /><br>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Login" /><br>
        <asp:Label ID="lblStatus" runat="server" Text="Please login" />
    </form>
</body>
</html>

And here is the complete source of the login.aspx.cs file:

using System;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class Default3 : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FormsAuthentication.Authenticate(txtUsername.Text, txtPassword.Text))
        {
            lblStatus.Text = ("Welcome " + txtUsername.Text);
            FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);
        }
        else
        {
            lblStatus.Text = "Invalid login!";
        }

    }
}

Let’s look at the login.aspx page first. This is fairly straight-forward HTML format. These aren’t actually straight HTML tags, but rather ASP.Net HTML controls that will render HTML page to the client browser (you can tell the difference because the runat=”server” tag at on the control). This is a form that accepts a username and password. When the submit button is clicked, this page executes the code within the login.aspx.cs page located in the subroutine named “Button1_Click”

Inside the Button1_Click method we use the FormsAuthentication object. The first line of the sub actually passes the entered username and password over to the object, which in turn compares this information to the values in the web.config file. If the values match, then the next line changes the label (just so we can see visually that it worked) then writes a cookie to the browser and redirects the user back to the original URL which was requested. The second value listed (“true”) tells the browser to persist the cookie. So if this user authenticates, closes their browser, opens it again, and tries the secure URL – they will still be authenticated.

If the username and password entered did not match, an error message is displayed to the screen and the visitor is allowed to enter a new username and password to try again.

This is a simple example and I don’t cover any of the advanced configurations or options, but with this sample code, you should have a basis to work with if you want to implement security in ASP.Net.

[NOTE: I wrote this post several years ago and had it on the OrcsWeb.com site but the CMS product we were using there mangled the code. I just realized this WAY after the CMS went live (sorry!) so today worked on migrating it off that site and onto this personal blog site of mine.]

[NOTE2: If you see any errors or anything that needs to be corrected/updated, please let me know and I’ll work on getting it fixed. Thanks in advance!]

Happy hosting!
Brad on Google+

Be Sociable, Share!

    17 Comments.

    1. Thanx for your post. I am getting confused for one thing. I have read in some articles, but not in Microsfot one, that we need to enable anonymous access in IIS7 together with form authentication to make it works ! It seems to me awkward !

      • That’s correct. If you don’t enable anonymous access in IIS then it’s going to try to try to authenticate before it even has a chance to run the code. With anonymous access allowed, the code is then able to “step in” and control the access itself.

        • Thanx a lot Brad! what is bothering me in this fact is that my sql connectionstring is using integrated security set to true and i expected form authentication to work as windows authentication. but i keep on getting a sql bad connection error because the anonymous account is used to get connected on sql. i would like to use the authenticated user credentials instead. i am afraid that i do not understand form authentification potential quite enough …

    2. protected void Button1_Click(object sender, EventArgs e)
      {

      string[] users = { “Shashi”, “Admin”, “Ankita” };
      string[] passwords = { “password”, “password”, “password” };
      for (int i = 0; i < users.Length; i++)
      {
      bool validUsername = (string.Compare(TextBox1.Text, users[i], true) == 0);
      bool validPassword = (string.Compare(TextBox2.Text, passwords[i], false) == 0);
      if (validUsername && validPassword)
      {
      Response.Redirect("About.aspx");
      }
      else
      {
      Label4.Visible = true;
      }
      }

      }

    3. Nice article, but how do i protect only one page instead of the full website?
      I have a page to view products that should be accessible by everyone, and a page admin.aspx that shoudl be password protected.
      Greetings, pjdc

    4. This article has helping my login problem.
      I’ve test with framework 4.0 and not in 3.5 version and maybe is that reason that i must add a attribute defaultUrl=”login.aspx” in the forms name=”TestAuthCookie” element.
      also the status text “Welcome user1″ works not fine. My work around is:
      protected void Page_Load(object sender, EventArgs e)
      {
      if (User.Identity.IsAuthenticated)
      {
      lblStatus.Text = “Welcome ” + User.Identity.Name;
      }
      else
      {
      lblStatus.Text = “Home page for guest user.”;
      }
      }

    5. but not not i am used this coding but no any responce in correct coding given it asp.net 3.5 with c#

      protected void Page_Load(object sender, EventArgs e)
      {
      if (!Page.IsPostBack)
      {
      //if(User.Identity.IsAuthenticated && Request.QueryString[“ReturnUrl”]!=null)
      if (Request.IsAuthenticated && !string.IsNullOrEmpty(Request.QueryString[“ReturnUrl”]))
      // This is an unauthorized, authenticated request…
      Response.Redirect(“~/UnauthorizedAccess.aspx”);
      }
      }

      protected void LoginButton_Click(object sender, EventArgs e)
      {
      string username = UserName.Text;
      string password = Password.Text;
      bool isPersistent = false;
      if (System.Web.Security.Membership.ValidateUser(username, password))
      {
      string userData = “ApplicationSpecifi data for this user.”;
      FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
      username, DateTime.Now, DateTime.Now.AddMinutes(30),
      isPersistent, userData,
      FormsAuthentication.FormsCookiePath);
      string encTicket = FormsAuthentication.Encrypt(ticket);
      Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

      if (System.Web.Security.Membership.ValidateUser(UserName.Text, Password.Text))
      {
      if (Request.QueryString[“ReturnUrl”] != null)
      {
      FormsAuthentication.RedirectFromLoginPage(UserName.Text, false);
      }
      else
      {
      FormsAuthentication.SetAuthCookie(UserName.Text, true);
      }
      HttpCookie cookie = new HttpCookie(“mycookie1″);
      cookie.Values.Add(“user”, UserName.Text);
      cookie.Expires = DateTime.Now.AddDays(1);
      Response.Cookies.Add(cookie);
      }

      if (System.Web.Security.Roles.IsUserInRole(UserName.Text, “Administrator”))
      {
      Response.Redirect(“~/Admin/AdminHome.aspx”);
      }
      //else if (System.Web.Security.Roles.IsUserInRole(UserName.Text, “Staff”))
      //{
      // Response.Redirect(“~/Staff/WebForm1.aspx”);
      //}
      //else if (System.Web.Security.Roles.IsUserInRole(UserName.Text, “User”))
      //{
      // Response.Redirect(“~/User/WebForm1.aspx”);
      //}
      //}
      else
      {
      InvalidCredentialsMessage.Text = “your attemp login was faild. pleas enter correct UserName or Password.”;

      }
      }
      }

    6. hi!… the article was of real help.. thanks a lot. but could u please help me with this problem—> see i dont want to create any multiple users for my page, i just have one user and only he will be authorized to access dat particular page.. so shd i just replace the following line “” with the original name and password?? will dat work ??

      • this is the line”username=”user1″ password=”pass1″/” to b replaced by “username=”vasudha” password=”chocolates””… it went missing in the previous post.. :sad:

    7. on local my web site is working fine.but on server when i directly provide url as http://dev.lobaansoftwares.com/ProxyBack/Admin/AddProxies.aspx it’s opening without login instead of login.

    8. nice Info :grin:

    9. very usefull, thanks

    10. Nice info and great tips… :) Thumbs up…