In Spring 3, is there a method that accepts a comma-separated list of permissions and returns a Boolean of whether the logged in user has any of those permissions? I envision doing something like:
if(loggedInUserHasAnyOfThesePermissions("PERMISSION_READ,PERMISSION_EDIT")){
//do stuff
}
Currently, since don’t know of any such built-in method, I’m doing this:
Set<String> permissions = new HashSet();
for (GrantedAuthority auth : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
permissions.add(auth.getAuthority());
}
if (permissions.contains("PERMISSION_READ") || permissions.contains("PERMISSION_EDIT")) {
//do stuff
}
I’ve searched for hours and haven’t found a more concise and elegant way of doing this, but one must exist. Thanks for your help!
P.S. I’m already familiar with how to handle permissions in JSP like this: ( how to conditionally show jsp content to logged in users with Spring security ) But what I need now is a way to check within the controller.
I ended up coding my own class: MyUserDetails class has various methods including one that iterates over roles and permissions to see all the permissions that a user has, such as:
It’s pretty ugly, but I don’t have a better way yet.
I use it by doing something like: