Roles and Forms Authentication problems
From: wrecker (wrecker_at_wrecked.com)
Date: Wed, 24 Aug 2005 15:10:03 -0400
I have been struggling with getting role-based security working with forms authentication. There
are two things happening/not happening in my code that for the life of me I can not figure out.
The first is that when I create my authentication ticket containing my roles and add the cookie, the
cookie will not add if I use
Dim cookie As HttpCookie = New HttpCookie(FormsAuthentication.FormsCookieName, hash)
However, if I hardcode the name of the cookie then the cookie will add
Dim cookie As HttpCookie = New HttpCookie("MY.AUTH", hash)
When I examine FormsAuthentication.FormsCookieName in the debugger is does indeed show the proper
value for the cookie name from the web.config. What is going on?
Second, in the global.asax Application_AuthenticateRequest() when I try to retrieve the role
information that I have stored in the cookie, the ticket is filled in with all the appropriate
information that I'd set upon login (like name, expiration etc.) but the ticket.UserData is blank!
If Not (HttpContext.Current.User Is Nothing) Then
If HttpContext.Current.User.Identity.IsAuthenticated Then
If TypeOf HttpContext.Current.User.Identity Is System.Web.Security.FormsIdentity
Dim id As System.Web.Security.FormsIdentity
id = CType(HttpContext.Current.User.Identity, System.Web.Security.FormsIdentity)
Dim ticket As System.Web.Security.FormsAuthenticationTicket
ticket = id.Ticket
Dim userData As String = ticket.UserData
Dim roles() As String = userData.Split(",")
HttpContext.Current.User = New GenericPrincipal(id, roles)
Both of these problems are very strange and I have not benn able to find a resolution for either of
them. I wrote a small test application seperate from main application and I'm not seeing the
problems that I am here. Could it be related to how the application is set up? The root directory
contains the web.config and the global.asax. The login page resides in a secure folder under root.
The code that logs that authenticates the user, creates the ticket and adds the cookie resides in
module of common functions in a folder called common.
This folder structure (which I inherited from a previous developer) is the only thing different from
my test application and my main application.
Can someone help me solve this very strange problem?