Sub topic 15
Assigning and auditing access in Setup, Apex, and SOQL
This chapter assumes you know what profiles, permission sets, and permission set groups are, and that you can navigate Setup. It covers how to give users access, how to list who has what, and which errors appear most often.
How an assignment works
A user gets a permission set or a permission set group through a junction record. The junction object is PermissionSetAssignment. Each record links one user (AssigneeId) to one permission set (PermissionSetId). A permission set group is also stored as a PermissionSet record behind the scenes, so the same object handles both.
Every user also has one hidden permission set for their profile. It has IsOwnedByProfile = true. You will see these records in queries unless you filter them out.
Assigning in Setup
You can assign from two directions.
- From the permission set or group. Open Permission Sets (or Permission Set Groups) in Setup, select the item, and click Manage Assignments. Click Add Assignments, tick the users, and click Assign.
- From the user. Open the user record, find Permission Set Assignments (or Permission Set Group Assignments), and click Edit Assignments.
The first route suits bulk changes. The second suits one-off requests.
Common reasons an assignment fails
- License mismatch. The permission set is tied to a user license, and the user has a different one. Only users with a matching license can receive it.
- Missing permission set license. The permission set includes permissions that need a permission set license (PSL), and the user has none. Assign the PSL first.
- Expired or inactive user. You cannot assign to a deactivated user.
- Duplicate assignment. The pair of user and permission set must be unique. A second insert fails.
Assigning with Apex
Use Apex when you assign access during provisioning, in a data load, or from a flow-invoked action. This example assigns one permission set to one user.
PermissionSet ps = [
SELECT Id
FROM PermissionSet
WHERE Name = 'Account_Viewer'
LIMIT 1
];
User u = [SELECT Id FROM User WHERE Username = '[email protected]' LIMIT 1];
insert new PermissionSetAssignment(
AssigneeId = u.Id,
PermissionSetId = ps.Id
);Query by Name, which is the API name. Labels can change and can be duplicated. The same code works for a group, because you query the group's PermissionSet record. For a group, you can instead look up PermissionSetGroup by DeveloperName and use its Id.
Bulk assignment and guarding against duplicates
Real code handles many users and may run twice. This version skips users who already hold the permission set.
public with sharing class PermSetAssigner {
public static void assign(String permSetName, Set<Id> userIds) {
PermissionSet ps = [
SELECT Id FROM PermissionSet
WHERE Name = :permSetName
LIMIT 1
];
Set<Id> alreadyAssigned = new Set<Id>();
for (PermissionSetAssignment existing : [
SELECT AssigneeId
FROM PermissionSetAssignment
WHERE PermissionSetId = :ps.Id
AND AssigneeId IN :userIds
]) {
alreadyAssigned.add(existing.AssigneeId);
}
List<PermissionSetAssignment> toInsert = new List<PermissionSetAssignment>();
for (Id userId : userIds) {
if (!alreadyAssigned.contains(userId)) {
toInsert.add(new PermissionSetAssignment(
AssigneeId = userId,
PermissionSetId = ps.Id
));
}
}
insert toInsert;
}
}The two queries and one insert stay outside any per-user loop, so the code works for a batch of users within governor limits.
Setup and non-setup objects in one transaction
PermissionSetAssignment is a setup object. If you insert it in the same transaction as a standard or custom object such as an Account, Salesforce raises a MIXED_DML_OPERATION error. In production code, run the assignment in a separate transaction, for example with a @future method or a Queueable. In a test, wrap the setup-object DML in System.runAs() with a user to keep the two apart.
Removing access
Delete the assignment record. You cannot delete the assignment that belongs to the user's profile.
delete [
SELECT Id
FROM PermissionSetAssignment
WHERE AssigneeId = :userId
AND PermissionSet.Name = 'Account_Viewer'
];Auditing with SOQL
The query below lists who holds which permission sets. The filter removes the hidden profile permission sets.
SELECT Assignee.Name, PermissionSet.Name, PermissionSet.Label
FROM PermissionSetAssignment
WHERE PermissionSet.IsOwnedByProfile = false
ORDER BY Assignee.NameYou can run it in the Developer Console Query Editor or in Apex. Adjust it for the question you are answering.
| Question | Change to the query |
|---|---|
| Who has one specific permission set? | Add `AND PermissionSet.Name = 'Account_Viewer'` |
| What does one user hold? | Add `AND AssigneeId = '005...'` |
| Which assignments come from a group? | Select `PermissionSetGroupId` and filter on `PermissionSetGroupId != null` |
| Who has a permission that grants Modify All Data? | Filter `PermissionSet.PermissionsModifyAllData = true` |
The last row is a useful security audit. Permission fields on PermissionSet are named Permissions plus the permission API name. Include profile permission sets in that audit by removing the IsOwnedByProfile filter, because a profile can grant the same permission.
Finding permission sets that grant object access
Assignments tell you who. The ObjectPermissions and FieldPermissions objects tell you what.
SELECT Parent.Name, Parent.Label, PermissionsRead, PermissionsEdit, PermissionsDelete
FROM ObjectPermissions
WHERE SobjectType = 'Account'
AND Parent.IsOwnedByProfile = falseFor fields, query FieldPermissions and filter on Field = 'Account.AnnualRevenue'. Together the two queries answer the question "who can see this field, and through which permission set."
Checking from the user's side
A user's effective access is the union of the profile, every assigned permission set, and every assigned group, minus any muted permissions. To test one user, use Login As if your org allows it, or run Apex under that user with System.runAs() in a test. For a single custom permission, FeatureManagement.checkPermission('Approve_Discounts') returns true or false for the running user across all sources.
Pitfalls
- Forgetting that profile-owned records exist. Counts of assignments look inflated until you filter them out.
- Querying by label. Use
Namefor permission sets andDeveloperNamefor groups. - Assuming a group assignment copies permissions. It does not. The user is linked to the group, and the group's calculated permissions apply.
- Reading a query result while a group is recalculating. Assignments are correct, but effective permissions may lag.
- Auditing only permission sets. Profiles can also grant access, so a complete audit covers both.
Exercise
You write an Apex trigger that creates an Account and, in the same transaction, assigns a permission set to its new owner. The code fails with MIXEDDMLOPERATION. Why, and how do you fix it?
Show answer
PermissionSetAssignment is a setup object, and Salesforce does not allow DML on setup objects and standard or custom objects in the same transaction. Move the assignment into a separate transaction, for example a Queueable or @future method called from the trigger.
Exercise
Write a SOQL query that lists every user who holds the permission set named Account_Viewer, without counting profile-owned permission sets.
Show answer
SELECT Assignee.Name FROM PermissionSetAssignment WHERE PermissionSet.Name = 'Account_Viewer' AND PermissionSet.IsOwnedByProfile = false