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

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

    You can get some help from AuthorityUtils class. Checking role as a one-liner:

    if (AuthorityUtils.authorityListToSet(SecurityContextHolder.getContext().getAuthentication().getAuthorities()).contains("ROLE_MANAGER")) {
        /* ... */
    }
    

    Caveat: This does not check role hierarchy, if such exists.

提交回复
热议问题