views:

218

answers:

1

I'm using multiple role providers, the standard SQL provider plus a custom one. Inside Global.asax - RoleManager_GetRoles I create a RolePrincipal for users that should use my custom provider with the provider name set to my custom provider, and let other users be handled as normal.

This almost works, asp.net allows access to pages protected via the web.config and calls my provider to get the list of roles. However, when I call Roles.GetRolesForUser() inside my code it only seems to invoke the default role provider, not my custom provider. If I set my custom provider to be the default, then it is invoked, but only it is ever invoked.

I've worked around it by instead enumerating the role providers and calling GetRolesForUser() on the provider with a matching name to the RolePrincipal, but it seems to me that Roles.GetRolesForUser() should be doing that by default.

Am I missing something? Thanks.

A: 

The RoleManager and RolePrincipal are different objects for different purposes.

I think what you want to be using is a call to GetRoles() on your RolePrincipal instance, rather than Roles.GetRolesForUser().

The difference is that an explicit RolePrincipal is defining the relationship between a user and a provider, whereas Roles is just a management object for role providers, and given no other information, will just use the default provider. From the documentation for RolePrincipal:

The RolePrincipal object implements the IPrincipal interface and represents the current security context for the HTTP request.

When role management is enabled (see Roles), the RoleManagerModule assigns a RolePrincipal object to the User property of the Current HttpContext.

The RolePrincipal class exposes the security identity for the current HTTP request and additionally performs checks for role membership. If CacheRolesInCookie is true, then the RolePrincipal object manages the cached list of roles and looks up role membership for the current user in the cached list first, then the role Provider. If CacheRolesInCookie is false, the RolePrincipal object always looks up role membership using the role provider.

Hope that helps.

womp
That makes sense and matches the behavior I'm seeing. Unfortunately I'm dealing with a large amount of pre-existing code that uses Roles.GetRolesForUser().Time for a re-factoring I guess. Thanks.
Eddie
No problem. If you get answers that help you, you should feel free to upvote them. ;)
womp