[ Download Code ]
I will discuss authentication and authorization simultaneously because these elements work together. There are four types of authentication that are available:
- Windows (which is the default)
- Forms
- Passport
- None
I will provide a sample using Forms authentication. (Be sure to read the Pros and Cons at MSDN.)
Listing 2: Example Authentication and Authorization Elements
<authentication mode="Forms">
<forms name="login" loginUrl="login.aspx" />
</authentication>
<authorization>
<allow roles="author" />
<allow roles="editor" />
<allow users="reader" />
<deny users="*" />
</authorization>
The next step is to add the appropriate code in the Global.aspx file which will handle the application authentication. The default Global.aspx (VB.NET) will look like the following.
Listing 3: Default VB.NET Global.aspx
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires upon attempting to authenticate the use
End Sub
All you need to do is replace the above default routine with the following. Take notice of the two imports as well.
Listing 4: Modified VB.NET Global.aspx
Imports System.Security.Principal
Imports System.Web.Security
Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
' Fires upon attempting to authenticate the use
If Not (HttpContext.Current.User Is Nothing) Then
If HttpContext.Current.User.Identity.IsAuthenticated Then
If TypeOf HttpContext.Current.User.Identity Is FormsIdentity Then
Dim formsIdent As FormsIdentity = CType(HttpContext.Current.User.Identity, FormsIdentity)
Dim formsAuthTicket As FormsAuthenticationTicket = formsIdent.Ticket
Dim astrRoles As String() = formsAuthTicket.UserData.Split("|"c)
HttpContext.Current.User = New GenericPrincipal(formsIdent, astrRoles)
End If
End If
End If
End Sub
If you are using C# then use the following method.
Listing 5: Modified C# Global.aspx
using System.Security.Principal;
using System.Web.Security;
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
//Fires upon attempting to authenticate the use
if (!(HttpContext.Current.User == null))
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity.GetType() == typeof(FormsIdentity))
{
FormsIdentity formsIdent = (FormsIdentity) HttpContext.Current.User.Identity;
FormsAuthenticationTicket formsAuthTicket = formsIdent.Ticket;
String[] astrRoles = formsAuthTicket.UserData.Split('|');
HttpContext.Current.User = new GenericPrincipal(formsIdent, astrRoles);
}
}
}
}
I am not going to cover the details of what is happening with the Global.aspx. Later in the article I will provide a variety of resources that will assist you further.