如何正确使用isUserInRole(角色) [英] How to properly use isUserInRole(role)

查看:87
本文介绍了如何正确使用isUserInRole(角色)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

防止用户角色执行操作。

To prevent a user role from performing an action.


  1. 示例1:角色administrator
    是唯一允许执行
    销毁操作的角色。

  2. 示例2:任何与guest不同的角色都可以执行CREATE操作。

真实case,我有这个:

In a real case, I have this:

public String delete() {
 if(FacesContext.getCurrentInstance().getExternalContext().isUserInRole("administrator"){
   //.....the action to perform
 }
 return "Denied";
}

我希望我可以使用EJB的注释 @RolesAllowed()我没有使用EJB而是使用ManagedBeans。
所以问题是:有没有办法同时使用多个角色?一些解决方法!
示例:如果必须允许一个操作为3个角色(管理员,主持人,经理)。我有义务这样做:

I wish I could use the annotation @RolesAllowed() of EJB yet I am not using EJB but ManagedBeans. So the question is: Is there any way to use many roles at the same time? Some workaround! Example: If an action must be allowed to 3 roles (administrator, moderator, manager). I am obliged to do :

if (FacesContext.getCurrentInstance().getExternalContext().isUserInRole("administrator")
    || FacesContext.getCurrentInstance().getExternalContext().isUserInRole("manager") 
    || .....) {
  //....
}

重现所有方法都很痛苦。像数百种方法:(

And it is a pain to reproduce on all the methods. Something like hundreds of methods :(

推荐答案

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

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

这篇关于如何正确使用isUserInRole(角色)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆