2016-11-29 101 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