CortezDaCardinal CortezDaCardinal - 4 days ago 6
Java Question

how to register a custom filter in spring security

in my spring-security.xml i have this

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


My custom filter is:

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


But on the startup i have an error : No bean named 'MyAuthFilter' available.

My 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>

Answer

Problem in your web.xml context config location I guess, it needs to be defined once for 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>
Comments