This is a start to a tutorial on Security in ASP.NET 1.1 using VB.Net code behind.

SETUP:
** Note this tutorial builds on/off the Updated:Simple ASP.Net Login Page tutorial **


Login.aspx HTML Code:

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="Login.aspx.vb" Inherits="NorthLogin3.WebForm1"%>
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
	<head>
	    <title>Northwind Database Login</title>
		<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
		<meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
		<meta content="JavaScript" name="vs_defaultClientScript">
		<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
		<!-- <summary>
			|||||	Style Sheet |||||
			</summary>
	    --><link title="standard" href="Styles.css" type="text/css" rel="stylesheet">
	</head>
	<body>
		<!-- |||||	Login Form	||||| -->
		<form id="frmlogin" method="post" runat="server">
		    <table id="mainTable" border="0">
		        <tr>
		    	    <td>
		    		    <table class="t_border" id="loginTable" cellspacing="15" cellpadding="0">
		    		        <tr>
					   <td><b>Login: </b>
					   </td>
					   <td><asp:textbox id="txtUserName" runat="server" width="160px"></asp:textbox><asp:requiredfieldvalidator id="rvUserValidator" runat="server" controltovalidate="txtUserName" errormessage="You must supply a Username!"
		 		 		 display="None"></asp:requiredfieldvalidator></td>
		    		        </tr>
		    		        <tr>
					   <td><b>Password: </b>
					   </td>
					   <td><asp:textbox id="txtPassword" runat="server" width="160px" textmode="Password"></asp:textbox><asp:requiredfieldvalidator id="rvPasswordValidator" runat="server" controltovalidate="txtPassword" errormessage="Empty Passwords not accepted"
		 		 		 display="None"></asp:requiredfieldvalidator></td>
		    		        </tr>
		    		        <tr>
		 		 		<td align="center" colspan="2"><asp:button id="cmdSubmit" runat="server" text="Submit" borderstyle="Solid"></asp:button></td>
		    		        </tr>
		    		    </table>
		    	    </td>
		        </tr>
		        <tr>
		    	    <td>
		    		    <table id="messageDisplay">
		    		        <tr>
					   <td><asp:validationsummary id="Validationsummary1" runat="server" width="472px" displaymode="BulletList"></asp:validationsummary></td>
		    		        </tr>
		    		    </table>
		    		    <asp:hyperlink id="hl_Register" runat="server" navigateurl="Register.aspx" font-size="X-Small"
		    		        height="8px" width="209px" font-names="MS Reference Sans Serif">New User?...Register Here!</asp:hyperlink>
		    	    </td>
		        </tr>
			</table>
		</form>
	    <asp:label id="lblMessage" runat="server" width="288px" font-bold="True" font-italic="True"
		    font-size="Medium" forecolor="#C00000"></asp:label>
	    <asp:label id="lblMessage2" runat="server" width="288px" font-bold="True" font-italic="True"
		    font-size="Medium" forecolor="#C00000"></asp:label>
	    <!--	|||||    End of Form	|||||    -->
	</body>
</html>

[img]http://www3.telus.net/public/tmlohnes/ExampleLogin.jpg[/img]

ASP.NET Security Data Flow:

Web Client makes request --> IIS performs some basic HTTP authentication procedures --> ASP.NET uses the authentication toke that was passed to it by IIS --> ASP.Net authenticates & authorizes the client via web.config --> CLR (Common Language Runtime) performs more indepth checks --> via ASP.NET impersonation the Operating System then processes the request to its conclusion.

Forms Authentication:

With ASP.Net you can opt to authenticate not through IIS but through your application via Forms Authentication.

Scenario -->

  • Client Requests Page on your site<<<<<<
  • If the request does not contain a valid authentication cookie, your web server redirects the client to the URL specified in the loginUrl attribute of the Authentication tag in your web.config file. The URL will be the location of the Login form page for the client.<<<<<<
  • Credentials are entered into the form and submitted via a form post.<<<<<<
  • If valid, and AuthCookie is generated<<<<<<
  • The client is then redirected to the originally requested page. <<<<<<

Code to add to Web.Config (Forms Authentication) - partial Web.Config Listing:

<!-- If the AuthCookie is not found the user is redirected to the loginUrl -->
    <authentication mode="Forms">
	    <forms name="AuthCookie" path="/" loginUrl="Login.aspx" protection="All">
		    <credentials passwordFormat="Clear">
		    	<user name="admin" password="admin" />
		    </credentials>
		</forms>
	</authentication>

	<!--  AUTHORIZATION 
		 This section sets the authorization policies of the application. You can allow or deny access
		 to application resources by user or role. Wildcards: "*" mean everyone, "?" means anonymous 
		  (unauthenticated) users.
	-->
    <authorization>

Notice the passwordFormat is set to Clear. This attribute can have these values; Clear = No encryption, or MD5 or SHA1, which are well known encryption algorithms. Which I will dicuss in updates to this tutorial.


Required Imports:

Imports System.Web.Security	 '   ||||||   Required Class for Authentication
Imports System.Data			 '   ||||||   DB Accessing Import
Imports System.Data.SqlClient   '   ||||||   SQL Server Import
Imports System.Configuration    '   ||||||   Required for Web.Config appSettings |||||

Login.aspx Code Behind for the OnClick of the Submit Button(in VB.NET):

Private Sub cmdSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click
		If Page.IsValid Then    '   ||||| Meaning the Control Validation was successful!
		    '   |||||   Connect to Database for User Validation |||||

		    If FormsAuthentication.Authenticate(txtUserName.Text.Trim(), txtPassword.Text.Trim()) Then
			    FormsAuthentication.SetAuthCookie(txtUserName.Text, False)
				Response.Redirect("default.aspx")
			Else
			    lblMessage.Text = "Invalid Login!"
			End If
		End If

	End Sub

When the client is authenticated, a cookie named AuthCookie is created. If this cookie is not present, the user is redirected to the LoginUrl of Login.aspx, which contains the form that allows the user to login in.

In the code behind the username is passed into the Cookie and the cookie is set to NOT persist when the user closes their browser. You would want this to happen, otherwise if someone else was to use the clients' browser they would automatically login with the first persons credentials. Security Breach!

In our scenario the user requests a page that is restricted, and ASP.Net automatically sends them to the loginUrl. The requested URL is stored in the querystring object, which we can use when the client logins in successfully. We use this stored querystring value to take them directly to that orignally requestd URL/Page.

How? With the FormsAuthentication.RedirectFromLoginPage method. This method does two things for us; it sets the authentication cookie exactly like the SetAuthCookie method, but it also causes a redirect back to the originally requested URL stored in the querystring.



Updated Login.aspx Code Behind - utilizing RedirectFromLoginPage:

Private Sub cmdSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click
		If Page.IsValid Then    '   ||||| Meaning the Control Validation was successful!
		    '   |||||   Connect to Database for User Validation |||||

		    If DBConnection(txtUserName.Text.Trim(), txtPassword.Text.Trim()) Then
			    GetUserInfo(txtUserName.Text.Trim())
			 FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False)  '   |||||   default.aspx Page if no page originally requested!
			 'FormsAuthentication.SetAuthCookie(txtUserName.Text, False)
			 ' ||||| Creates the AuthCookie, and sets it to NOT persist after the browser is closed.
			Else
			    '   |||||   Credentials are Invalid
			    lblMessage.Text = "Invalid Login!"
			End If
		End If

It should be made clear that if the client requests this page directly they will be directed to the default.aspx page on successful login.

Code for default.aspx (or any other page to check authentication):

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
		 If Not (User.Identity.IsAuthenticated) Then
			 Response.Redirect("Login.aspx")
		 End If
 
	End Sub

You don't have to put the user information in the Web.Config file, but rather you could put the information in a database and build custom routines to authenticate users. Using this approach will disallow you from using the Authenticate method to validate users.

The FormsAuthentication object also contains a SignOut method to log the user out. This removes the authentication cookie, and forces the client to log in again if they want acess to any pages in your application.

You can also use the mode="Passport" in the web.config file in order to use the authentication service (not a Web Service) provided by Microsoft. http://www.passport.com for details on this.

As well you can rely on Windows to process your security, but that is beyond the scope of this tutorial.

Part 2 I will go onto demonstrate SHA1, etc encryption

Happy Coding :cool:

Hi Paladine,

I really like your tutorials because they are very straight forward and simple.
Have you ever wrote one on Role-base Security connect to Ms Access?
Are you planning to write one soon?

Thanks in advance,

Bee :)

Thanks, I appreciate the complments.

Role based.... I was thinking about that. I will try to piece something together. I may do that one before SHA1 encrytion.

Keep checking back for updates

ON REQUEST:

Role Based Security
Windows operating system supports role-based security. A role is basically an defined identity. Usually a role has several identities associated with it. i.e. Your computer at work would more than likely have multiple logins / roles associated with it. An administrator, power-user (may be you), and guests.

In Windows these identities are known as users.

So to add identities you would do so in the Control Panel --> User Account Section.

Under IIS in Windows 2000 & XP --> Properties of the Web Server --> Directory Security --> The Anonymous Access & Authentication Control there is a means of editing your authentication method. The default anonymous access is the IUSR_MachineName username. One other important part to notice is the Check Box labeled Integrated Windows Authentication. With this set, you are able to implement Role based security.

[img]http://www3.telus.net/public/tmlohnes/Image2.jpg[/img]


In the web.config file you will have to set the authentication mode to "windows". This signals IIS to look to windows for user accounts.

<authentication mode="windows">
		
	</authentication>

IIS uses three different types of Windows Authentication: Basic, Digest, and NTLM. Basic is the simplest form. You will have probably see this already. You go to a website, and the browser pops up a window asking for a user name and a password. You can see in the above image how to check off Basic setting for your website, or more appropriately you specific application on that webserver (done at the application directory level, and NOT the website level). Once the credentials are entered then IIS will compare these values to the operating system's list of users, and will authenicate or deny the request based on the comparison result.

Digest is simlar, except the Username and password are encrypted before they are sent across the network. This encryption mechanism is known as hashing *Note: Both Digest and Windows Authenication require that your users are running Internet Explorer (ick!).

With NTLM authentication, the user never sees a prompt for credentials, but rather once the browser makes contact with the server, it sends the encrypted username ans password information that the user used to log on to the computer. This is all done invisible to the user.

This is basically role based / windows user based security.

It all might be right i'll surely check these later but right now i am having problem in loading images in my site. I dont understand what's the problem but the image is not displayed intead an empty box is displayed. I am specifying the right path but its still not working. Plz help me as I have to submit my final project and I have only 2 days.

Works like charm, only problem is, it doesnt redirect to original calling page. It always redirects to default.aspx.

Here is my code:

Protected Sub cmdSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click
        If Page.IsValid Then    '   ||||| Meaning the Control Validation was successful!
            '   |||||   Connect to Database for User Validation |||||
            If Login(txtUserName.Text.Trim(), txtPassword.Text.Trim()) Then
                Session("Logged_IN") = "Yes"    '   |||||   Use to Validate on other pages in the application
                FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False)  '   |||||   default.aspx Page!
            Else
                '   |||||   Credentials are Invalid
                lblMessage.Text = "Invalid Login!"
            End If
        End If
    End Sub

Here is my code in page_load event which I need to secure:

If Session("Logged_IN").Equals("No") Then
            Response.Redirect("Login.aspx")
End If

What am I missing here?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.