Efetuar Login com SpringSecurity + JSF2 + PrimeFaces

Coloquei o SpringSecurity pra fucionar, tento acessar uma pagina e ele me direciona para a pagina de login. Até ae OK, quando eu tento efetuar o login ele nao faz nada, nao trava, nao da erro, nao avança, nao volta. kkkkkkkk queria saber como ele direcionar para a pagina de logado…

estrutura das pastas

webcontent
-jsp
–login.xhtml
–sucesso.xhtml
–erro.xhtml
–privado
—principal.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<b:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:b="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">
	<http auto-config="true" >
		<!-- Don't set any role restrictions on login.jsp -->
		<intercept-url pattern="/jsp/login.xhtml" access="IS_AUTHENTICATED_ANONYMOUSLY"  />
		<!-- Restrict access to ALL other pages -->
		<intercept-url pattern="/jsp/privado/*.xhtml" access="ROLE_USER"  />
		<!-- Set the login page and what to do if login fails -->
		<form-login login-page="/jsp/login.xhtml" 
			authentication-failure-url="/jsp/login.xhtml?login_error=1"  default-target-url="/jsp/sucesso.xhtml"
			login-processing-url="/j_spring_security_check"
			/>
	</http>
	<authentication-manager>
		<authentication-provider>
			<jdbc-user-service data-source-ref="dataSource"
				users-by-username-query="SELECT login as username, senha as password, 'true' as enable FROM usuario WHERE login = ?"
				authorities-by-username-query="SELECT u.login as username, n.nome as authority FROM usuario u, usuarionivel n WHERE  u.nivel_id = n.id AND u.login = ?" />
		</authentication-provider>
	</authentication-manager>
	<b:bean id="dataSource"	class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<b:property name="url"
			value="jdbc:mysql://localhost:3306/decom" />
		<b:property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<b:property name="username" value="rootx" />
		<b:property name="password" value="root" />
	</b:bean>
</b:beans>

login.xhtml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui"
	xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
</h:head>
<h:body style="font-family: sans-serif; font-size: 11px; ">

	<center>
		<p:dialog widgetVar="login" width="230" height="160" dynamic="true"
			resizable="false" style="margin: 0;" header="DECOM - SISViagem"
			visible="true" showEffect="fade" maximizable="false" closable="false"
			id="dialogLogin">

			<br />
			<br />
			<form action="j_spring_security_check" method="post">
				<h:panelGrid columns="2">
					<h:outputText value="Login:"></h:outputText>
					<p:inputText id="j_username"></p:inputText>
					<h:outputText value="Senha:"></h:outputText>
					<p:password id="j_password"></p:password>
					<h:column></h:column>
					<p:commandButton value="Entrar" action="#{usuarioController.login}"></p:commandButton>

				</h:panelGrid>
			</form>
		</p:dialog>
	</center>

</h:body>
</html>

usuarioController

package br.com.Decom.ManergerBeam;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

import br.com.Decom.Model.Usuario;

@SessionScoped
@ManagedBean
public class UsuarioController  implements Serializable  {

	private static final long serialVersionUID = 1L;
	private Usuario usuario = new Usuario();

	//DAO<Usuario> daoUsDao = new DAO<Usuario>(Usuario.class);
	//private String login;

	//private String senha;

	public UsuarioController() {
		System.out.println("teset");
		    usuario = new Usuario();
	        SecurityContext context = SecurityContextHolder.getContext();
	        if (context instanceof SecurityContext){
	            Authentication authentication = context.getAuthentication();
	            if (authentication instanceof Authentication){
	                usuario.setNome(((User)authentication.getPrincipal()).getUsername());
	                System.out.println("Nome: " + usuario.getNome());
	            }
	        } 
	}
	public void login(){
		System.out.println("teste");
	}
}

Você pode add na a propriedade authentication-success-handler-ref=“algumaCoisa”
onde ela aponta pra um component do spirng. Ficando ± assim:

<form-login login-page="/login" authentication-failure-url="/login" authentication-success-handler-ref="algumaCoisa" default-target-url="/" always-use-default-target="false" />

crie uma classe qualquer anote-a como @Component(“algumaCoisa”) e extenda: SavedRequestAwareAuthenticationSuccessHandler e implemente: Filter, LogoutSuccessHandle

@Component("algumaCoisa")
public class AlgumaCoisa extends SavedRequestAwareAuthenticationSuccessHandler implements Filter, LogoutSuccessHandler {

@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws ServletException, IOException {
		HttpServletResponse resp = addCookies(request, response,authentication);
		
		Usuario usuario = (Usuario) authentication.getPrincipal();
		request.getSession().setAttribute("usuario", usuario);
		request.getSession().setAttribute("permissoes", usuario.getAuthorities());
		
		super.onAuthenticationSuccess(request, resp, authentication);
	}
}

quando o usuário fizer a autenticação vai ser chamado o method onAuthenticationSuccess.
Nele vc pode add cookies… pegar as perms do usuário e fazer responses. Podendo redireciona-lo para uma página, por exemplo.

Fala pessoal, blz?
Invadindo aqui o post =)
eu estou batendo cabeça com isso e não faço mais a minima ideia do que fazer.
Não sei se o q fiz esta correto, mas qdo clico em login simplesmente nao acontece nada.
meu spring-security.xml

<?xml version="1.0" encoding="UTF-8"?> <b:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:b="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"> <http auto-config="true" > <!-- Don't set any role restrictions on login.jsp --> <intercept-url pattern="/login.xhtml" access="IS_AUTHENTICATED_ANONYMOUSLY" /> <!-- Restrict access to ALL other pages --> <intercept-url pattern="/paginas/privado/*.xhtml" access="ROLE_USER" /> <!-- Set the login page and what to do if login fails --> <form-login login-page="/login.xhtml" authentication-failure-url="/login.xhtml?login_error=1" default-target-url="/paginas/inicio.xhtml" login-processing-url="/j_spring_security_check" authentication-success-handler-ref="algumaCoisa" /> </http> <authentication-manager> <authentication-provider> <jdbc-user-service data-source-ref="dataSource" users-by-username-query="SELECT login_usuario, login_senha FROM login limit 1" authorities-by-username-query="SELECT login_usuario, login_senha FROM login limit 1" /> </authentication-provider> </authentication-manager> <b:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <b:property name="url" value="jdbc:mysql://localhost:3306/formafit" /> <b:property name="driverClassName" value="com.mysql.jdbc.Driver" /> <b:property name="username" value="root" /> <b:property name="password" value="erz84b626" /> </b:bean> </b:beans>

Nesse caso coloquei um limit só p trazer algo no resultado.

Meu login.xhtml

[code]<?xml version="1.0" encoding="ISO-8859-1"?>

<h:head>

   <title>
   		Spring + Security + Hibernate
   </title>
   
   <link type="text/css" rel="stylesheet" href="#{facesContext.externalContext.requestContextPath}/css/redmond/skin.css" />

</h:head>

<h:body>

   <h:form prependId="false">
   
   		<p:dialog header="Area restrita"
   				  modal="true"
   				  closable="false"
   				  position="center"
   				  widgetVar="modalLogin"
   				  minWidth="300"
   				  width="300"
   				  showEffect="slide" 
   		    	  draggable="false"
   		    	  resizable="false"
   		    	  visible="true">		 
   				 
   			<center>	 
   				 
			   	<p:messages id="mensagens" showDetail="true" showSummary="false" />    				 
	   				 
	   			<h:panelGrid columns="2">   		
	     	
			      	<h:outputLabel value="Login" />
	     			<h:inputText value="#{loginBean.login}" size="15" />
	
			 		<h:outputLabel value="Senha" />
					<h:inputSecret value="#{loginBean.senha}" size="15" />
									
				</h:panelGrid>
				
				<br />	
	
				<h:commandButton value="Entrar" action="#{loginBean.logar}" />		
				
			</center>
				
		</p:dialog>
			
 	</h:form>

</h:body>
[/code]

classe login

[code]package br.com.exemploseguranca.web.controle;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;

import br.com.exemploseguranca.web.util.FacesUtil;

@ManagedBean(name = “loginBean”)
@SessionScoped
public class LoginMB {

private String login;

private String senha;
		
public String getLogin() {
	return login;
}

public void setLogin(String login) {
	this.login = login;
}

public String getSenha() {
	return senha;
}

public void setSenha(String senha) {
	this.senha = senha;
}

public LoginMB() {	
}

public String logar() {
	try {
		System.out.println("Passou aqui");
	    RequestDispatcher dispatcher = FacesUtil.getServletRequest().getRequestDispatcher("/j_spring_security_check");
	    dispatcher.forward(FacesUtil.getServletRequest(), FacesUtil.getServletResponse());
	    FacesContext.getCurrentInstance().responseComplete();
	} catch (Exception ex) {
		FacesUtil.exibirMensagemErro(ex.getMessage());
		return null;
	}
    return null;
}

public String logout() {
	FacesUtil.exibirMensagemAlerta("Sess?o finalizada com sucesso");
	try {
		RequestDispatcher dispatcher = FacesUtil.getServletRequest().getRequestDispatcher("/j_spring_security_logout");
		dispatcher.forward(FacesUtil.getServletRequest(), FacesUtil.getServletResponse());
		FacesContext.getCurrentInstance().responseComplete();
	} catch (Exception ex) {
		FacesUtil.exibirMensagemErro("Erro ao sair do sistema");
		return null;
	}
	return null;
}

}
[/code]

Ele não da erro e nenhum retorno.
Alguem tem alguma ideia de onde errei?

Vlwwww

[]s

A variável addCookies como vc crio ela?

alguém?

analisando o debug do firefox e do chrome, ele ta direcionando para “http://localhost:8080/Projeto/jsp/j_spring_security_check” como nao existe essa pagina ele da not found, ae ele nao mostra. alguem pode ajudar…

Ninguem? :frowning: