10.2. Checking permissions for the current user
The primary method for accessing the Permissions API is via the
Identity
bean, which provides the following two methods for checking permissions for the currently authenticated user:
boolean hasPermission(Object resource, String operation); boolean hasPermission(Class<?> resourceClass, Serializable identifier, String operation);
The first overloaded method may be used when you have a reference to the actual resource for which you wish to check privileges:
@Inject Identity identity; public void deleteAccount(Account account) { // Check the current user has permission to delete the account if (identity.hasPermission(account, "DELETE")) { // Logic to delete Account object goes here } else { throw new SecurityException("Insufficient privileges!"); } }
The second overloaded method may be used when you don't have a reference to the resource object, but you have it's identifier value (for example the primary key value of an entity bean):
@Inject Identity identity; public void deleteCustomer(Long customerId) { // Check the current user has permission to delete the customer if (identity.hasPermission(Customer.class, customerId, "DELETE")) { // Logic to delete Customer object goes here } else { throw new SecurityException("Insufficient privileges!"); } }
This method is generally used for performance reasons, for example when you don't necessarily wish to load a resource object because of a possibly expensive instantiation cost, or you wish to check whether there are suitable permissions assigned to the user before loading the resource.