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

前端 未结 18 1541
梦毁少年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 20:58

    Spring Security 3.0 has this API

    SecurityContextHolderAwareRequestWrapper.isUserInRole(String role)
    

    You'll have to inject the wrapper, before you use it.

    SecurityContextHolderAwareRequestWrapper

    0 讨论(0)
  • 2020-11-28 21:00

    you can use the isUserInRole method of the HttpServletRequest object.

    something like:

    public String createForm(HttpSession session, HttpServletRequest request,  ModelMap   modelMap) {
    
    
        if (request.isUserInRole("ROLE_ADMIN")) {
            // code here
        }
    }
    
    0 讨论(0)
  • 2020-11-28 21:01

    On your user model just add a 'hasRole' method like below

    public boolean hasRole(String auth) {
        for (Role role : roles) {
            if (role.getName().equals(auth)) { return true; }
        }
        return false;
    }
    

    I usually use it to check if the authenticated user has the role admin as follows

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // This gets the authentication
    User authUser = (User) authentication.getPrincipal(); // This gets the logged in user
    authUser.hasRole("ROLE_ADMIN") // This returns true or false
    
    0 讨论(0)
  • 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<GrantedAuthority> 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<GrantedAuthority> authorities, String role) {
        boolean isRolePresent = false;
        for (GrantedAuthority grantedAuthority : authorities) {
          isRolePresent = grantedAuthority.getAuthority().equals(role);
          if (isRolePresent) break;
        }
        return isRolePresent;
      }
    
    0 讨论(0)
  • 2020-11-28 21:05

    Better late then never, let me put in my 2 cents worth.

    In JSF world, within my managed bean, I did the following:

    
    HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
    SecurityContextHolderAwareRequestWrapper sc = new SecurityContextHolderAwareRequestWrapper(req, "");
    

    As mentioned above, my understanding is that it can be done the long winded way as followed:

    
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserDetails userDetails = null;
    if (principal instanceof UserDetails) {
        userDetails = (UserDetails) principal;
        Collection  authorities = userDetails.getAuthorities();
    }
    
    0 讨论(0)
  • 2020-11-28 21:05

    The @gouki answer is best!

    Just a tip of how spring really do this.

    There is a class named SecurityContextHolderAwareRequestWrapper which implements the ServletRequestWrapper class.

    The SecurityContextHolderAwareRequestWrapper overrides the isUserInRole and search user Authentication (which is managed by Spring) to find if user has a role or not.

    SecurityContextHolderAwareRequestWrapper the code is as:

        @Override
        public boolean isUserInRole(String role) {
            return isGranted(role);
        }
    
     private boolean isGranted(String role) {
            Authentication auth = getAuthentication();
    
            if( rolePrefix != null ) {
                role = rolePrefix + role;
            }
    
            if ((auth == null) || (auth.getPrincipal() == null)) {
                return false;
            }
    
            Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
    
            if (authorities == null) {
                return false;
            }
    
            //This is the loop which do actual search
            for (GrantedAuthority grantedAuthority : authorities) {
                if (role.equals(grantedAuthority.getAuthority())) {
                    return true;
                }
            }
    
            return false;
        }
    
    0 讨论(0)
提交回复
热议问题