Spring Security + JSF ROLE conversion of page components (link, etc.)

Use JSF + Spring Security.

Solution 1 - User Interface Oriented:
JSF page displays a panel with users if the registered person has only ROLE_ADMIN .

 <p:panel rendered="#{facesContext.externalContext.isUserInRole('ROLE_ADMIN')}"> ... 

Solution 2 - backend-oriented (annotate the corresponding DAO method):

 @Transactional @PreAuthorize("hasRole('ROLE_ADMIN')") public List<User> getUsers() { return sessionFactory.getCurrentSession().createCriteria(User.class) .list(); } 

Summary:
It seems that the JSF rendered attribute is not a flexible solution, and the annotated DAO methods are not user friendly due to redirection to 403 .

What is an elegant solution that allows me NOT to display a panel or link that does not correspond to specific permissions?

+4
source share
2 answers

You do not want to show enduser panels or any functions that the end user cannot see / use in any way. This will only lead to general confusion and disappointment. So checking the role in the rendered attribute is the way to go.

The expression can be simplified only in this form:

 <p:panel rendered="#{request.isUserInRole('ROLE_ADMIN')}"> 

ExternalContext#isUserInRole() delegates HttpServletRequest#isUserInRole() , but the HttpServletRequest itself is also present in the EL area as #{request} .

+9
source

Spring Security, depending on how it is configured, will return 403 or redirect if the user does not have access to a specific resource.

Solution 1 is an appropriate way to do what you are trying to achieve, but you are essentially creating a dependency between FacesContext and your view, which in my opinion is bad practice. A better solution would be to encapsulate this authorization logic into a managed bean property. The advantage of this is that your presentation no longer depends on your authorization implementation, and your managed bean now appropriately contains this dependency.

+1
source

Source: https://habr.com/ru/post/1402667/


All Articles