SpringBoot 获取 HttpSecurity 配置 authorizeHttpRequests 中放行的所有 URL 和 Method
可以使用 SpringBoot 提供的 HttpSecurity 配置对象来获取所有放行的 URL 和 HTTP 方法。可以通过以下步骤来实现:
- 在 SpringBoot 应用程序的配置类中,注入 HttpSecurity 对象,例如:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 配置 HttpSecurity 对象
}
@Autowired
private HttpSecurity http;
}
- 在上面的配置类中,添加一个方法来获取所有放行的 URL 和 HTTP 方法,例如:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// 配置 HttpSecurity 对象
}
@Autowired
private HttpSecurity http;
@Bean
public List<String> getAllowedUrls() throws Exception {
List<String> allowedUrls = new ArrayList<>();
http.authorizeRequests()
.antMatchers('/**').permitAll()
.and()
.formLogin();
for (HttpSecurityBuilder.RequestMatcherConfigurer<?> configurer : http.getConfigurers()) {
if (configurer instanceof HttpSecurityBuilder.RequestMatcherRegistry) {
HttpSecurityBuilder.RequestMatcherRegistry registry = (HttpSecurityBuilder.RequestMatcherRegistry) configurer;
List<HttpSecurityBuilder<?>> builders = registry.builders();
for (HttpSecurityBuilder<?> builder : builders) {
if (builder instanceof HttpSecurity.AuthorizeRequestsBuilder) {
HttpSecurity.AuthorizeRequestsBuilder authorizeRequestsBuilder = (HttpSecurity.AuthorizeRequestsBuilder) builder;
List<ConfigAttribute> configAttributes = authorizeRequestsBuilder.getConfigAttributes();
for (ConfigAttribute configAttribute : configAttributes) {
if (configAttribute instanceof org.springframework.security.access.SecurityConfig) {
org.springframework.security.access.SecurityConfig securityConfig = (org.springframework.security.access.SecurityConfig) configAttribute;
allowedUrls.add(securityConfig.getAttribute());
}
}
}
}
}
}
return allowedUrls;
}
}
-
在上面的方法中,首先添加了一些放行所有 URL 的配置,然后获取了所有的 HttpSecurity 配置器,通过遍历配置器来获取所有的放行 URL。
-
最后,可以在其他类中注入上面的方法,获取所有放行 URL 和 HTTP 方法,例如:
@RestController
public class MyController {
@Autowired
private SecurityConfig securityConfig;
@GetMapping("/allowedUrls")
public List<String> getAllowedUrls() throws Exception {
return securityConfig.getAllowedUrls();
}
}
通过上面的步骤,就可以获取到所有放行的 URL 和 HTTP 方法。
原文地址: https://www.cveoy.top/t/topic/nbit 著作权归作者所有。请勿转载和采集!