3

I'm following this article in which is described how to assign roles to users when theiy log-in using forms authentication:

public void Application_AuthenticateRequest( Object src , EventArgs e )
{
   if (!(HttpContext.Current.User == null))
   {
      if (HttpContext.Current.User.Identity.AuthenticationType == "Forms" )
      {
      System.Web.Security.FormsIdentity id;
      id = (System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity;
      String[] myRoles = new String[2];
      myRoles[0] = "Manager";
      myRoles[1] = "Admin";
      HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id,myRoles);
      }
   }
}

I put the role logic in the event handler, so I basically don't need a role provider. Nonetheless, in order to run this, appears that I must enable Role Provider in web.config. Sadly, if I just put:

<roleManager enabled="true"/>

it results in runtime errors related to a failed connection to the SQL server, like if I chose AspNetSqlRoleProvider as Role Provider.

What should I do to have roles working this way? How can I choose to use no role provider, or how should I implement a dummy one (if it makes any sense)?

1
  • The code looks fine to me. I don't believe you need to enable a role manager to do this. What happens if you don't enable the role provider in web.config? Sep 24, 2012 at 13:03

1 Answer 1

2

You shouldn't need to enable roleManager in web.config - after all, people used to use roles with .NET 1.x before roleManager came along.

One thing that roleManager will do for you that you haven't done in your code is set Thread.CurrentPrincipal to HttpContext.Current.User. If you're relying on this (e.g. using PrincipalPermissionAttribute), then you need to add this:

Thread.CurrentPrincipal = HttpContext.Current.User;

Otherwise, I'd expect it to work: what symptoms are you seeing that makes you think it isn't working?

As for implementing a dummy RoleProvider, it's easy enough: for example see this MSDN article.

You only need to implement the GetRolesForUser and IsInRole methods; the other methods can simply throw NotSupportedException.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.