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

Piotr Gwiazda picture Piotr Gwiazda · Jun 11, 2010 · Viewed 174.1k times · Source

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"));
}

Answer

gouki picture gouki · Jun 23, 2010

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
    }
}