如何仅在安全端点上应用Spring安全filter?

我有以下Spring Security配置:

httpSecurity .csrf() .disable() .exceptionHandling() .authenticationEntryPoint(unauthorizedHandler) .and() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .authorizeRequests() .antMatchers("/api/**").fullyAuthenticated() .and() .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); 

即使在与/api/**表达式不匹配的端点上也应用authenticationTokenFilterBean() 。 我还尝试添加以下配置代码

 @Override public void configure(WebSecurity webSecurity) { webSecurity.ignoring().antMatchers("/some_endpoint"); } 

但这仍然没有解决我的问题。 如何告诉spring security仅在与安全URI表达式匹配的端点上应用filter? 谢谢

我有一个具有相同要求的应用程序并解决它我基本上将Spring Security限制为给定的ant匹配模式(使用antMatcher ),如下所示:

 http.antMatcher("/api/**").authorizeRequests() // .anyRequest().authenticated() // .and() .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); 

您可以按如下方式阅读:for http仅在与ant模式/api/**匹配的请求上调用这些配置,授权对经过authenticated用户的any requestand before UsernamePasswordAuthenticationFilter before add filter authenticationTokenFilterBean() 。 对于所有其他请求,此配置无效。

要绕过某些特定端点的弹簧安全性,请执行以下操作:

 httpSecurity .authorizeRequests() .antMatchers("/some_endpoints").permitAll() .anyRequest().authenticated() .and() ... 

如果使用.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

您可以在构造函数中定义它将应用于的特定路径:

 public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter { public JwtAuthenticationFilter(AuthenticationManager authenticationManager) { super("/api/**"); this.setAuthenticationManager(authenticationManager); } @Override protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) { return super.requiresAuthentication(request, response); } 

requiresAuthentication方法将用于了解该端点是否需要身份validation