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

前端 未结 18 1629
梦毁少年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:21

    In our project, we are using a role hierarchy, while most of the above answers only aim at checking for a specific role, i.e. would only check for the role given, but not for that role and up the hierarchy.

    A solution for this:

    @Component
    public class SpringRoleEvaluator {
    
    @Resource(name="roleHierarchy")
    private RoleHierarchy roleHierarchy;
    
    public boolean hasRole(String role) {
        UserDetails dt = AuthenticationUtils.getSessionUserDetails();
    
        for (GrantedAuthority auth: roleHierarchy.getReachableGrantedAuthorities(dt.getAuthorities())) {
            if (auth.toString().equals("ROLE_"+role)) {
                return true;
            }
        }
        return false;
    }
    

    RoleHierarchy is defined as a bean in spring-security.xml.

提交回复
热议问题