How to: Get the Current User in Code

  • 2 min to read

An application's functionality may depend on the user who is currently logged on. So, you may be required to get the user name, user ID or the entire user object. For this purpose, the static SecuritySystem class exposes the following properties.

The current user is also available in criteria expressions. It this topic, several popular scenarios of accessing the current user are listed.

Access Current User in Criteria

When you are required to use the current user in a filter criteria, use the CurrentUserId function criteria operator.

Initialize the Object Owner

To assign a current user reference to the Owner property of your business class, support the IXafEntityObject and IObjectSpaceLink interfaces in this class and implement the IXafEntityObject.OnCreated method in the following manner.

void IXafEntityObject.OnCreated() {
    Owner = objectSpace.GetObjectByKey<PermissionPolicyUser>(SecuritySystem.CurrentUserId);
}
Note

The complete example is available in the IXafEntityObject interface description.

When using XPO, you can also override the BaseObject.AfterConstruction method as follows.

public override void AfterConstruction() {
    base.AfterConstruction();
    if (SecuritySystem.CurrentUser != null) {
        Owner = Session.GetObjectByKey<PermissionPolicyUser>(SecuritySystem.CurrentUserId);
    }
}

Configure Permissions Based on the Object Owner

To grant access to objects that are owned by the current user and prohibit access to other objects, implement the Owner property as it is demonstrated above, and configure the security permissions as follows.

  • Add a Type Permission for the object type you wish to filter and set its AllowRead property to false.
  • Add an Object Permission to this Type Permission, set its AllowRead property to true and Criteria property to "Owner.Oid = CurrentUserId()".
See Also