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

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

    The answer from JoseK can't be used when your in your service layer, where you don't want to introduce a coupling with the web layer from the reference to the HTTP request. If you're looking into resolving the roles while in the service layer, Gopi's answer is the way to go.

    However, it's a bit long winded. The authorities can be accessed right from the Authentication. Hence, if you can assume that you have a user logged in, the following does it:

    /**
     * @return true if the user has one of the specified roles.
     */
    protected boolean hasRole(String[] roles) {
        boolean result = false;
        for (GrantedAuthority authority : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
            String userRole = authority.getAuthority();
            for (String role : roles) {
                if (role.equals(userRole)) {
                    result = true;
                    break;
                }
            }
    
            if (result) {
                break;
            }
        }
    
        return result;
    }
    

提交回复
热议问题