javaspring-securityuser-roles

How to check "hasRole" in Java Code with Spring Security?


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:

@PreAuthorize("hasRole('ROLE_USER')")

How to make it in Java code? Something like :

if(somethingHere.hasRole("ROLE_MANAGER")) {
   layout.addComponent(new Button("Edit users"));
}

Solution

  • Spring Security 3.0 has this API

    SecurityContextHolderAwareRequestWrapper.isUserInRole(String role)
    

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

    SecurityContextHolderAwareRequestWrapper