This article will inform you more about forms Authentication using ASP .NET and Visual Basic .net (VB .NET). Before I continue I must stress that the web.config is xml and must be used with extreme sensitivity in mind. All tags must be closed etc. or else you will end up with endless problems trying to figure out what you've done wrong. I should also stress that no code should be copied from this article as invisible characters such as spaces may be carried with it and your code wont work. The best thing to do is just to type it from scratch.

When using forms Authentication you must first declare it in the web.config. If you are using vb .net as your language then the web.config will allready have been auto-generated for you. The default is:

<authentication mode="Windows" />

Authentication modes that can be used are: "Windows", "Passport" and of course "Forms". Since this post is about Forms authentication we will be using "Forms" and perhaps I will go more indepth about the others in a later post. Now that we have chosen forms authentication, we have to remove the '/' at the end as this is closing the tag and we have yet to enter more information in so we do this:

<authentication mode="Forms">
More to go here
</authentication>

The Forms authentication has the following properties:

Name: The name of the HTTP cookie where authentication information is stored

loginUrl: The name says it all :) what is the url for the login page?

protection: This is used to set the method from which to protect your cookie data. The following valid values can be supplied:

-All: Specifies to use both data validation and encryption to protect the cookie. Triple DES is used for encryption, if it is available and if the key is long enough (48 bytes). The All value is the default (and suggested) value.

-None: Used for sites that are only using cookies for personalization and have weaker requirements for security. Both encryption and validation can be disabled. This is the most efficient performance wise, but must be used with caution.

-Encryption: Specifies that the cookie is encrypted using Triple DES or DES, but data validation is not done on the cookie. It's important to note that this type of cookie is subject to chosen plaintext attacks.

-Validation: Specifies to avoid encrypting the contents of the cookie, but validate that the cookie data has not been altered in transit. To create the cookie, the validation key is concatenated in a buffer with the cookie data and a MAC is computed/appended to the outgoing cookie.

path: Path to be used for the issued cookie. Default is "/"

timeout: How long until the session times out in minutes. 30=30 minutes which is the default value. The timeout is a sliding value, therefore it means the cookie will expire 30 minutes from the last time a request was received.

Note: Once a user logs in, they are redirected to default.aspx, I think there may be a property here to change this...

So we now have:

<configuration>	
<system.web>
<authentication mode="Forms">
<forms name="cookie" loginUrl="Login.aspx" protection="All" path="/" timeout="30">
</forms>
</authentication>
</system.web>
</configuration>

Next we create the user credentials. Credentials has the following properties:

passwordFormat: Indicates what format the password is stored in. Valid Values are listed below.

-Clear: Just reads the value in it's pure format, e.g. if my password was dag then I would put it as dag in the web config.

-SHA1: Reads the password value as a SHA1 encrypted Password. You must first encrypt your password before you can place it into the web config though. I am currently writing an article on how to make a SHA1 web application encryption program.

-MD5: Reads the password value as an MD5 encrypted password. You must first encrypt your password before you can place it into the web.config.

Both SHA1 and MD5 are hashing algorithms that are used to make the web application more secure.

So now we have:

<configuration>	
<system.web>
<authentication mode="Forms">
<forms name="cookie" loginUrl="Login.aspx" protection="All" path="/" timeout="30">
<credentials passwordFormat="Clear">
</credentials>
</forms>
</authentication>
</system.web>
</configuration>

Next comes the user information. User has the following properties:

Name: The user name
Password: The user password
Roles: There is also a property called 'Roles' which allows you to define what roles a user is e.g. Administrator, user, editor, author, etc. However, we won't be using this here.

We now have:

<configuration>	
<system.web>
<authentication mode="Forms">
<forms name="cookie" loginUrl="Login.aspx" protection="All" path="/" timeout="30">
<credentials passwordFormat="Clear">
<user name="Slade" password="Test" />
<user name="Scod" password="Test" />
</credentials>
</forms>
</authentication>
</system.web>
</configuration>

Next we have to decide what users are allowed to use this application. So we use the authorization tag:

<authorization>
<allow users="*" />

You can use Allow:

users: A comma-separated list of user names that are granted access to the resource. A question mark (?) allows anonymous users; an asterisk (*) allows all users.

roles: A comma-separated list of roles that are granted access to the resource.

verbs: A comma-separated list of HTTP transmission methods that are granted access to the resource. Verbs registered to ASP.NET are GET, HEAD, POST, and DEBUG.

You can also use deny:

users: A comma-separated list of user names that are denied access to the resource. A question mark (?) indicates that anonymous users are denied access; an asterisk (*) indicates that all users are denied access.

roles: A comma-separated list of roles that are denied access to the resource.

verbs: A comma-separated list of HTTP transmission methods that are denied access to the resource. Verbs registered to ASP.NET are GET, HEAD, POST, and DEBUG.

Ok Now we break away from the web.config :) Next comes some vb and html :D.

The Login Page:

On the login page we need:
Two labels
Two Text Boxes
One Checkbox
One Command Button

Properties that need to be changed:

label1
Text: UserName

label2
Text: Password

TextBox1
(ID): txtUser

TextBox2
(ID): txtPass
Textmode: Password

Checkbox
(ID): chkPersist

The labels are merely to label the text boxes so users can identify each text box with it's label. E.g. if the label Username is placed to the left of txtUser than the user knows that the text box is for the username input. txtUser is for the username. txtPass is for the password. If chkPersist is ticked, then the user will stay constantly signed in, even after leaving the site.

The code for the html will look like this:

<table height="100%" cellSpacing="0" cellPadding="0" width="100%" bgColor="#999999" border="0">
<tr>
<td><asp:label id="lblUser" runat="server" Font-Size="X-Small" ForeColor="Black" BackColor="Transparent">Username:</asp:label></td>
<td align="right"><asp:textbox id="txtUser" runat="server" Font-Size="X-Small" BorderStyle="Inset" MaxLength="20"></asp:textbox></td>
</tr>
 
 
<tr>
<td><asp:label id="lblPass" runat="server" Font-Size="X-Small" ForeColor="Black" BackColor="Transparent">Password:</asp:label></td>
<td align="right"><asp:textbox id="txtPass" runat="server" Font-Size="X-Small" BorderStyle="Inset" MaxLength="20" TextMode="Password"></asp:textbox></td>
</tr>
 
 
<tr>
<td colSpan="2"><asp:checkbox id="chkPersist" runat="server" Font-Size="X-Small" ForeColor="Black" BackColor="Transparent"
Text="Remember Me?"></asp:checkbox></td>
</tr>
 
</table>

NOW the code for the login button behind. NOTE: I am using vb.

This line MUST be included in the top of the page.

Imports System.Web.security

The login button (redirects the "login-attempter" to the page "Denied.aspx" on their third attempt):

Private Sub cmdLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLogin.Click
		If FormsAuthentication.Authenticate(txtUser.Text, txtPass.Text) Then
			FormsAuthentication.RedirectFromLoginPage(txtUser.Text, chkPersist.Checked)
		Else
			lblStatus.Text = "Not Authenticated"
			If CInt(ViewState("Tries")) > 1 Then
				Response.Redirect("Denied.aspx")
			Else
				' Otherwise, increment number of tries.
				ViewState("Tries") = CInt(ViewState("Tries")) + 1
			End If
		End If
	End Sub
End Class

Now that the user is logged in... how do they log out? It is a good idea to have a log-out button as well. The code for a logout button is:

cmdLogout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLogout.Click
FormsAuthentication.SignOut()
Response.Redirect("Default.aspx")

I hope that this article has been informative.;)

Slade.

Is there any other way to authenticate users other than adding all the username to web.config?

I support a website for my community and was planning to switch to .net from classic asp. Currently I authenticate users by retrieving user info from database. the website is hosted thru one of the hosting companies.

How will I go about implementing what you have suggested?

You can authenticate users from a database, INI file, text file, remote database, XML file, CSV file, or just about anything else you can come up with. I personally use a database and that is also what I advocate so I would stick with the concepts you use in your classic ASP app (but not the code, .NET is better!!).

This is just one way to go about it :)

OP - Nice post

This is a very well thought out approach and greatly appreciated, but I believe "lpatel" was not asking whether one ~can~ authenticate users from a database, but rather ~how~ to implement within the context of your excellent example. I think the real question is: What VB code might one use in place of the single "FormsAuthentication.Authenticate" statement in your example, in which user id's and passwords were pulled from (say) a simple text file?

The forms which are often used in terms of authority given to someone else on behalf of you are termed as authorization forms. By the use of authorization forms, we can simply give authority to anyone and can be carried out our tasks via them comfortably. In that condition, the respective person by whom we are carried out our tasks is considered free to sign a deal on our behalf. Hence their signature will be treated as out signature.

This article has been dead for over six months. Start a new discussion instead.