Jan
04
2006
Built-in Forms Authentication - sample with DOWNLOAD
Posted by admin under
ASP.NET articles
We want to implement a login solution to all files in directory /admin/. All other pages should be public. Lets look at the filestructure in Visual Studio:
The webroot default.aspx page looks like this:
As you can see we can surf to that page with no trouble. When trying to access /admin/default.aspx ASP.NET intercepts that call and shows the login.aspx page:
I have added a little error message when login doesn't succeed:
and after successfull logon the secret pages are shown to us:
Download zip solution
Code from files:
web.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<location path="admin">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
<system.web>
<compilation
defaultLanguage="c#"
debug="true"
/>
<customErrors
mode="RemoteOnly"
/>
<authentication mode="Forms">
<forms name="mylogin" loginUrl="admin/login.aspx">
<credentials passwordFormat="Clear">
<user name="kalle" password="kallepwd" />
<user name="pelle" password="pellepwd" />
</credentials>
</forms>
</authentication>
<authorization>
<allow users="*" /> <!-- Allow all users -->
</authorization>
<trace
enabled="false"
requestLimit="10"
pageOutput="false"
traceMode="SortByTime"
localOnly="true"
/>
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes"
cookieless="false"
timeout="20"
/>
<globalization
requestEncoding="utf-8"
responseEncoding="utf-8"
/>
</system.web>
</configuration>
admin/login.aspx <%@ Page language="c#" Codebehind="login.aspx.cs" AutoEventWireup="false" Inherits="Login.login" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>login</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<table>
<tr>
<td><asp:Label id="lblID" runat="server">ID:</asp:Label></td>
<td><asp:TextBox id="txtID" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Label id="lblPwd" runat="server">Password:</asp:Label></td>
<td><asp:TextBox id="txtPwd" runat="server" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<td colspan="2" align="center"><asp:Button id="btnLogin" runat="server" Text="Log in"></asp:Button> </td>
</tr>
</table>
<asp:Label id="LabelError" runat="server" ForeColor="Red"></asp:Label>
</form>
</body>
</HTML>
admin/login.cs codebehind from button click
private void btnLogin_Click(object sender, System.EventArgs e)
{
if ( FormsAuthentication.Authenticate(txtID.Text, txtPwd.Text) )
{ //ok
FormsAuthentication.RedirectFromLoginPage(txtID.Text,false);
}
else
{
LabelError.Text = "Error logging in";
}
}