Hi everyone,
I'm using WCF authentication services in my current project. I used
the following information as a starting point:
http://msdn.microsoft.com/en-us/library/bb398990.aspx
Unfortunately, I can't manage to get/set the generic principal when I
call other services. The authentication cookie is always null. I've
included some of my Global.asax code below. Any help would be greatly
appreciated:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
AuthenticationService.Authenticating
+= new EventHandler<AuthenticatingEventArgs>
(AuthenticationService_Authenticating);
/// Customize the cookie returned, adding role
/// and other information.
AuthenticationService.CreatingCookie
+= new EventHandler<CreatingCookieEventArgs>
(AuthenticationService_CreatingCookie);
}
void AuthenticationService_Authenticating(object sender,
AuthenticatingEventArgs e)
{
e.Authenticated = false;
/// Theoretical custom credential that would distinguish
/// duplicate user names for the purpose of ensuring
/// unique authentication MK 04/13/08
int organizationId;
string[] credentials = e.CustomCredential.Split(new char[]
{ ',' });
if (credentials.Length != 0
&& int.TryParse(credentials[0], out organizationId))
{
e.Authenticated =
MembershipManager.ValidateUser(e.UserName,
e.Password,
organizationId);
}
e.AuthenticationIsComplete = true;
}
void AuthenticationService_CreatingCookie(object sender,
CreatingCookieEventArgs e)
{
int organizationId;
if (int.TryParse(e.CustomCredential, out organizationId))
{
string roles = RoleManager.GetRolesForUser(e.UserName,
organizationId);
FormsAuthenticationTicket ticket = new
FormsAuthenticationTicket(1,
e.UserName,
DateTime.Now,
DateTime.Now.AddHours(2),
false,
roles,
FormsAuthentication.FormsCookiePath);
string encryptedTicket =
FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
encryptedTicket);
cookie.Expires = DateTime.Now.AddHours(2);
cookie.Domain = ".localhost";
HttpContext.Current.Response.Cookies.Add(cookie);
e.CookieIsSet = true;
}
}
/// <summary
/// Recreates the Principal on every request, assigning roles
/// and other information from the authentication ticket.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Application_AuthenticateRequest(object sender, EventArgs e)
{
HttpCookie ticketCookie
=
Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (null == ticketCookie)
{
return;
}
try
{
FormsAuthenticationTicket ticket
= FormsAuthentication.Decrypt(ticketCookie.Value);
if (null != ticket)
{
string[] roles =
RoleManager.GetRolesFromString(ticket.UserData);
FormsIdentity identity = new FormsIdentity(ticket);
Context.User = new GenericPrincipal(identity, roles);
}
}
catch (Exception ex)
{
/// TODO: Make to call to exception utility method
}
}