【发布时间】:2021-02-28 20:20:21
【问题描述】:
我有一个 Spring Boot 应用程序,其 Spring Security 配置如下:
@EnableWebSecurity
public class AppSecurityConfiguration {
@Configuration
@Order(Constants.DEVSTACK_SECURITY_ORDER - 1)
static class WebHttpSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* Configures Application WebSecurity which involves the full Security pipeline (?)
*
* @param web WebSecurity
*/
@Override
public void configure(WebSecurity web) {
web.ignoring()
// Allow requests to HealthCheck Endpoint without Bearer Token
.antMatchers("/api/healthCheck", "/v3/api-docs/**", "/configuration/**", "/swagger-ui.html",
"/swagger-ui/**", "/webjars/**", "/api/v1/browser/**", "/swagger-resources/**")
// Allow OPTIONS request without Bearer Token (for pre-flight requests)
.antMatchers(HttpMethod.OPTIONS, "/**");
}
/**
* Configures HttpSecurity
*
* @param http HttpSecurity
* @throws Exception if an error occurs
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//Authorize INSECURE request to this endpoint (so Swagger can pull the data)
.antMatcher("/v2/api-docs")
.authorizeRequests()
.anyRequest()
.permitAll();
}
}
}
在此 Configuration 类中,我忽略了某些通过 Spring Security 的端点,其中大部分用于 Swagger 文档,因此您可以忽略它。
我的问题在于 configure(HttpSecurity) 方法。我不知道为什么,但我写它的方式很有效。当我试图了解我刚刚配置的内容时,我是这样阅读的:
- 对“/v2/api-docs”的每个请求,授权请求
- 对于任何其他请求,请全部允许。
现在我想在 Spring Security 过滤器链中添加一个自定义过滤器。 这是过滤器类:
public class MyFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
log.debug("MyFilter");
filterChain.doFilter(servletRequest, servletResponse);
}
}
每当我尝试将过滤器添加到我的 HttpSecurity 时,我最终都会让 Spring Security 将我的 Principal 设置为“anonymousUser”。
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(new MyFilter(), WebAsyncManagerIntegrationFilter.class);
}
我尝试了很多不同的方法,例如:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(new MyFilter(), WebAsyncManagerIntegrationFilter.class)
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic()
.disable()
.formLogin()
.disable();
}
但当我尝试获取用户的 Principal 时,它仍然返回“anonymousUser”。
我不知道为什么要这样配置?!?!
@Override
protected void configure(HttpSecurity http) throws Exception {
http
//Authorize INSECURE request to this endpoint (so Swagger can pull the data)
.antMatcher("/v2/api-docs")
.authorizeRequests()
.anyRequest()
.permitAll();
}
有人可以像我五岁那样启发我并解释我吗?有时候我只是觉得自己太笨了,看不懂Spring
谢谢
【问题讨论】:
标签: java spring spring-boot spring-security