[RESOLVIDO] Spring Security 3 - Custom Filter

Olá pessoal,
Estou com problemas para estender um filtro do Spring Security 3.

Meu filtro:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

public class JsonUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
		System.out.println("entrou");
		return super.attemptAuthentication(request, response);
	}
	
}

applicationContext.xml

        <beans:bean id="customFormLoginFilter" class="br.com.k2studio.spring.filter.JsonUsernamePasswordAuthenticationFilter" />
	
	<http>
		<form-login login-page="/" authentication-failure-url="/?error=invalido" default-target-url="/secure/home"/>
		<intercept-url  pattern="/secure/**" access="ROLE_SECURE" />
		<custom-filter position="FORM_LOGIN_FILTER" ref="customFormLoginFilter" />
	</http>

Erro:

10:39:05,032 ERROR [org.springframework.web.context.ContextLoader] Context initialization failed: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Filter beans '<customFormLoginFilter>' and 'Root bean: class [org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null' have the same 'order' value. When using custom filters, please make sure the positions do not conflict with default filters. Alternatively you can disable the default filters by removing the corresponding child elements from <http> and avoiding the use of <http auto-config='true'>.
Offending resource: ServletContext resource [/WEB-INF/applicationContext.xml]
	at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68) [:3.0.3.RELEASE]
	at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85) [:3.0.3.RELEASE]
	at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:72) [:3.0.3.RELEASE]
....

Alguma dica de onde está o erro?

[]'s
Daniel

Nos projetos daqui eu dois arquivos o aplicattion-context.xml
para o Spring e o application-security.xml para o Spring Security.
Esta sua configuração não deveria estar no arquivo de configuração do Spring Security?

Eu estou usando o VRaptor com Spring Security, por isso só estou utilizando oXML para configurar o Security.
E sem as linhas do meu filtro ele funciona normalmente.

[]'s
Daniel

Mas é possível usar o Spring Security sem este arquivo de configuração que eu citei??

Então, minha configuração está assim:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>webapp</display-name>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <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>
  <filter>
    <filter-name>vraptor</filter-name>
    <filter-class>br.com.caelum.vraptor.VRaptor</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>vraptor</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>REQUEST</dispatcher>
  </filter-mapping>
  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>messages</param-value>
  </context-param>
</web-app>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd"
             >
	
	<!-- 
	<beans:bean id="customFormLoginFilter" class="br.com.k2studio.spring.filter.JsonUsernamePasswordAuthenticationFilter" />
	 -->
	<http>
		<form-login login-page="/" authentication-failure-url="/?error=invalido" default-target-url="/secure/home"/>
		<intercept-url  pattern="/secure/**" access="ROLE_SECURE" />
		<!-- 
		<custom-filter position="FORM_LOGIN_FILTER" ref="customFormLoginFilter" />
		 -->
	</http>
	
	<authentication-manager>
		<authentication-provider>
		<password-encoder hash="md5" />
		<jdbc-user-service data-source-ref="dataSource"
			users-by-username-query="SELECT email as username, senha as password, CASE status WHEN 1 THEN 'true' WHEN 0 THEN CASE WHEN 24 > EXTRACT(DAY FROM CURRENT_TIMESTAMP - usuario.data_cadastro) * 24 + extract(HOUR FROM CURRENT_TIMESTAMP - usuario.data_cadastro) THEN 'true' ELSE 'false' END END as enable FROM usuario WHERE email = ?"
			authorities-by-username-query="SELECT email as username, r.regra as authority FROM usuario u, usuario_regra ur, regra r WHERE r.id = ur.regra_id AND ur.usuario_id = u.id AND u.email = ?"/>
		</authentication-provider>
	</authentication-manager>
	
	<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
		<beans:property name="url" value="jdbc:postgresql://localhost:5432/database" />
		<beans:property name="driverClassName" value="org.postgresql.Driver" />
		<beans:property name="username" value="postgres" />
		<beans:property name="password" value="postgres" />
	</beans:bean>
</beans:beans>

E dessa forma que está, com o meu Filter comentado, o sistema está funcionando.
Mas preciso criar um filter para poder utilizar uma chamada AJAX no /j_spring_security_check retornando assim os dados em formato JSON.
Preciso disso para submeter o login utilizando jQuery.

[]'s
Daniel

E se eu renomear o applicationContext.xml para application-security.xml ele reclama que o applicationContext.xml não foi encontrado.

[]'s
Daniel

Resolvido pessoal.
Olhando a documentação do Spring Security eu encontrei uma maneira de pegar o contexto e inserir o usuário.
Para quem tiver a mesma dúvida, está na parte 5.3 Authentication do documento http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ns-config

De qualquer forma vou escrever um post no blog detalhando melhor a solução.

[]'s
Daniel

Cara eu estou usando a mesma coisa no meu projeto ta tudo otimo, se quiser mando para vc !

abraço jr.