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

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

    You can implement a hasRole() method as below - (This is tested on spring security 3.0.x not sure about other versions.)

      protected final boolean hasRole(String role) {
        boolean hasRole = false;
        UserDetails userDetails = getUserDetails();
        if (userDetails != null) {
          Collection authorities = userDetails.getAuthorities();
          if (isRolePresent(authorities, role)) {
            hasRole = true;
          }
        } 
        return hasRole;
      }
      /**
       * Get info about currently logged in user
       * @return UserDetails if found in the context, null otherwise
       */
      protected UserDetails getUserDetails() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserDetails userDetails = null;
        if (principal instanceof UserDetails) {
          userDetails = (UserDetails) principal;
        }
        return userDetails;
      }
      /**
       * Check if a role is present in the authorities of current user
       * @param authorities all authorities assigned to current user
       * @param role required authority
       * @return true if role is present in list of authorities assigned to current user, false otherwise
       */
      private boolean isRolePresent(Collection authorities, String role) {
        boolean isRolePresent = false;
        for (GrantedAuthority grantedAuthority : authorities) {
          isRolePresent = grantedAuthority.getAuthority().equals(role);
          if (isRolePresent) break;
        }
        return isRolePresent;
      }
    

提交回复
热议问题