【问题标题】:Is there any way to mix spring-security java configuration and @secured annotation?有没有办法混合spring-security java配置和@secured注解?
【发布时间】:2019-04-10 05:50:35
【问题描述】:

我为 Web 应用设置了 Spring Security。我想制定全局安全规则(在 GET 上允许所有经过身份验证的用户,并且只允许在其他 http 方法上使用角色 ADMIN)并使用 @Secured 注释向端点添加自定义规则。

当我像那个只有角色 SUPER_USER 的用户一样配置和 @Secured 注释时,无法访问该端点

override def configure(http: HttpSecurity): Unit = {
    http
      .sessionManagement()
      .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
      .and()
      .authorizeRequests()
      .antMatchers(HttpMethod.GET, ALL)
      .permitAll()
      .and()
      .authorizeRequests()
      .antMatchers(ALL).hasRole("ADMIN")
  }
@DeleteMapping(value = Array("/{id}"))
@Secured(Array("SUPER_USER"))
def delete(@PathVariable("id") id: String): Unit = {...}

我希望有@Secured 的全局安全规则和自定义规则。有什么办法吗?

【问题讨论】:

  • 它们是互补的。所以现在用户必须在他的权限列表中同时拥有ROLE_ADMINROLE_SUPER_USER。如果其中一个丢失,他将无法访问。如果这不起作用,请将 @EnableGlobalMethodSecurity 注释添加到您的安全配置中。另一种选择是使用角色层次结构,这意味着SUPER_USER 将扩展ADMIN
  • 是否有任何选项可以检查用户是否有 ROLE_ADMIN 表单 java config 或 ROLE_SUPER_USER 表单 Secured annotation?
  • 没有。如前所述,它们是互补的。安全过滤器首先检查配置中定义的规则,然后检查@Secured / @PreAuthorize 检查。
  • 只是为了重新执行来自@M.Deinum 的评论,您可以查看spring.io

标签: java spring scala spring-security spring-annotations


【解决方案1】:

您可以使用@PreAuthorize。它会解决你的问题。

@PreAuthorize("hasRole('" + <Your Role> + "')")

【讨论】:

  • 这行不通。看起来像请求匹配 .antMatchers(ALL).hasRole("ADMIN"),检查用户是否没有角色 admin,返回 AccessDenied 并且不检查他是否有角色 SUPER_USER 表单注释 \@Secured 或 \@PreAuthorize
  • 如果@Secured 不起作用,@PreAuthorize 也不起作用。
猜你喜欢
  • 1970-01-01
  • 2014-03-09
  • 2017-01-27
  • 1970-01-01
  • 2017-05-22
  • 2016-07-18
  • 2016-08-11
  • 1970-01-01
  • 2015-05-30
相关资源
最近更新 更多