【问题标题】:Spring Security @PreAuthorize on controllers控制器上的 Spring Security @PreAuthorize
【发布时间】:2015-08-12 08:02:26
【问题描述】:

我正在尝试在某些控制器上使用与 @PreAuthorize("permitAll") 匹配的 url(基于蚂蚁),即

@Controller
@RequestMapping("/register")
public class RegistrationController {
...

  @PreAuthorize("permitAll")
  @RequestMapping(method = RequestMethod.GET)
  public String register() { ... }

安全配置:

@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()

我还尝试将 @EnableGlobalMethodSecurity 添加到我的 MVC 配置中:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MvcConfig extends WebMvcConfigurerAdapter { ... }

但这没有效果

但是,在点击 /register 时仍然提示我进行身份验证。如果我将“/register”添加到蚂蚁匹配器中,它可以工作,即 .antMatchers("/", "/register").permitAll()

我在这里缺少什么? @PreAuthorize 似乎对我的控制器没有影响

【问题讨论】:

  • 我应该澄清控制器上的 @PreAuthorize("hasRole('ADMIN')") 确实有效:非管理员会收到 403 错误。问题特别是如何使用 @PreAuthorize 注释覆盖蚂蚁匹配器

标签: spring-mvc spring-security


【解决方案1】:

您不能这样做,因为 ant matchers 和 @PreAuthorize 在不同级别工作。

ant 匹配器工作在 http 安全级别。 Spring安全过滤器查看请求,如果发现应该拒绝访问,它甚至不将请求传递给dispatcher servlet,直接发送403错误。

PreAuthorize方法级别工作。当一个方法即将被调用时,一个 AOP 代理控制是否应该允许访问。所以 2 个授权级别是链接的,而不是第二个覆盖第一个。

无论如何,我强烈建议您不要在控制器上使用@PreAuthorize("hasRole('ADMIN')")

  • 使用简单的蚂蚁匹配器即可轻松完成
  • 它强制您允许在控制器上进行代理,或者使用类代理而不是 JDK 代理,或者使用控制器接口

恕我直言,@PreAuthorize 最适合服务级别,因为您可以将域对象与用户授予的权限混合以获得细粒度的授权。

【讨论】:

  • Thanls Serge,我打算使用注释的原因是为了保持简单和可维护,目前我需要映射“/register”、“/register/”和“/register/ *" 在安全配置中,如果我更改请求映射,我也需要更改这些。
猜你喜欢
  • 2014-08-03
  • 1970-01-01
  • 2011-03-06
  • 1970-01-01
  • 1970-01-01
  • 2020-10-15
  • 2013-10-13
  • 2015-03-25
相关资源
最近更新 更多