Asp. NET in the form of authentication of the second

Source: Internet
Author: User
Tags anonymous exit config hash sha1 sha1 hash sha1 hash algorithm root directory
asp.net

Brief introduction

The second part of this article is mainly about how to use asp.net to implement our own form authentication method. In the first part, we discuss the basic concepts and principles of table authentication. Before reading the second part of this article, readers need to know some basic concepts of table authentication, or have read the first part.

Establishment of custom form authentication

Pages used: Default.aspx, Login.aspx, web.config, Users.xml, hashpassword.aspx

In this custom form authentication example, we will use an XML document to store the username and password throughout. Some of the preparatory work required to establish the custom form certification:

    • Create a directory with the name customforms under the root directory of the Internet server.
    • Make this folder an application in the Internet Service Manager.
    • Creates a subdirectory with the name unsecure.
    • Create a file with the name hashpassword.aspx and move it to the unsecure directory.



Web.config overview

The Web.config file contains all the configurable setup options for the Web application. I highlighted the code that needs to be studied carefully:

Web.config code

<configuration>
<system.web>
<customerrors mode= "Off"/>

<authentication mode= "Forms" >
<forms name= "Authcookie" path= "/" Loginurl= "Login.aspx" protection= "All" timeout= "ten" >
</forms>
</authentication>

<authorization>
<deny users= "?"/>
</authorization>

</system.web>
This part is highlighted
<location path= "unsecure" >
<system.web>
<authorization>
<allow users= "*"/>
</authorization>
</system.web>
</location>
This part is highlighted
</configuration>



Web.config detailed

This example adds a configuration section named location that allows us to overwrite the settings in the system.web configuration section of the Web.config file. In this case, we want to allow anonymous or not authenticated users to access the unsecure directory, and the common example is that the entire Web application is secure and only the registration page is an exception. By allowing anonymous users access to a directory, we can store files that can be browsed by anyone to that directory. If necessary, we can create multiple location sections.

Users.xml Overview

In this file, we store all the required data for authentication, such as username and password. The password is encrypted using the SHA1 algorithm, and we will explain the SHA1 algorithm later.

Users.xml Code

<?xml version= "1.0"?>
<users>
<jeff>A94A8FE5CCB19BA61C4C0873D391E987982FBBD3</jeff>
<mike>A94A8FE5CCB19BA61C4C0873D391E987982FBBD3</mike>
</users>



Users.xml detailed

In this file, there is a section called users that contains a personal node for each user, and a hashed password between the start and end flags of the node. Obviously, the file can contain more information, such as last name, first name, and phone number.

Login.aspx Overview

This file contains all the logic required to authenticate a user. In this case, we will use an XML file to authenticate the user, and of course we can use the logic of this page to authenticate users using a database.

Login.aspx Code

<% @Page language= "VB"%>
<% @Import namespace= "System.Web.Security"%>
<% @Import namespace= "System.Xml"%>

<script language= "VB" runat= "Server" >
Sub ProcessLogin (Objsender as Object, Objargs as EventArgs)
Dim Strcurrentpath as String = Request.PhysicalPath
Dim Strxmldocpath as String = Left (Strcurrentpath, InStrRev (Strcurrentpath, "\")) & "Users.xml"
Dim struser as String = Txtuser.text
Dim strpassword as String = txtPassword.Text
Dim Strencpassword as String = Gethashedpass (strpassword)
Dim blnisauthenticated as Boolean

Dim objXMLDoc as New XmlDocument ()

Try
Objxmldoc.load (Strxmldocpath)
Catch Objerror as Exception
errormessage.innerhtml = "<b> XML document could not is Loaded.</b>.<br>" & _
Objerror.message & "<br/>" & Objerror.source
Exit Sub
End Try

Dim Usernodes as XmlNodeList

Usernodes = Objxmldoc.getelementsbytagname (struser)

Is there an element with the same user name as the user name entered
If not usernodes are nothing Then
Dim blnuserexists as Boolean = True
Dim Strusercheck as String
Try
Strusercheck = usernodes (0). FirstChild (). Value
Catch Objerror as Exception
errormessage.innerhtml = "<b>invalid username</b> Please re-enter ..."
Blnuserexists = False
End Try
If blnuserexists = True Then
If Strencpassword = usernodes (0). FirstChild (). Value Then
blnisauthenticated = True
Else
errormessage.innerhtml = "<b>invalid password</b> Please re-enter ..."
End If
End If
End If

If blnisauthenticated Then
FormsAuthentication.RedirectFromLoginPage (struser, chkpersistlogin.checked)
End If

End Sub

Function Gethashedpass (ByVal Apassword As String) as String
Return FormsAuthentication.HashPasswordForStoringInConfigFile (Apassword, "SHA1")
End Function
</script>

<title>custom Forms Authentication Login form</title>

<body bgcolor= "#FFFFFF" text= "#000000" >
<form runat= "Server" >
<table width= "border=" 0 "cellspacing=" 0 "cellpadding=" 0 ">
<tr>
&LT;TD width= ">username": </td>
&LT;TD width= "Ten" > </td>
<td><asp:textbox id= "Txtuser" runat= "Server"/></td>
</tr>
<tr>
<td>password: </td>
&LT;TD width= "Ten" > </td>
<td><asp:textbox id= "Txtpassword" textmode= "Password" runat= "Server"/></td>
</tr>
<tr>
<tr>
<td></td>
&LT;TD width= "Ten" > </td>
<td><asp:checkbox id= "Chkpersistlogin" runat= "Server"/>remember my credentials
<br>
</td>
</tr>
<tr>
<td> </td>
&LT;TD width= "Ten" > </td>
<td><asp:button id= "Cmdlogin" text= "Login" runat= "Server"/></td>
</tr>
</table>
<br>
<br>
<div id= "errormessage" runat= "Server"/>
</form>
</body>


Login.aspx detailed

In this case, I've added references to System.Web.Security and System.Xml, because we're going to use the classes in these two namespaces. We also wrote a process named ProcessLogin, which checks whether the table data (username and password) is the same as the password and user name contained in the XML file.

First, we created some local variables for the text edit box. Because we need to get the full path of the Users.xml file, we use the

Request.PhysicalPath the method, and then defragment the script file name. In addition, we have created a variable that holds the hashed password.

Second, we put the Xmldoc.load method call on the Try ... Catch statement. Try ... A catch statement is a new addition in the ASP.net, which is a good way to handle errors and exceptions. In the following code, we use the User node table as an array of variables, using the getElementsByTagName method to assign the user node in the XML file to it. Then check if the user exists, and if so, check that the password entered by the user is the same as stored in the XML file. If the user exists and the password is the same, we set Blnisauthenticated's duty to true. At the end of the procedure, if the value of blnisauthenticated is true, we call the RedirectFromLoginPage method. Of course, we can also use the SetAuthCookie method to do the same thing, but not the user to boot to another page.

In the Login.aspx file interface or HTML section, we have developed 2 server-correct text boxes, 1 server-side checkboxes, 1 buttons, in the button's onclick event, called the ProcessLogin. We also have a div that runs on the server side that can display error messages to the user.

Default.aspx Overview

The code in this file is the same as the Default.aspx file in the first part of this article.

Default.aspx's Code

<% @Page language= "VB"%>
<% @Import namespace= "System.Web.Security"%>
<script language= "VB" runat= "Server" >
Sub SignOut (Objsender as Object, Objargs as EventArgs)
Delete a user-authenticated cookie and exit
FormsAuthentication.SignOut ()
To boot a user to a submitted web page
Response.Redirect (Request.UrlReferrer.ToString ())
End Sub

Sub Page_Load ()
Verification Certification
If User.Identity.IsAuthenticated Then
Display authentication information
displaycredentials.innerhtml = "Current User: <b>" & User.Identity.Name & _
"</b><br><br>authentication Used: <b>" & _
User.Identity.AuthenticationType & "</b>"
Else
Display error messages
displaycredentials.innerhtml = "Sorry, have not been authenticated."
cmdsignout.disabled = True
End If

End Sub
</script>
<title>forms authentication</title>

<body bgcolor= "#FFFFFF" text= "#000000" >
<span class= "Header" >forms Based authentication using Custom method</span>
<br>
<br>
<div id= "displaycredentials" runat= "Server"/>
<br>
<br>
<form runat= "Server" >
<input id= "Cmdsignout" type= "Submit" value= "Sign Out" runat= "server" onserverclick= "SignOut"/><p/>
</form>
</body>



Default.aspx detailed

This page is exactly the same as the Default.aspx in the first part of this article, and it simply shows the user name and the authentication method used.

Hashpassword.aspx Overview

This page allows an unauthenticated user to create an encrypted password that can be used to store passwords in the credentials section of web.config, in an XML file, or in a database.

<ccid_nobr><b>hashpassword.aspx Code </b></ccid_nobr>
<% @Page language= "VB"%>
<% @Import namespace= "System.Web.Security"%>
<script language= "VB" runat= "Server" >
Sub Gethashedpass (Objsender as Object, Objargs as EventArgs)
Dim Strencpass as String
Strencpass = FormsAuthentication.HashPasswordForStoringInConfigFile (Txtpassword.value, "SHA1")
hashedpass.innerhtml = "Hashed Password for web.config, XML File or database<br><b>" & _
Strencpass & "</b>"
End Sub
</script>
<title>create Hashed password</title>

<body bgcolor= "#FFFFFF" text= "#000000" >
<b>create Hashed password</b>
<form runat= "Server" >
<table width= "100%" border= "0" cellspacing= "0" cellpadding= "0" >
<tr>
<td>password to encrypt:
<input id= "txtpassword" type= "password" runat= "server" name= "text"/>

<input type= "Submit" value= "Hash Pass" runat= "server" onserverclick= "Gethashedpass"/>
</td>
</tr>
<tr>
<tr>
<td> </td>
</tr>
<tr>
<td>
<div id= "Hashedpass" runat= "Server"/>
</td>
</tr>
</table>
</form>
</body>



Hashpassword.aspx detailed

In order to use the Forms authentication namespace, we need to use the System.Web.Security namespace again. Here, we use a procedure to receive the text of the text box and hash it with the SHA1 hash algorithm. The name of the method that completes this function is HashPasswordForStoringInConfigFile (which is probably the longest method name I have seen), which receives two parameters, one is the string that needs to be hashed, and the other is the algorithm to use, in which We can use SHA1 or MD5 algorithms.

Conclusion

As you can see in the previous manuscript, form authentication is a powerful tool in the development of Web applications. If we can master its use, it will bring great convenience to our development work.




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.