Introduction
I have been searching through google couldn't find a better solution to authenticate user easily and quickly. Here is a solution I made so far, please comment on, help me improve it.
Background
Asp.net provide 2 authentication method, forms and windows, people normally use forms, because it provide more flexibility, while-as windows type authentication requires PC create account every user. With forms authentication a web site can use database or other method to authenticate users.
How it works
Download source code, create a IIS virtual directory, run it. That's all. It provide a default page, login page, logout page, and an admin folder, which restrict user 's access by through web.config file.
At this web.config file, important parts are:
1. Create an entry called "admin" folder, only allow users with a role of "administrators" to access it.
2. Authentication mode set to "Forms".
Web.config file snippet like this:
<location path="Admin">
<system.web>
<authorization>
<allow roles="Administrators"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<authentication mode="Forms"/>
Create a site map, which will be used to create your web site. Web.sitemap file
web.SiteMap file may look like this:
="1.0"="utf-8"
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="~" title="Home" description="">
<siteMapNode url="default.aspx" title="Home" description="" roles="*"/>
<siteMapNode url="login.aspx" title="Login" description="" roles="*"/>
<siteMapNode url="Admin/" title="Administration" description="" roles ="*" >
<siteMapNode url="Admin/default.aspx" title="Administration" description="" roles ="Administrators" />
</siteMapNode>
<siteMapNode url="logout.aspx" title="Logout" description="" roles="*"/>
</siteMapNode>
</siteMap>
Your login.aspx may look like following:
protected void btnLogin_Click(object sender, EventArgs e)
{
FormsAuthenticationUtil.RedirectFromLoginPage("Lewis", "Administrators", true);
}
FormsAuthenticationUtil is a third party dll, which I found is quite reliably pass user's roles to application. "Lewis" is a authenticated user, "Administrators" is that user's role, this role conform to our web.config's roles and folder settings.
At your global.asax, you should see following line
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id =
(FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new GenericPrincipal(id, roles);
}
}
}
}
Remeber add following line at top your Global.asax file:
<%@ Import Namespace="System.Security.Principal" %>
Please rate or comment on :)