【问题标题】:Spring security different roles DTAPSpring Security 不同角色 DTAP
【发布时间】:2014-10-19 11:41:05
【问题描述】:

我们目前在我们的环境中拥有不同的角色,例如在开发中我们有称为USRADM的角色,而在生产中它们使用全名,例如USERADMINADMINISTRATOR

我解决这个问题的想法是使用属性文件和角色名的占位符,例如,这是我的属性文件:

role.user='USER'
role.admin='ADMIN', 'ADMINISTRATOR'

在我的AppConfig 中,我在类的顶部添加了以下注释:

@PropertySource("classpath:roles.properties")
public class AppConfig {

}

在我的服务中,我现在正在使用:

@PreAuthorize("hasAnyRole(${role.admin})")
public Item deleteItem(int id) {

}

但是,这会导致以下异常:

Caused by: org.springframework.expression.spel.SpelParseException: EL1043E:(pos 12): Unexpected token.  Expected 'rparen())' but was 'lcurly({)'

因为它说它没有扩展花括号,所以我还尝试了以下操作:@PreAuthorize("hasAnyRole(role.admin)") 导致:

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 11): Property or field 'role' cannot be found on object of type 'org.springframework.security.access.expression.method.MethodSecurityExpressionRoot' - maybe not public?

至少表达式本身现在看起来有效,但它似乎不是在查看属性文件,而是查看特定类的属性。

有没有人想办法解决这个问题?还是有另一种/更好的解决环境特定角色的解决方案?

【问题讨论】:

  • 我会在阅读角色名称时立即翻译它们。或者,您也可以使用角色层次结构。
  • 顺便说一句。 ${} 是属性占位符的格式。对于 SpEL,您可能想尝试environment['role.admin']
  • environment['role.admin] 也不起作用,它给出了相同的异常(它在MethodSecurityExpressionRoot 中寻找environment。稍后我会尝试其他选项(需要更多时间来实现)。

标签: spring spring-security spring-el


【解决方案1】:

@PreAuthorize 中使用的 Spring EL 只有:

  • 访问 SecurityExpressionRoot 的方法和属性。

  • 访问方法参数(需要使用调试信息或自定义 ParameterNameDiscoverer 进行编译):

看到这个答案https://stackoverflow.com/a/3786581/883859

您可以通过@ 访问其他bean 所以

 public interface RoleNameGetter {
    String getSuperUserRole();
    ...
 }

 @Configuration
 @PropertySource("classpath:xyz.properties")
 @EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
 public class Configuration {
    @Autowired
    protected Environment env;

    @Bean
    RoleNameGetter roleNameGetter() {
      return new RoleNameGetter() {
        @Override
        public String getSuperUserRole() {
            return env.getProperty("superuser_role_name");
        }
    };
}

允许从 @PreAuthorize 中使用的 Spring EL 中的属性文件访问角色名称,如下所示:

  @PreAuthorize("hasAnyAuthority(@roleNameGetter.getSuperUserRole(),@roleNameGetter.getNormalUserRole())")
  public void end() {...}

【讨论】:

    猜你喜欢
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 2015-07-29
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多