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: