javaspringspring-securityspring-elspring-4

Spring security 3.2 - @PostAuthorize expressions to evaluate principal against the method's returned object


I use spring security to secure and evaluate expression in @PostAuthorize and @PreAuthorize annotations to authorize the service methods. I have a requirement that need to check if the returned object has the same userid who has logged in the system and is invoking this method.

// this allows the ids of other users too
@PostAuthorize("#returnObject!=null?returnObject.userId==principal.account.acid:true")
public AudioClip findAudioClip(int clipId) {
     .....
     AudioClip clip = dao.findById(clipId);
     // may also be null
     return clip;
}

AudioClip.java

@Component
public class AudioClip implements java.io.Serializable {

private java.math.BigDecimal id;
private java.lang.Integer    userId;
.....
}

The fetched object from the database contains the userId who created this db object. So, only he is eligible to access that component. How to compare the returnObject.userId with the userid who has logged-in to the system?


Solution

  • @holmis, as you had pointed, the culprit is the # in the code! this code

    @PostAuthorize("returnObject!=null?returnObject.userId==principal.account.aid:true")
    

    works!