【问题标题】:Is there a way to configure Roles in a property file for Spring security MVC app有没有办法在 Spring 安全 MVC 应用程序的属性文件中配置角色
【发布时间】:2013-02-27 11:40:27
【问题描述】:

我有一个 Spring Security MVC 应用程序。在几个 JSP 文件中,我的代码如下所示:

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

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

所以代码看起来像这样:

属性文件:

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 中预先配置用于测试和生产。

【问题讨论】:

    标签: java spring spring-mvc spring-security


    【解决方案1】:

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

    这个链接应该很有用。 link

    由于每个版本之间存在一些差异。你最好看看DefaultWebSecurityExpressionHandler的源代码,确保你在覆盖createSecurityExpressionRoot时不会遗漏任何东西

    【讨论】:

      【解决方案2】:

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

      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>
      

      【讨论】:

      • 这可能会起作用,因为我只有固定数量的角色。但是,我也在 app-servlet.xml 中使用角色作为 &lt;intercept url&gt; 的一部分。我如何通过那里的属性访问角色?
      • 例如通过自定义网络安全表达式,请参阅@Willy 回答
      猜你喜欢
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 2015-04-09
      • 1970-01-01
      • 2016-06-07
      • 2021-06-18
      • 2019-01-02
      • 1970-01-01
      相关资源
      最近更新 更多