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_Sta rt(object sender, EventArgs e)
{
// Code that runs on application startup
AuthenticationS ervice.Authenti cating
+= new EventHandler<Au thenticatingEve ntArgs>
(Authentication Service_Authent icating);
/// Customize the cookie returned, adding role
/// and other information.
AuthenticationS ervice.Creating Cookie
+= new EventHandler<Cr eatingCookieEve ntArgs>
(Authentication Service_Creatin gCookie);
}
void AuthenticationS ervice_Authenti cating(object sender,
AuthenticatingE ventArgs 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.CustomCredent ial.Split(new char[]
{ ',' });
if (credentials.Le ngth != 0
&& int.TryParse(cr edentials[0], out organizationId) )
{
e.Authenticated =
MembershipManag er.ValidateUser (e.UserName,
e.Password,
organizationId) ;
}
e.Authenticatio nIsComplete = true;
}
void AuthenticationS ervice_Creating Cookie(object sender,
CreatingCookieE ventArgs e)
{
int organizationId;
if (int.TryParse(e .CustomCredenti al, out organizationId) )
{
string roles = RoleManager.Get RolesForUser(e. UserName,
organizationId) ;
FormsAuthentica tionTicket ticket = new
FormsAuthentica tionTicket(1,
e.UserName,
DateTime.Now,
DateTime.Now.Ad dHours(2),
false,
roles,
FormsAuthentica tion.FormsCooki ePath);
string encryptedTicket =
FormsAuthentica tion.Encrypt(ti cket);
HttpCookie cookie = new HttpCookie(
FormsAuthentica tion.FormsCooki eName,
encryptedTicket );
cookie.Expires = DateTime.Now.Ad dHours(2);
cookie.Domain = ".localhost ";
HttpContext.Cur rent.Response.C ookies.Add(cook ie);
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_Aut henticateReques t(object sender, EventArgs e)
{
HttpCookie ticketCookie
=
Context.Request .Cookies[FormsAuthentica tion.FormsCooki eName];
if (null == ticketCookie)
{
return;
}
try
{
FormsAuthentica tionTicket ticket
= FormsAuthentica tion.Decrypt(ti cketCookie.Valu e);
if (null != ticket)
{
string[] roles =
RoleManager.Get RolesFromString (ticket.UserDat a);
FormsIdentity identity = new FormsIdentity(t icket);
Context.User = new GenericPrincipa l(identity, roles);
}
}
catch (Exception ex)
{
/// TODO: Make to call to exception utility method
}
}