如何仅在安全端点上应用 Spring Security 过滤器?

新手上路,请多包涵

我有以下 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 表达式匹配的端点上应用过滤器?

原文由 Bravo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 712
2 个回答

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

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

You can read it as follows: for http only invoke these configurations on requests matching the ant pattern /api/** authorizing any request to authenticated users and add filter authenticationTokenFilterBean() before UsernamePasswordAuthenticationFilter .对于所有其他请求,此配置无效。

原文由 Francisco Spaeth 发布,翻译遵循 CC BY-SA 4.0 许可协议

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 的过滤器中,您可以覆盖该方法并实现逻辑以仅在您想要的路由上运行过滤器。

原文由 Saša Šijak 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题