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

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

    My Approach with the help of Java8 , Passing coma separated roles will give you true or false

        public static Boolean hasAnyPermission(String permissions){
        Boolean result = false;
        if(permissions != null && !permissions.isEmpty()){
            String[] rolesArray = permissions.split(",");
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            for (String role : rolesArray) {
                boolean hasUserRole = authentication.getAuthorities().stream().anyMatch(r -> r.getAuthority().equals(role));
                if (hasUserRole) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }
    

提交回复
热议问题