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

前端 未结 18 1661
梦毁少年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: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();
    }
    

提交回复
热议问题