Question

I have an MVC4 site and have recently noticed some unexpected behaviour regarding Roles which Im sure is something I have either misunderstood or overlooked but I cant see the problem yet so here goes;

On Login I create an authticket including the roles information in Userdata.

In Application_AuthenticateRequest I retrieve the Role data and assign it to the CurrentUser.

Notwithstanding I suspect I should be using an Authorize mechanism, can anyone see why when I later check User.IsInRole() it times out trying to hit SqlServer presumably because it thinks it is acting as the RoleProvider (its not set in config), why is it not just getting it from the Current User as assigned in the Global.asax?

TIA, dan

[snipped from my Application_AuthenticateRequest]

try
        {
            if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated)
            {
                var currentUser = HttpContext.Current.User;
                var formsId = currentUser.Identity as FormsIdentity;
                var ticket = formsId.Ticket;
                string userData = ticket.UserData;

                var rolesString = userData.GetValueFromKeyValuePairs<string>("roles", "|");
                var rolesList = rolesString.SplitAndType<string>("|").Select(s => s.ToLower().Replace(" ", ""));

                if (rolesList.Count() > 0)
                {
                    HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(ticket.Name), rolesList.ToArray());
                }
            }
        }
        catch (Exception ex)
        {
            if (Debugger.IsAttached)
            {
                throw ex;
            }
        }
Était-ce utile?

La solution

Ok, so I was setting the User roles at the wrong point in the lifecycle and they were being overwritten, moving the code verbatim to this event ensures it is not overwritten.

Application_PostAuthenticateRequest(Object sender, EventArgs e)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top