Usign JSF+Spring Security.
Solution 1 - UI oriented:JSF
page displays panel with users if authenticated person has ROLE_ADMIN
authority only.
<p:panel rendered="#{facesContext.externalContext.isUserInRole('ROLE_ADMIN')}">
...
Solution 2 - backend oriented (annotate appropriate DAO method):
@Transactional
@PreAuthorize("hasRole('ROLE_ADMIN')")
public List<User> getUsers() {
return sessionFactory.getCurrentSession().createCriteria(User.class)
.list();
}
Resume:
Looks like JSF rendered
attribute is not flexible solution and DAO annotated methods are not user-friendly,because of redirecting to 403
.
What is the gracefull solution,that allows me NOT to display panel or link,that are not corresponded to specific authorities?
You don't want to show the enduser panels or any kind of functionality which the enduser isn't allowed to see/use anyway. That would only result in general confusion and frustration. So role checking in the rendered
attribute is the way to go.
The expression can only be more simplified in this form:
<p:panel rendered="#{request.isUserInRole('ROLE_ADMIN')}">
The ExternalContext#isUserInRole()
delegates to HttpServletRequest#isUserInRole()
, but the HttpServletRequest
is by itself also present in EL scope as #{request}
.
Spring Security, depending on how it is configured will return 403 or redirect in the event that a user is not authorized to access a specific resource.
Solution 1 is the appropriate way to do what you are trying to achieve but you are essentially creating a dependency between FacesContext and your view which I think is bad practice. A better solution would be to encapsulate this authorization logic within a managed bean property. The benefit of doing this is that your view is no longer dependent on your authorization implementation, and your managed bean now appropriately contains that dependency.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With