This may be a slightly ignorant question but Im new to mvc so Im sorry!
I studied the nerd dinner auth model but In my app I have a complicated role based authentication. So What I do is this:
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
HttpCookie authCookie = HttpContext.Current.Request
.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
string encTicket = authCookie.Value;
if (!String.IsNullOrEmpty(encTicket))
{
FormsAuthenticationTicket ticket =
FormsAuthentication.Decrypt(encTicket);
CustomIdentity id = new CustomIdentity(ticket.Name);
GenericPrincipal prin = new GenericPrincipal(id, id.Roles);
HttpContext.Current.User = prin;
}
}
}
On LogOn I authentication the username/pass with FormsAuth and then I create the cookie.
The problem here is every time I create the custom identity, I have to query the database for the users roles. Is there a correct way around this or am I doing the right thing to query the DB on every incoming request? Should I save the roles list in a cookie or something?
I also don't really understand the whole life cycle of how forms auth takes care of the authentication? I use the same IFormsAuthentication
design pattern that nerd dinner users and during a sign-in I call FormsAuth.SignIn()
which in turn calls FormsAuthentication.SetAuthCookie
, When does it manage to call the membershipservice.validateuser()
method ?? Also if the auth cookie has been set why would nerd dinner create a ticket, then add it into the request, and then read it during PostAuthenticationRequest
to check which user it was. Does the ticket operation like a session?
Thanks! Merry Christmas!
Update : This link gave me a slightly better understanding about forms authentication ticket.
An alternative approach is to store your user's roles in the authentication ticket when your user is authenticated. Then for every request (Application_AuthenticateRequest
method of the global.asax file) you can extract the roles from the authentication ticket and create a GenericPrincipal
.
See this answer for more details.