Blog

Understanding Spring Security – Part 5 – Custom Permission Evaluator and Permissions

by | Sep 24, 2024 | Content Security, Webapps | 0 comments

In this portion of the Understanding Spring Security blog series, we will demonstrate the code for setting up the Custom Permission Evaluator and Permissions.

Code to create a custom permission evaluator:
security.xml

Service Interface

 @PostFilter("hasPermission(filterObject, 'READ')")
 public List getAll();
Custom Permissions Evaluator
@Override
 public boolean hasPermission(Authentication authorities,
 Object targetDomainObject, Object permission) {
boolean Decision = false;
 System.out.println("Initial Decision: " + Decision);
Date cutoffDate = null;
 try {
 cutoffDate = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH)
 .parse("January 1, 2012");
 System.out.println("Cutoff Date: " + cutoffDate.toString());
 } catch (ParseException e) {
 e.printStackTrace();
 }
System.out.println("Domain Object Date: "
 + Post.class.cast(targetDomainObject).getDate());
if (Post.class.cast(targetDomainObject).getDate().before(cutoffDate)) {
 Decision = false;
 System.out.println("In before");
 } else {
 Decision = true;
 System.out.println("In after");
 }
 System.out.println("Final Decision: " + Decision);
 System.out.println("--------");
 return Decision;
 }

How to create custom permission

Security.xml:

Custom Permission class:

public class myPermission extends BasePermission {

public static final Permission CUSTOMX = new myPermission (1 << 5,
'X');
public static final Permission CUSTOMY = new myPermission (1 << 6, 'Y');

protected myPermission (int mask) {
super(mask);
}

protected myPermission (int mask, char code) {
super(mask, code);
}
}

Custom Factory Class to register the new permissions:

public class myPermissionFactory extends DefaultPermissionFactory {
public myPermissionFactory() {
super();
registerPublicPermissions(myPermission.class);
}
}

The method annotation:

@PreAuthorize("hasPermission(#user,'customx')")
public void myMethod(User user) {
...
}

Categories

Need a bit more info on how Armedia can help you?

Feel free to schedule a 30-minute no-obligations meeting.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *