My question is a duplicate of Custom annotation with spring security but it went unanswered and I believe there should be a simple solution to the problem.
Basically ins
Facing the same issue, I ended up with a hybrid solution. I am using Spring-El and a custom bean to provide my own hasPermission()
method which accepts an Enum. Given that Spring does an automatic string->enum
conversion, at runtime, I will get a runtime exception that a particular enum does not exist if there is a typo in the string. Not the ideal solution (would have rather had something that failed at compile-time), but an acceptable compromise. It gives me some semi-type safety.
@Component("securityService")
public class SecurityService {
public boolean hasPermission( Permission...permissions){
// loop over each submitted role and validate the user has at least one
Collection extends GrantedAuthority> userAuthorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
for( Permission permission : permissions){
if( userAuthorities.contains( new SimpleGrantedAuthority(permission.name())))
return true;
}
// no matching role found
return false;
}
}
Used as follows:
@PreAuthorize("@securityService.hasPermission({'USER_ADD'})")
public User addUser(User user){
// create the user
return userRepository.save( user );
}
Where Permission is just a normal enum definition:
public enum Permission {
USER_LIST,
USER_EDIT,
USER_ADD,
USER_ROLE_EDIT
}
Hope this can help someone else out in the future.