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+
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 …
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
Sure, here you go: http://bradkingsley.com/multiple-forms-auth-security-settings-in-asp-net/
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:
Correct… just replace the user1 data and then remove the entire user2 line – that will give you the single user access with the u/p of your choice.