G
Guest
When I started a new ASP project I was eager to use the login facilities
offered in Framework 2.0/VS 2005.
I wanted:
- A custom principal that could hold my integer UserID from the database
- An easy way to classify different pages as either Admin, Member or Public,
where login is necessary for Admin and Member but not for Public. My idea was
to put the pages in different directories to easily keep my order.
- An easy menu system that would show only accesible pages
I carefully read the newsgroups and put together what I thought was a good
mix of working ideas. I think I am quite close but I don't really make it all
through.
Hopefully someone can give me a hint by scanning through my code sample:
===============================================
web.config content:
<authentication mode="Forms">
<forms loginUrl="Public/Login.aspx" defaultUrl="/Default.aspx"
name=".ASPXFORMSAUTH" path="\">
</forms>
</authentication>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
Global.asax content:
<script runat="server">
Protected Sub Application_AuthenticateRequest(ByVal sender As Object,
ByVal e As System.EventArgs)
Dim app As HttpApplication
Dim authTicket As FormsAuthenticationTicket
Dim authCookie As String = ""
Dim cookieName As String = FormsAuthentication.FormsCookieName
Dim userIdentity As FormsIdentity
Dim userData As String
Dim userDataGroups As String()
Dim PersonID As Integer
Dim roles As String()
Dim userPrincipal As CustomPrincipal
Dim AllowAccess as Boolean
app = DirectCast(sender, HttpApplication)
If app.Request.IsAuthenticated AndAlso
app.User.Identity.AuthenticationType = "Forms" Then
Try
'Get authentication cookie
authCookie = app.Request.Cookies(cookieName).Value
Catch ex As Exception
'Cookie not found generates exception: Redirect to loginpage
Response.Redirect("Login.aspx")
End Try
'Decrypt the authentication ticket
authTicket = FormsAuthentication.Decrypt(authCookie)
'Create an Identity from the ticket
userIdentity = New FormsIdentity(authTicket)
'Retrieve the user data from the ticket
userData = authTicket.UserData
'Split user data in main sections
userDataGroups =
userData.Split(CustomPrincipal.DELIMITER_SECTIONS)
'Read out ID and roles
PersonID = CType(userDataGroups(0), Integer)
roles = userDataGroups(1).Split(CustomPrincipal.DELIMITER_ROLES)
'Rebuild the custom principal
userPrincipal = New CustomPrincipal(userIdentity, PersonID, roles)
'Set the principal as the current user identity
app.Context.User = userPrincipal
End If
'If we already are heading for Login page then we don't need to
check anything more
If Request.Url.AbsolutePath.ToLower =
FormsAuthentication.LoginUrl.ToLower Then
Exit Sub
End If
'Evaluate if access is allowed
Select Case BaseDirectory(Request.Url)
Case "Member", "Admin"
'For all restricted pages we need to check user validity
If IsNothing(app.Context.User) Then
'User is not authenticated
AllowAccess = False
ElseIf IsNothing(SiteMap.CurrentNode) OrElse
(SiteMap.CurrentNode.Roles.Count = 0) Then
'Missing SiteMap means access is implicitly allowed
AllowAccess = True
Else
AllowAccess = False
'Loop through each role and check to see if user is in
one of them
For Each Role As String In SiteMap.CurrentNode.Roles
If app.Context.User.IsInRole(Role) Then
AllowAccess = True
Exit For
End If
Next
End If
Case Else
'Public folders are always OK
AllowAccess = True
End Select
If Not AllowAccess Then
Response.Redirect(FormsAuthentication.LoginUrl)
End If
End Sub
Protected Function BaseDirectory(ByVal u As System.Uri) As String
Select Case u.Segments.Length
Case Is < 3
Throw New Exception("BaseDirectory expecting at least one
level of directories")
Case 3
Return ""
Case Else
Return u.Segments(2).Replace("/", "")
End Select
End Function
</script>
Public Class CustomPrincipal
Inherits System.Security.Principal.GenericPrincipal
Private _PersonID As Integer
Public Const DELIMITER_SECTIONS As String = ";"
Public Const DELIMITER_ROLES As String = ","
Public Enum Roles
Member = 1
Editor = 2
Admin = 3
End Enum
Public Sub New(ByVal identity As System.Security.Principal.IIdentity,
ByVal PersonID As Integer, ByVal roles As String())
MyBase.New(identity, roles)
_PersonID = PersonID
End Sub
Public ReadOnly Property UserName() As String
Get
Return MyBase.Identity.Name
End Get
End Property
Public ReadOnly Property PersonID() As Integer
Get
Return _PersonID
End Get
End Property
Public Shadows ReadOnly Property IsInRole(ByVal role As Roles) As Boolean
Get
Return MyBase.IsInRole(role)
End Get
End Property
End Class
Partial Class Login
Inherits System.Web.UI.Page
Protected Sub cmdLogin_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles cmdLogin.Click
Dim p As Person
Dim RedirectUrl As String
Try
p = New Person
p.Load(txtUserID.Text, txtPassword.Text)
If p.IsEmpty Then
Throw New Exception("Login failed. Please check your
username and password and try again.")
End If
'Create a ticket with validated user
CreateAuthenticationTicket(p, chkPersist.Checked)
'Redirect to requested page
RedirectUrl = GetReturnUrl
Response.Redirect(RedirectUrl)
Catch ex As Exception
lblFailure.Text = ex.Message
End Try
End Sub
Public ReadOnly Property GetReturnUrl() As String
Get
If IsNothing(Request.QueryString("ReturnUrl")) Then
'Default page
Return FormsAuthentication.DefaultUrl
Else
'Requested page if present
Return Request.QueryString("ReturnUrl")
End If
End Get
End Property
Public Sub CreateAuthenticationTicket(ByVal p As Person, ByVal
Persistant As Boolean)
Dim authTicket As FormsAuthenticationTicket
Dim encTicket As String
Dim cookie As HttpCookie
Try
'Create a ticket
authTicket = New FormsAuthenticationTicket(1, p.Name, _
DateTime.Now,
DateTime.Now.AddMonths(1), _
Persistant, p.UserData)
'Encrypt the ticket into a string
encTicket = FormsAuthentication.Encrypt(authTicket)
'Create the cookie
cookie = New HttpCookie(FormsAuthentication.FormsCookieName,
encTicket)
If Persistant Then
'Specify expiration date
cookie.Expires = Now.AddMonths(1)
End If
'Save the cookie
Response.Cookies.Add(cookie)
Catch ex As Exception
Throw New Exception("CreateAuthenticationTicket: " & ex.Message)
End Try
End Sub
End Class
Sitemap content:
<siteMapNode title="Start" url="default.aspx" description="Return to start
page" roles="*">
<siteMapNode title="Activities">
<siteMapNode title="Calender" url="Public/Calendar.aspx" roles="*" />
<siteMapNode title="My Responsibility"
url="Member/MyResponsibility.aspx" roles="*" />
<siteMapNode title="Edit Activity" url="Member/ActivityEdit.aspx"
roles="1" />
<siteMapNode title="Add Activity" url="Member/ActivityAdd.aspx"
roles="2" />
</siteMapNode>
.....
================================================
Problems found with this code:
Problems:
1) You need to click Logout twice to get out
2) You don't reach pages in the Public folder without logging in
3) After login some redirection doesn't work.
If the Login page itself is placed in a subdirectory, then it will not find
the defaultURL.
4) The TreeView control based on a sitemap always show all menus even if
they are mapped to different roles.
offered in Framework 2.0/VS 2005.
I wanted:
- A custom principal that could hold my integer UserID from the database
- An easy way to classify different pages as either Admin, Member or Public,
where login is necessary for Admin and Member but not for Public. My idea was
to put the pages in different directories to easily keep my order.
- An easy menu system that would show only accesible pages
I carefully read the newsgroups and put together what I thought was a good
mix of working ideas. I think I am quite close but I don't really make it all
through.
Hopefully someone can give me a hint by scanning through my code sample:
===============================================
web.config content:
<authentication mode="Forms">
<forms loginUrl="Public/Login.aspx" defaultUrl="/Default.aspx"
name=".ASPXFORMSAUTH" path="\">
</forms>
</authentication>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
Global.asax content:
<script runat="server">
Protected Sub Application_AuthenticateRequest(ByVal sender As Object,
ByVal e As System.EventArgs)
Dim app As HttpApplication
Dim authTicket As FormsAuthenticationTicket
Dim authCookie As String = ""
Dim cookieName As String = FormsAuthentication.FormsCookieName
Dim userIdentity As FormsIdentity
Dim userData As String
Dim userDataGroups As String()
Dim PersonID As Integer
Dim roles As String()
Dim userPrincipal As CustomPrincipal
Dim AllowAccess as Boolean
app = DirectCast(sender, HttpApplication)
If app.Request.IsAuthenticated AndAlso
app.User.Identity.AuthenticationType = "Forms" Then
Try
'Get authentication cookie
authCookie = app.Request.Cookies(cookieName).Value
Catch ex As Exception
'Cookie not found generates exception: Redirect to loginpage
Response.Redirect("Login.aspx")
End Try
'Decrypt the authentication ticket
authTicket = FormsAuthentication.Decrypt(authCookie)
'Create an Identity from the ticket
userIdentity = New FormsIdentity(authTicket)
'Retrieve the user data from the ticket
userData = authTicket.UserData
'Split user data in main sections
userDataGroups =
userData.Split(CustomPrincipal.DELIMITER_SECTIONS)
'Read out ID and roles
PersonID = CType(userDataGroups(0), Integer)
roles = userDataGroups(1).Split(CustomPrincipal.DELIMITER_ROLES)
'Rebuild the custom principal
userPrincipal = New CustomPrincipal(userIdentity, PersonID, roles)
'Set the principal as the current user identity
app.Context.User = userPrincipal
End If
'If we already are heading for Login page then we don't need to
check anything more
If Request.Url.AbsolutePath.ToLower =
FormsAuthentication.LoginUrl.ToLower Then
Exit Sub
End If
'Evaluate if access is allowed
Select Case BaseDirectory(Request.Url)
Case "Member", "Admin"
'For all restricted pages we need to check user validity
If IsNothing(app.Context.User) Then
'User is not authenticated
AllowAccess = False
ElseIf IsNothing(SiteMap.CurrentNode) OrElse
(SiteMap.CurrentNode.Roles.Count = 0) Then
'Missing SiteMap means access is implicitly allowed
AllowAccess = True
Else
AllowAccess = False
'Loop through each role and check to see if user is in
one of them
For Each Role As String In SiteMap.CurrentNode.Roles
If app.Context.User.IsInRole(Role) Then
AllowAccess = True
Exit For
End If
Next
End If
Case Else
'Public folders are always OK
AllowAccess = True
End Select
If Not AllowAccess Then
Response.Redirect(FormsAuthentication.LoginUrl)
End If
End Sub
Protected Function BaseDirectory(ByVal u As System.Uri) As String
Select Case u.Segments.Length
Case Is < 3
Throw New Exception("BaseDirectory expecting at least one
level of directories")
Case 3
Return ""
Case Else
Return u.Segments(2).Replace("/", "")
End Select
End Function
</script>
Public Class CustomPrincipal
Inherits System.Security.Principal.GenericPrincipal
Private _PersonID As Integer
Public Const DELIMITER_SECTIONS As String = ";"
Public Const DELIMITER_ROLES As String = ","
Public Enum Roles
Member = 1
Editor = 2
Admin = 3
End Enum
Public Sub New(ByVal identity As System.Security.Principal.IIdentity,
ByVal PersonID As Integer, ByVal roles As String())
MyBase.New(identity, roles)
_PersonID = PersonID
End Sub
Public ReadOnly Property UserName() As String
Get
Return MyBase.Identity.Name
End Get
End Property
Public ReadOnly Property PersonID() As Integer
Get
Return _PersonID
End Get
End Property
Public Shadows ReadOnly Property IsInRole(ByVal role As Roles) As Boolean
Get
Return MyBase.IsInRole(role)
End Get
End Property
End Class
Partial Class Login
Inherits System.Web.UI.Page
Protected Sub cmdLogin_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles cmdLogin.Click
Dim p As Person
Dim RedirectUrl As String
Try
p = New Person
p.Load(txtUserID.Text, txtPassword.Text)
If p.IsEmpty Then
Throw New Exception("Login failed. Please check your
username and password and try again.")
End If
'Create a ticket with validated user
CreateAuthenticationTicket(p, chkPersist.Checked)
'Redirect to requested page
RedirectUrl = GetReturnUrl
Response.Redirect(RedirectUrl)
Catch ex As Exception
lblFailure.Text = ex.Message
End Try
End Sub
Public ReadOnly Property GetReturnUrl() As String
Get
If IsNothing(Request.QueryString("ReturnUrl")) Then
'Default page
Return FormsAuthentication.DefaultUrl
Else
'Requested page if present
Return Request.QueryString("ReturnUrl")
End If
End Get
End Property
Public Sub CreateAuthenticationTicket(ByVal p As Person, ByVal
Persistant As Boolean)
Dim authTicket As FormsAuthenticationTicket
Dim encTicket As String
Dim cookie As HttpCookie
Try
'Create a ticket
authTicket = New FormsAuthenticationTicket(1, p.Name, _
DateTime.Now,
DateTime.Now.AddMonths(1), _
Persistant, p.UserData)
'Encrypt the ticket into a string
encTicket = FormsAuthentication.Encrypt(authTicket)
'Create the cookie
cookie = New HttpCookie(FormsAuthentication.FormsCookieName,
encTicket)
If Persistant Then
'Specify expiration date
cookie.Expires = Now.AddMonths(1)
End If
'Save the cookie
Response.Cookies.Add(cookie)
Catch ex As Exception
Throw New Exception("CreateAuthenticationTicket: " & ex.Message)
End Try
End Sub
End Class
Sitemap content:
<siteMapNode title="Start" url="default.aspx" description="Return to start
page" roles="*">
<siteMapNode title="Activities">
<siteMapNode title="Calender" url="Public/Calendar.aspx" roles="*" />
<siteMapNode title="My Responsibility"
url="Member/MyResponsibility.aspx" roles="*" />
<siteMapNode title="Edit Activity" url="Member/ActivityEdit.aspx"
roles="1" />
<siteMapNode title="Add Activity" url="Member/ActivityAdd.aspx"
roles="2" />
</siteMapNode>
.....
================================================
Problems found with this code:
Problems:
1) You need to click Logout twice to get out
2) You don't reach pages in the Public folder without logging in
3) After login some redirection doesn't work.
If the Login page itself is placed in a subdirectory, then it will not find
the defaultURL.
4) The TreeView control based on a sitemap always show all menus even if
they are mapped to different roles.