Adding user to BackendUsers role
Hello,
I am trying to programmatically add a user to the BackendUsers role (which occurs via the site, when you check the 'can access backend' box when creating a user).
I do know you can call:
user.IsBackendUser =
true
;
if
(userManager.UserExists(user.UserName))
foreach
(
string
roleName
in
rolesToAdd)
if
(roleManager.RoleExists(roleName))
Role role = roleManager.GetRole("BackendUsers");
roleManager.AddUserToRole(user, role);
I have solved this. For reference:
RoleManager roleManager = RoleManager.GetManager(
"AppRoles"
);
Thanks Richard, the RoleManager did not work for me until I specifically requested that provider.
Does anyone know why RoleManager.GetManager() does not work by default? I don't think I've done anything special with the security providers. I'm using Sitefinity 5.3 and claims authentication.
Hi Arno,
The problem comes from the fact that some roles that you query are in different provider than the "Default" (only the default roles provider is requested with GetProvider(). In order to get all roles for a specific user you need to check all providers for the user's roles. Here's an example code:
var providers = RoleManager.GetManager().Providers;
foreach
(var provider
in
providers)
var manager = RoleManager.GetManager(provider.Name).Provider;
manager.SuppressSecurityChecks =
true
;
string
roleName =
"Custom"
;
Role MyRole = manager.GetRoles().Where(r => r.Name == roleName).FirstOrDefault();
var uManager = UserManager.GetManager();
var loggedInUser = uManager.GetUser(
"Approver1"
);
if
(MyRole !=
null
)
var roleid = MyRole.Id;
if
(manager.RoleExists(MyRole.Name))
//var users = manager.GetUsersInRole(roleid).ToList();
manager.IsUserInRole(loggedInUser.Id, roleid);
Thanks Jen, I had no idea about that. Looping through all providers makes my code work in all cases.