1

In MVC2, I am running into a situation where my HttpContext.User.IsInRole(xxx) check immediately after calling FormsService.SignIn returns false, but in a subsequent call to Page.User.IsInRole(xxx) returns true, which is correct. Can't figure out what's going on. Here's the code:

Account Controller:

if (MembershipService.ValidateUser(model.UserName, model.Password))
{
    FormsService.SignIn(model.UserName, model.RememberMe);

    if (HttpContext.User.IsInRole("Teacher")) //returns false, even when true
    {
         //set up custom user object
    }
    else
    {
         //set standard user object
    }

    ....
}

Subsequent View:

  <%
        var teacher = Page.User.IsInRole("Teacher"); //returns true
    %>

Config:

<roleManager enabled="true" defaultProvider="MySqlRoleProvider" cacheRolesInCookie="false" createPersistentCookie="false" cookieProtection="All">
  <providers>
    <clear />
    <add applicationName="myapp" connectionStringName="ApplicationServices" name="MySqlRoleProvider" type="System.Web.Security.SqlRoleProvider" />
  </providers>
</roleManager>

Have tried w/cacheRolesInCookie true and false, makes no difference.

What am I missing?

Thanks for any ideas!

sydneyos
  • 4,527
  • 6
  • 36
  • 53

2 Answers2

1

Replace:

if (HttpContext.User.IsInRole("Teacher")) 

with:

if (Roles.IsUserInRole(model.UserName, "Teacher")) 

and it should work.

Rafał Rawicki
  • 22,324
  • 5
  • 59
  • 79
Alex Pana
  • 11
  • 1
0

FormsService.SignIn sets an authentication cookie which gets read and processed for the first time on the next request. So your User is authenticated, but your current request isn't updated to that fact.

One solution is to redirect to some action right after signing in and access the user's data after that.

ghallas
  • 285
  • 2
  • 14