How to check “hasRole” in Java Code with Spring Security?

前端 未结 18 1649
梦毁少年i
梦毁少年i 2020-11-28 20:54

How to check user authority or permission in Java Code ? For example - I want to show or hide button for user depending on role. There are annotations like:

         


        
18条回答
  •  青春惊慌失措
    2020-11-28 21:12

    Most answers are missing some points:

    1. Role and authority are not the same thing in Spring. See here for more details.

    2. Role names are equal to rolePrefix + authority.

    3. The default role prefix is ROLE_, however, it is configurable. See here.

    Therefore, a proper role check needs to respect the role prefix if it is configured.

    Unfortunately, the role prefix customization in Spring is a bit hacky, in many places the default prefix, ROLE_ is hardcoded, but in addition to that, a bean of type GrantedAuthorityDefaults is checked in the Spring context, and if it exists, the custom role prefix it has is respected.

    Bringing all this information together, a better role checker implementation would be something like:

    @Component
    public class RoleChecker {
    
        @Autowired(required = false)
        private GrantedAuthorityDefaults grantedAuthorityDefaults;
    
        public boolean hasRole(String role) {
            String rolePrefix = grantedAuthorityDefaults != null ? grantedAuthorityDefaults.getRolePrefix() : "ROLE_";
            return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
                    .map(Authentication::getAuthorities)
                    .map(Collection::stream)
                    .orElse(Stream.empty())
                    .map(GrantedAuthority::getAuthority)
                    .map(authority -> rolePrefix + authority)
                    .anyMatch(role::equals);
        }
    }
    

提交回复
热议问题