正在尝试在方法级别定义访问规则,但是它从未如此有效。
安全配置
@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规则,但是我必须知道为什么它对我不起作用。
在控制器上使用PrePost注释的一个常见问题是Spring方法的安全性基于Spring AOP,默认情况下,该方法是使用JDK代理实现的。
这意味着它在作为接口注入到控制器层中的服务层上可以正常工作,但是在控制器层上它会被忽略,因为控制器通常不实现接口。
以下是我的看法:
你必须添加@EnableGlobalMethodSecurity(prePostEnabled = true)WebSecurityConfig。
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter {