Spring Security @PreAuthorization pass enums in directly

前端 未结 4 1497
清歌不尽
清歌不尽 2021-02-07 03:29

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

4条回答
  •  [愿得一人]
    2021-02-07 03:59

    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 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.

提交回复
热议问题