如何仅在受保护的端点上应用Spring安全过滤器?

我有以下Spring Security配置:

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

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

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

但这仍然没有解决我的问题。如何告诉Spring Security仅在与安全URI表达式匹配的端点上应用过滤器?


答案 1

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

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

您可以按如下方式阅读它:因为仅在与授权给用户的 ant 模式匹配的请求上调用这些配置。对于所有其他请求,此配置不起作用。http/api/**any requestauthenticatedandadd filterauthenticationTokenFilterBean()beforeUsernamePasswordAuthenticationFilter


答案 2

GenericFilterBean有以下方法:

/**
     * Can be overridden in subclasses for custom filtering control,
     * returning {@code true} to avoid filtering of the given request.
     * <p>The default implementation always returns {@code false}.
     * @param request current HTTP request
     * @return whether the given request should <i>not</i> be filtered
     * @throws ServletException in case of errors
     */
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return false;
    }

因此,在扩展的筛选器中,可以重写该方法并实现逻辑以仅在所需的路由上运行筛选器。GenericFilterBean