有没有一种方法可以在Spring安全MVC应用程序的属性文件中配置角色



我有一个spring安全MVC应用程序。在一些JSP文件中,我有如下代码:

<sec:authorize access="hasAnyRole('ROLE_FOO', 'ROLE_BAR')">
  <!--do something here-->  
</sec:authorize>

在将应用程序部署到生产环境时,我必须更改代码(将ROLE_FOO更改为其他内容(,因为它有不同的角色名称。因此,我想知道是否有一种方法可以在属性文件中配置这些角色名称,然后在<sec:authorize>标记中选择这些名称。

所以代码看起来像这样:

属性文件:

Admin_Roles = ROLE_FOO ROLE_BAR

和JSP

<sec:authorize access="hasAnyRole(<get roles from Admin_Roles in prop file>)">
  <!--do something here-->  
</sec:authorize>

顺便说一句,我使用Active Directory进行身份验证,所以这些角色在Active Directory中预先配置,用于测试和生产。

不确定这是最简单的方法。但是你可以自己写表达。

这个链接应该非常有用。链路

因为每个版本之间都有一些差异。您最好查看DefaultWebSecurityExpressionHandler的源代码,以确保在覆盖createSecurityExpressionRoot 时不会遗漏任何内容

不确定如何为可变数量的角色执行此操作,但对于固定数量的角色,您尝试过这样的操作吗?

JSP:

<sec:authorize access="hasAnyRole('${adminRole1}', '${adminRole2}')">
  <!--do something here-->  
</sec:authorize>

控制器:

@Value("#{myprops.admin_role_1}"}
private String adminRole1;
@Value("#{myprops.admin_role_2}"}
private String adminRole2;
...
@RequestMapping("/hello")
public String hello(final Model model) {
  model.addAttribute("adminRole1", adminRole1);
  model.addAttribute("adminRole2", adminRole2);
  ...
} 

和配置XML:

<bean id="myprops"
  class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <!-- External property files -->
      <value>file:${somepathvar}/adminroles.properties</value>
    </list>
  </property>
</bean>

最新更新