Reputation: 81
I'm making a system for asset management.there three categories of user in the system, the Administrator, Subadmin, and limited user.Administrator can do anything, Subadmin only served to verify the data and the limited user can only see just finished data / View Data
in the database, access rights characterized by number.Administrator = 0, SubAdmin = 1, and a limited user = 2.
to enter the system, each user must login, at the time of login, access rights saved into session. the problem, how do I check the session in servlet file (. xhtml)? for example there is data in the DataTable. there is menu "edit", "delete", and "Verify". if admin is logged on, then the menu "edit, delete" will appear in the table row, if SubAdmin logged on, then just appearing menu "verify ", and if the limited user is logged on, the menu does not appear.
Should I check servletnya session at the file, or is there another way? how ?
Thanks much..
Upvotes: 0
Views: 2745
Reputation: 3671
When used Spring Security in a web application, your problem is easily solved with the help of special tag:
<sec:authorize ifAllGranted="ADMINISTRATOR">
<h:commandButton value="edit" />
<h:commandButton value="delete" />
</sec:authorize>
<sec:authorize ifNotGranted="SUBADMIN">
<h:commandButton value="verify" />
</sec:authorize>
To do this just add in the namespace of your page:
xmlns:sec="http://www.springframework.org/security/tags"
And connect this library to your project.
You can also learn other helpful benefits of Spring Security which you can use.
Upvotes: 0
Reputation: 1108722
First of all, a XHTML file is not a Servlet file. It's a Facelets file. Facelets is a XML based view technology.
As to your concrete question, just determine it in the JSF component's rendered
attribute. If the boolean condition evaluates false
, then JSF simply won't render the component (and also not process it upon submit, so you're also safe against tampered requests).
Assuming that the logged-in user is as an User
javabean available in EL scope as #{user}
, and has a hasRole()
method taking a String
and returning a boolean
, then you could do so:
<h:commandButton value="delete" rendered="#{user.hasRole('admin')}" />
There are variations, like having just an isAdmin()
method returning boolean
:
<h:commandButton value="delete" rendered="#{user.admin}" />
Or having a getRoles()
method returning a Collection
:
<h:commandButton value="delete" rendered="#{user.roles.contains('admin')}" />
You could if necessary also use an integer 0
instead of string admin
, but that's less self-documenting.
Do however note that you're basically homegrowing authorization. You could also consider using Java EE builtin container managed authentication and authorization. You could then use HttpServletRequest#isUserInRole()
to authorize users. It's much like the User#hasRole()
suggestion:
<h:commandButton value="delete" rendered="#{request.isUserInRole('admin')}" />
Upvotes: 1