java - 如果我在给定端点上全局允许所有请求,如何禁用在方法级别设置的@PreAuthorize 注释?
问题描述
我有这个安全配置:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
// @formatter:off
@Override
public void configure(final HttpSecurity http) throws Exception {
http.headers().frameOptions().disable()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/test/**").authenticated()
.antMatchers("/**").permitAll()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
而这个控制器:
@RestController
public class MyController {
@GetMapping("")
@PreAuthorize("hasRole('ROLE_USER')")
public String hello() {
return "Hello world!";
}
@GetMapping("/api/test")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String helloTest(Principal principal) {
System.out.println(principal.toString());
return "Hello test world!";
}
}
两种控制器方法都有@PreAuthorize
注释。在安全配置中,我要求/api/test/**
端点是安全的,而其余的应该是匿名的。
但是,当我测试给定的控制器时,由于注释而打开时,http://localhost:8080
我希望它不安全()。401 Unauthorized
@PreAuthorize("hasRole('ROLE_USER')")
.antMatchers("/**").permitAll()
TL:DR - 我希望“全局”配置覆盖@PreAuthorize()
注释。
为什么?因为我想设置文件中的.antMatchers("/api/test/**").authenticated()
部分,application.properties
所以如果我将值更改为“/api/test/hello/**”,那么我希望该helloTest
方法可供匿名用户使用,而无需通过所有控制器并删除到处都是@PreAuthorize()
注释,希望我能找到这一切。提前致谢。