PreAuthorize 不适用于控制器 [英] PreAuthorize not working on Controller
问题描述
我正在尝试在方法级别定义访问规则,但它不起作用.
I'm trying to define access rules at method-level but it's not working what so ever.
安全配置
@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();
}
}
示例控制器
@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<而给我一个访问被拒绝的错误/代码>?
Whenever I try to access /v2/home using user:user
it executes just fine, shouldn't it give me an Access Denied error due to 'user' not having ROLE_ADMIN
?
我实际上正在考虑在方法级别放弃访问规则并坚持 http() 蚂蚁规则,但我必须知道为什么它对我不起作用.
I'm actually thinking of ditching access rules at method-level and stick to http() ant rules, but I have to know why it's not working for me.
推荐答案
在控制器上使用 PrePost 注解的一个常见问题是 Spring 方法安全性基于 Spring AOP,默认情况下使用 JDK 代理实现.
A common problem with using PrePost annotations on controllers is that Spring method security is based on Spring AOP, which is by default implemented with JDK proxies.
这意味着它在作为接口注入控制器层的服务层上工作正常,但在控制器层被忽略,因为控制器通常不实现接口.
That means that it works fine on the service layer which is injected in controller layer as interfaces, but it is ignored on controller layer because controller generally do not implement interfaces.
以下只是我的看法:
- 首选方式:在服务层移动pre post注解
- 如果您不能(或不想),请尝试让您的控制器实现一个包含所有带注释方法的接口
- 作为最后一种方法,使用 proxy-target-class=true
这篇关于PreAuthorize 不适用于控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!