Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

"Correct?" Its a matter of opinion.

I'd say, if you aren't experiencing issues with the database performance caused by this query, then don't worry about it.

If you are, you can centralize your authentication code into some sort of auth provider or type, and cache authentication information in memory until a write updates the database, which should invalidate the cache at the same time.

(Your second question would do well on its own; I don't have enough info to answer it.)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top