Skip to main content
All docs
V24.2

Change the Current User Role in Code

  • 2 minutes to read

This topic describes how to access and edit a user’s role collection in applications with Integrated Mode.

Follow the steps below to replace the “Default” role with “Extended”.

  1. Create a new ViewController with SimpleAction and handle the Action’s Execute event.
  2. In the event handler, call the CreateNonsecuredObjectSpace (XPO/EF Core) method to create a non-secured IObjectSpace instance. The non-secured Object Space ignores security permissions and provides access to all data.
  3. Use the GetSecurityStrategy(XafApplication) method and User property to access the current user. Call the GetObject(Object) method to copy the user object to the non-secured Object Space.
  4. Remove the “Default” role from the Roles collection and add the “Extended” role to this collection.
  5. Call the CommitChanges() method of the unsecured Object Space to save these changes.
  6. Call the Refresh() method of the main Object Space to display the new changes in the UI.
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.Persistent.Base;
using DevExpress.ExpressApp.Security;
using DevExpress.Persistent.BaseImpl.PermissionPolicy;
using System.Linq;
// ...
public class SetExtendedRoleController : ViewController {
    SimpleAction setExtendedRoleAction; 
    public SetExtendedRoleController() {
        setExtendedRoleAction = new SimpleAction(this, "SetExtendedRole", PredefinedCategory.Edit);
        setExtendedRoleAction.Execute += SetExtendedRoleAction_Execute;
    }

    private void SetExtendedRoleAction_Execute(object sender, SimpleActionExecuteEventArgs e) {
        using (IObjectSpace nonSecuredObjectSpace =
            ((INonsecuredObjectSpaceProvider)Application.ObjectSpaceProvider).CreateNonsecuredObjectSpace()) {
            SecurityStrategy security = Application.GetSecurityStrategy();
            ApplicationUser user = (ApplicationUser)nonSecuredObjectSpace.GetObject(security.User);
            PermissionPolicyRole oldRole = user.Roles.FirstOrDefault(r => r.Name == "Default");
            if (oldRole != null) {
                PermissionPolicyRole newRole =
                    nonSecuredObjectSpace.FirstOrDefault<PermissionPolicyRole>(r => r.Name == "Extended");
                user.Roles.Remove(oldRole);
                user.Roles.Add(newRole);
                nonSecuredObjectSpace.CommitChanges();
                ObjectSpace.Refresh();
            }
        }
    }
}
See Also