Implement form Authentication through ASP.NET

in utopian-io •  7 years ago  (edited)

asp.net.jpg
Image Source

What Will I Learn?

We will discuss form authentication. This authentication mode consists in redirecting any user to a login page as long as it has not authenticated. Authentication can be carried out either from a file of XML configuration either from an external system (DBMS or Active Directory).
We will describe the implementation of the form-based authentication mechanism. The list of authorized users will first be described in an XML configuration file and then integrated into a table of users of a database SQL2000 data.

  • Forms authentication under ASP .Net
  • Setting up the Web.Config file
  • The authentication form
  • Disconnection of the user

Requirements

  • ASP.net coding
  • SQL2000 table creation
  • Web.Config file configuration

Difficulty

  • Intermediate

Tutorial Contents


1 . Forms authentication under ASP .Net

Here's how ASP forms .Net authentication works:
1 . A client submits an http request to access a secure ASP page.
2 . IIS forwards the request to ASP .Net for authentication. Anonymous access must be checked for IIS authentication.
3 . ASP.NET checks if the client has an authentication cookie. If the user is not authenticated then he is redirected to a login page.
4 . The user enters his identity and password.
5 . Authentication information is checked (configuration file, DBMS.). If the user is not authenticated then an access denied message is displayed.
6 . Authentication information has been validated, an authentication cookie is generated.
7 . If the user is authorized by ASP.NET then he accesses the requested page.

Let's move on to practice and implement this authentication system by taking the following steps:

  • Setting the Web.Config file: Setting the mode authentication.Definition of the redirection page.Definition from the list of authenticated users with their word encryption password.
  • Creating a web form to collect information customer identification.
  • Verification of the client authentication information from an XML configuration file.
2 .Setting up the Web.Config file

To set form authentication, here are the changes to make in the Web.Config file.

<authentication mode = "Forms">
<forms loginUrl = "login.aspx" timeout = "20">
<credentials passwordFormat = "MD5">
<user name = "christian" password = "7FF13585437685
0E9711BD75CE942E07 "/>
</ Credentials>
</ Forms>
</ Authentication>
<Authorization>
<deny users = "?" />
</ Authorization> 

First the authentication mode was switched to "Forms". The LoginUrl tag indicates the page to which the user will be automatically redirected until he is authenticated. The timeout tag indicates the duration in minutes of the authentication cookie. The user information is defined in the credentials tag. Then you have to define for each user a name and a password within a user tag, only these accounts will be authorized to to authenticate on our application.

Finally, we complete the security of our web application, prohibiting its access to all unauthenticated users.

Password encryption:
But will you tell me that means the MD5 format and how to encrypt the password of the users?
Encryption of the password can be achieved through the HashPasswordForStoringInConfigFile function of the FormsAuthentication class. It makes it possible to generate an encrypted password according to a hashing algorithm SHA1 or MD5.
These two values ​​can be used as the format of the password as well as a value "Clear" to use if you do not do not want to encrypt it.

3. The authentication form

The authentication screen is relatively simple with an input box for the user name, an input box for the password and a login button. Let's not worry about the other buttons for now.
Now let's look at the code executed when the user clicks on the Login button.
using System.Web.Security;

private void BtConnection_Click (object sender,
System.EventArgs e)
{
 if (FormsAuthentication.Authenticate (txtUti
lisateur.Text, txtMotDePasse.Text))
 {
FormsAuthentication.RedirectFromLoginPage (txtUt
ilisateur.Text, false);
 }
 else
 {
 lbMessage.Text = "Incorrect login!";
 }
}

The FormsAuthentication class is part of the System.Web.Security namespace. It must be included in our page.
The Authenticate method checks the username and password from the elements in the tag Credentials of the Web.Config file. If the user is enabled then an authentication cookie is generated and the user is redirected to the page originally requested; these operations are performed by the method RedirectFromLoginPage. This method also takes a second parameter that indicates whether the cookie should persist during a session change.
Note that in case the RedirectFromLoginPage method can not identify a return page then the page default.aspx is displayed.

4. User authentication via a database

We have just implemented forms authentication by validating the identity of the user from information contained in an XML configuration file. This solution works but can quickly become tedious for an administrator to enter a large number of user accounts.
Let's try to improve our solution by now validating the information from a "users" table of a database.
SQL2000 data. To do this, we must:
Edit the Web.Config file by deleting the credentials tag.

  • Create a SQL2000 table that will contain the information authentication.
  • Develop our own authentication function "Authenticate" responsible for checking the information entered by the user with those contained in the database.
  • Change the code associated with the Login button to use our new method.

For security reasons, we will encrypt the password in MD5 format.
Description of the "Authenticate" function:

private bool Authentifier(string strUtilisateur
, string strMotDePasse)
{
 bool bOk=false ;
 // Cryptage du mot de passe
 strMotDePasse =
FormsAuthentication.HashPasswordForStoringInCon
figFile(strMotDePasse,"MD5");
 // Création d'une connexion SGBD
 SqlConnection oConnexion
= new SqlConnection("user
id=sa;password=;initial catalog=pubs;data
source=pttravail");
 // Définition de la requête à exécuter
 SqlCommand oCommand
= new SqlCommand("SELECT * FROM Utilisateurs
WHERE nom='" + strUtilisateur+ "'",oConnexion);
 try
 {
 // Ouverture de la connexion et
exécution de la requête
 oConnexion.Open();
 SqlDataReader drUtilisateur =
oCommand.ExecuteReader();
 // Parcours de la liste des
utilisateurs
 while (drUtilisateur.Read())
 {
 if (drUtilisateur["motdepasse"].ToString()
== strMotDePasse)
 {
 bOk = true ; break ;
 }
 }
 }
 catch
 {
 bOk = false ;
 }
 oConnexion.Close();
 return bOk;

We first encrypt the password entered by the user, then we select the list of user's passwords who tries to authenticate, finally we go through it by comparing each password with that encrypted previously.
As soon as a password has been found we return true to the calling function.
All that remains is to modify the code associated with the Login button and to invoke our Authentifier method.

private void BtConnection_Click (object sender,
System.EventArgs e)
{
 if (Authenticate (txtUser.Text, txtMot
DePasse.Text))
 {
FormsAuthentication.RedirectFromLoginPage (txtUt
ilisateur.Text, false);
 }
 else
 {
 lbMessage.Text = "Error
authentication, the user or the word
pass do not exist! ";
}
}
5. Disconnection of the user

Most sites, which offer a way to authenticate with forms, also provide a disconnection.
The SignOut () method of the FormsAuthentication class performs this disconnect operation by destroying the authentication cookie, which will require the user to authenticate again to access one of the pages of your application.
Here is the code executed when the user clicks the Logout button:

private void BtDeconnect_Click (object sender,
System.EventArgs e)
{
 FormsAuthentication.SignOut ();
Response.Redirect ( "Login.aspx");
}

We destroy the authentication cookie and redirect the user to the login page.

We were able to see how easy it is to implement form authentication with ASP .Net. It is thus possible in a few lines of code and at a lower cost to secure any Intranet or Internet Web application.



Posted on Utopian.io - Rewarding Open Source Contributors

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Thank you for the contribution. It has been approved.

Thanks For The Suggestion and Thanks For The Approval. But now repository option is disabled to make any kind of change.
I'm glad to make this contribution.

Hey @holudghuri I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x