Revoke The permission Set From The User Using An Apex Trigger.

Everyone is familiar with how permission sets offer a means to manage Salesforce access. With Apex, we can dynamically handle the assignment and removal of permission sets for users.

Here’s an example demonstrating how you can unassign a permission set from a user using an Apex trigger:

trigger UnassignPermissionSet on User (before update) {
    List<PermissionSetAssignment> psaList = [SELECT Id, PermissionSetId, AssigneeId FROM PermissionSetAssignment WHERE AssigneeId = :Trigger.Old[0].Id];
    if (!psaList.isEmpty()) {
        delete psaList;
    }
}

In this trigger, we initially fetch a collection of all PermissionSetAssignment records linked to the user undergoing an update in our Salesforce organization.

Subsequently, we examine whether the list is not empty, signifying that permission sets are assigned to the user. If this condition is met, we proceed to delete the PermissionSetAssignment records, thereby unassigning the permission sets from the user. The trigger employs a before update trigger on the User object to capture modifications to the user, ensuring the unassignment of permission sets occurs before the updates are finalized in the database.