2016-11-29 102 views
-1

我在春天的security.xml我有這個如何在春季安全註冊自定義過濾器

<custom-filter before="FORM_LOGIN_FILTER" ref="MyAuthFilter" /> 

我的自定義過濾器是:

@Component 
public class MyAuthFilter extends UsernamePasswordAuthenticationFilter { 
@Override 
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) 
      throws AuthenticationException { 
...... 
} 
} 

但在啓動時我有一個錯誤:沒有可用的名爲「MyAuthFilter」的bean。

我的web.xml:

<context-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value>/WEB-INF/webproject-servlet.xml</param-value> 
    </context-param> 

    <listener> 
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
    </listener> 
    <!-- Loads Spring Security config file --> 
    <context-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value> 
      /WEB-INF/spring-security.xml 
     </param-value> 
    </context-param> 

    <!-- Spring Security --> 
    <filter> 
     <filter-name>springSecurityFilterChain</filter-name> 
     <filter-class>org.springframework.web.filter.DelegatingFilterProxy 
     </filter-class> 
    </filter> 

    <filter-mapping> 
     <filter-name>springSecurityFilterChain</filter-name> 
     <url-pattern>/*</url-pattern> 
    </filter-mapping> 

回答

1

問題在您的web.xml方面的配置位置我想,它需要ContextLoaderListener定義一次。

<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

<!-- Loads Spring Security config file --> 
<context-param> 
    <param-name>contextConfigLocation</param-name> 
     <param-value> 
      /WEB-INF/webproject-servlet.xml 
      /WEB-INF/spring-security.xml    
    </param-value> 
</context-param> 

<!-- Spring Security --> 
<filter> 
    <filter-name>springSecurityFilterChain</filter-name> 
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy 
    </filter-class> 
</filter> 

<filter-mapping> 
    <filter-name>springSecurityFilterChain</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 
+0

contextConfigLocation已被定義兩次 – kuhajeyan

+0

但它是兩個不同的xml文件。我應該把它們編成一個嗎?它在我添加自定義過濾器之前工作正常。 – CortezDaCardinal

+0

是的。你可以將它們組合起來,或者按照上面的方式聲明它 – kuhajeyan

1

請嘗試以下

<custom-filter before="FORM_LOGIN_FILTER" ref="MyAuthFilter" />

<custom-filter before="FORM_LOGIN_FILTER" ref="myAuthFilter" /> 

OR

@Component 
public class MyAuthFilter extends UsernamePasswordAuthenticationFilter { 

@Component("MyAuthFilter") 
public class MyAuthFilter extends UsernamePasswordAuthenticationFilter { 
+0

它不起作用。 – CortezDaCardinal