且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何正确使用isUserInRole(角色)

更新时间:2023-02-26 08:57:59

这需要在视图方面进行控制。难道你不是自己找到的吗?当你在某个网站上看到一个你没有足够权利按下的按钮时会非常讨厌,因此当你这样做时会得到一个令人生畏的错误页面?

This needs to be controlled in the view side. Don't you find it by yourself very annoying when you see on some site a button for which you don't have sufficient rights to press and thus get an intimidating error page when you do so?

只是渲染只有当用户具有所需角色时,视图侧的按钮才会完全隐藏。

Just render the button in the view side only when the user has the required role, else hide it altogether.

<h:commandButton value="Delete" action="#{bean.delete}" 
    rendered="#{request.isUserInRole('administrator')}" />

这对(CSRF)黑客不敏感,因为JSF在申请请求值阶段再次检查条件。

This is not sensitive to (CSRF) hacks as JSF checks the condition once again during apply request values phase.

对于使用多个条件并在一个视图中反复重复相同的操作,请考虑使用< c:set> 给它一个简短的别名。你甚至可以将它放在某个主模板的顶部以便它可供所有子模板使用。

As to using multiple conditions and repeating the same over and over in a single view, consider using <c:set> to give it a short alias. You could even place it in the top of some master template so that it's available to all child templates.

<c:set var="isPowerUser" value="#{request.isUserInRole('manager') or request.isUserInRole('administrator')}" scope="request" />
...
<h:commandButton rendered="#{isPowerUser}" />
...
<h:commandButton rendered="#{isPowerUser}" />