Olá colegas
Estou com algumas dificuldades com o Spring Security (SS) integrado ao Hibernate e gostaria da ajuda de vocês.
São dois problemas:
1º - Após o login, o SS não direciona para a página inicial; Ainda que o login falhe, o SS não direciona para a página de erros.
Entretanto, eu posso acessar as páginas do sistema digitando a URL no browser após fazer o login, o que me leva a crer que o SS está agindo (ainda que de forma incompleta)
2º - O logout também não direciona o usuário para a página correta, além de não remover o usuário da sessão. Assim, o usuário pode continuar usando o sistema mesmo depois de ter feito o logout.
Vou postar as configurações abaixo, acho que pode ajudar.
web.xml
[code]<?xml version="1.0" encoding="UTF-8"?>
<welcome-file-list>
<welcome-file>home.xhtml</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>primefaces.THEME</param-name>
<param-value>bluesky</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.writeStateAtFormEnd</param-name>
<param-value>false</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>Spring Hibernate Filter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Spring Hibernate Filter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
[/code]
faces-config.xml
[code]<?xml version="1.0" encoding="utf-8"?>
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
<variable-resolver>org.springframework.web.jsf.DelegatingVariableResolver</variable-resolver>
</application>
<lifecycle>
<phase-listener>br.com.empresa.sistema.jsf.LoginErrorPhaseListener</phase-listener>
</lifecycle>
[/code]
applicationContext.xml
[code]<?xml version="1.0" encoding="UTF-8"?>
<context:property-placeholder location="classpath:application.properties" />
<context:component-scan base-package="br.com.empresa.sistema" />
<import resource="spring-dao.xml" />
<import resource="spring-security.xml" />
<tx:annotation-driven />
<bean name="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="annotatedClasses">
<list>
<value>br.com.empresa.sistema.model.Usuario</value>
<value>br.com.empresa.sistema.model.Perfil</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${database.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="exposeTransactionAwareSessionFactory">false</prop>
</props>
</property>
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Injeta uma sessão do hibernate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.username}" />
<property name="password" value="${database.password}" />
</bean>
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="view">
<bean class="br.com.empresa.sistema.spring.ViewScope" />
</entry>
</map>
</property>
</bean>
<bean id="loggerListener"
class="org.springframework.security.access.event.LoggerListener" />
[/code]
spring-securty.xml
[code]<?xml version="1.0" encoding="UTF-8"?>
<security:http auto-config="true" use-expressions="true" access-denied-page="/AcessoNegado.jsf" >
<security:intercept-url pattern="/style/*" filters="none"/>
<security:intercept-url pattern="/layout/*" filters="none"/>
<security:intercept-url pattern="/home.jsf*" access="hasAnyRole('ADMIN', 'USER')" />
<security:intercept-url pattern="/admin/*" access="hasRole('ADMIN')" />
<security:intercept-url pattern="/cadastro/*" access="hasAnyRole('ADMIN', 'USER')" />
<security:form-login login-page="/login.jsf"
login-processing-url="/j_spring_security_check"
default-target-url="/home.jsf"
always-use-default-target="true"
authentication-failure-url="/loginError.jsf" />
<security:logout invalidate-session="true" logout-url="/j_spring_security_logout" logout-success-url="/login.jsf" />
</security:http>
<security:authentication-manager>
<security:authentication-provider
user-service-ref="hibernateUserDetailsService" ref="daoAuthenticationProvider" />
</security:authentication-manager>
<bean id="daoAuthenticationProvider"
class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="hibernateUserDetailsService" />
</bean>
[/code]
login.xhtml:
[code]<?xml version="1.0" encoding="ISO-8859-1"?>
<f:view contentType=“text/html”>
<h:head>
<title>Login - Sistema</title>
<link type="text/css" rel="stylesheet"
href="#{request.contextPath}/style/default.css" />
<link type="text/css" rel="stylesheet"
href="#{request.contextPath}/style/syntaxhighlighter/syntaxhighlighter.css" />
</h:head>
<h:body>
<h:form prependId="false" >
<p:messages id="mensagens" showDetail="true" showSummary="false" />
<p:layout fullPage="true">
<p:layoutUnit id="top" position="north" size="auto">
<h:panelGrid columns="3" styleClass="login_form"
columnClasses="login_form_column,login_form_column">
<h:outputLabel for="j_username" value="Login" />
<h:outputLabel for="j_password" value="Senha" />
<h:outputLabel />
<p:inputText id="j_username" label="Login" />
<p:password id="j_password" required="true" label="Senha" />
<p:commandButton id="submit" value="Entrar"
action="#{loginMB.login()}" />
<p:selectBooleanCheckbox value="Mantenha-me conectado" />
<h:outputLink value="#{request.contextPath}/retrievePassword.jsf">
Esqueceu sua senha?
</h:outputLink>
<h:outputLabel />
</h:panelGrid>
</p:layoutUnit>
<p:layoutUnit id="center" position="center">
</p:layoutUnit>
<p:layoutUnit id="bottom" position="south" minSize="50" size="auto"
visible="true">
<ui:include src="layout/footer.xhtml" />
</p:layoutUnit>
</p:layout>
</h:form>
</h:body>
</f:view>
[/code]LoginMB.java
[code]package br.com.empresa.sistema.view.mb;
import javax.faces.context.FacesContext;
import javax.servlet.RequestDispatcher;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import br.com.empresa.sistema.jsf.FacesUtil;
import br.com.empresa.sistema.model.Usuario;
@Controller(“loginMB”)
@Scope(“session”)
public class LoginMB {
public LoginMB() {
}
public void login() {
try {
RequestDispatcher dispatcher = FacesUtil.getServletRequest()
.getRequestDispatcher("/j_spring_security_check");
dispatcher.forward(FacesUtil.getServletRequest(),
FacesUtil.getServletResponse());
FacesContext.getCurrentInstance().responseComplete();
} catch (Exception ex) {
ex.printStackTrace();
FacesUtil.exibirMensagemErro("Usuário e/ou senha incorretos.");
}
}
public void logout() {
try {
RequestDispatcher dispatcher = FacesUtil.getServletRequest()
.getRequestDispatcher("/j_spring_security_logout");
dispatcher.forward(FacesUtil.getServletRequest(),
FacesUtil.getServletResponse());
FacesContext.getCurrentInstance().responseComplete();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}[/code]
O logout eu faço (pelo menos tento fazer) atavés de um menu com a chamada:
<p:menuitem icon="ui-icon ui-icon-closethick" value="Sair"
action="#{loginMB.logout()}" />
É isso aí pessoal. Qualquer ajuda será bem vinda.
Agradeço desde já.
Edenilton