【问题标题】:spring security custom-filter with java configuration带有java配置的spring security自定义过滤器
【发布时间】:2015-07-10 14:18:48
【问题描述】:

如何在 java 配置中用自定义过滤器替换默认过滤器?在 XML 中,例如:

<bean id="myFilter" class="lalalal.MyFilter">
<property name="authenticationManager" ref="authenticationManager"/>
</bean>

<security:http auto-config="true">     
      <security:custom-filter ref="myFilter" position="FORM_LOGIN_FILTER"/>
</security:http> 

关于filterBefore,filterAfter和默认过滤器继承我知道。

【问题讨论】:

    标签: spring spring-security servlet-filters spring-java-config


    【解决方案1】:

    假设您大致了解 Spring-security 的 Java 配置,添加过滤器相对简单(general details of updating spring-security config to java here):

    所以在你的WebSecurityConfigurerAdapter 实现中,做这样的事情:

    @Configuration
    @EnableWebSecurity
    class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    
       @Override protected void configure(HttpSecurity http) throws Exception {
    
           //Custom security filters
           http.addFilterBefore( myFilter(), BasicAuthenticationFilter.class );
    
           //Rest of the security configuration goes here
           ...
       }
    

    这是一个非常精简的示例-但希望有足够的帮助-您可以在此处放置其他安全配置(例如基于角色的限制、csrf、会话配置等),myFilter() 是定义您在问题中提到的 bean 的另一种方法设置您的过滤器。还有一个 addFilterAfter() 方法,您可以选择在链中放置过滤器的位置。

    Here is an example for API security that shows some custom filters being used.

    【讨论】:

    • tnx 为您解答,但这并不是我正在寻找的。您在存在之前/之后显示插入您自己的过滤器。但我正在寻找插入我的过滤器 INSTEAD 默认值的方法。
    • 好的 - 也许这个答案会帮助您解决问题:stackoverflow.com/questions/24122586/… - 可能还值得看看您与 @EnableWebSecuriyt 一起使用并扩展 WebSecurityConfigurerAdapter 的弹簧代码(这就是为什么正在添加默认过滤器)github.com/spring-projects/spring-security/blob/master/config/…
    • tnx 再次,我已经阅读了这些文章,但我想知道在 HttpSecurity 中没有像 .addCustomFilter(filter, position) 这样的方法,根据 xml 变体
    • 我不知道 - 您的自定义过滤器在做什么?这不是可以使用类提供但配置的默认东西来完成的吗?
    • 没关系。关于 java 配置中的自定义过滤器的问题。现在似乎我几乎找到了答案。但是存在子问题:我可以在 中使用什么类型的 bean 作为 ref?任何人或只有默认过滤器类型的子类型?
    猜你喜欢
    • 2018-05-25
    • 2014-07-30
    • 1970-01-01
    • 2011-08-23
    • 2014-07-28
    • 2013-07-22
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多