小编典典

预授权在控制器上不起作用

spring

正在尝试在方法级别定义访问规则,但是它从未如此有效。

安全配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().
                withUser("user").password("user").roles("USER").and().
                withUser("admin").password("admin").roles("ADMIN");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/v2/**").authenticated()
                .and()
                .httpBasic()
                .realmName("Secure api")
                .and()
                .csrf()
                .disable();
    }
}

ExampleController

@EnableAutoConfiguration
@RestController
@RequestMapping({"/v2/"})
public class ExampleController {
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @RequestMapping(value = "/home", method = RequestMethod.GET)
    String home() {
        return "Hello World";
    }
}

每当我尝试使用user:user它访问/ v2 / home时,它执行得很好,是否由于“用户”没有访问权限而给我“拒绝访问”错误ROLE_ADMIN?

我实际上是在考虑在方法级别放弃访问规则并坚持使用http()ant规则,但是我必须知道为什么它对我不起作用。


阅读 429

收藏
2020-04-20

共2个答案

小编典典

在控制器上使用PrePost注释的一个常见问题是Spring方法的安全性基于Spring AOP,默认情况下,该方法是使用JDK代理实现的。

这意味着它在作为接口注入到控制器层中的服务层上可以正常工作,但是在控制器层上它会被忽略,因为控制器通常不实现接口。

以下是我的看法:

  • 首选方式:在服务层上移动post post注释
  • 如果你不能(或不想),请尝试让你的控制器实现包含所有带注释方法的接口
  • 作为最后一种方法,请使用proxy-target-class = true
2020-04-20
小编典典

你必须添加@EnableGlobalMethodSecurity(prePostEnabled = true)WebSecurityConfig。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
2020-04-20