Expirar sessão de um usuário específico através do Session ID (SPRING-SECURITY 3.1)

1 resposta
L

Olá pessoal !

Estou com a seguinte dúvida:

Meu sistema possui dois cadastros básicos; são eles:

Cadastro de Usuários
Cadastro de Perfis

Somente o administrador tem acesso aos cadastros, quando o mesmo alterar as permissões do Perfil específico, eu gostaria de forçar o logout de todos os usuário logados no sistema com este determinado perfil.

Estava pensando em utilizar o sessionID , pois é através dele que podemos invalidar uma sessão.

como eu posso recuperar todos os sessionsID’s atualmente logados no sistema ???

através deles eu posso fazer:

sessionRegistry.getSessionInformation([color=red]sessionID[/color]).expireNow();

talvez essa não seja a melhor forma, alguém tem alguma idéia melhor ou poderia implementar a minha mesma idéia ??

Muito obrigado desde já !!

1 Resposta

L

Pessoal , já faz um tempo que eu postei e não obtive nenhuma resposta, estou realmente precisando, alguém poderia me ajudar ???

o que eu fiz até agora:

Meu application-context-security:

<?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"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"

	
	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.1.xsd
           
           http://www.springframework.org/schema/context
           
           http://www.springframework.org/schema/context/spring-context-3.1.xsd">


	<http use-expressions="true" auto-config="false" entry-point-ref="authenticationEntryPoint">

		<!-- Don't set any role restrictions on login.jsp -->
		<intercept-url pattern="/content/login/login.jsf"
			access="permitAll" />

		<!-- Restrict access to ALL other pages -->
		<intercept-url pattern="/content/template.jsf"
			access="hasAnyRole('ROLE_ADMINISTRADOR','ROLE_USUARIO')" />


		<logout logout-success-url="/content/login/login.jsf" invalidate-session="true" />


		<custom-filter ref="authenticationFilter" position="FORM_LOGIN_FILTER" />

		<custom-filter ref="concurrencyFilter" after="CONCURRENT_SESSION_FILTER" />

		<session-management
			session-authentication-strategy-ref="sas" />

	</http>

	<b:bean id="authenticationFilter"
		class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"
		p:sessionAuthenticationStrategy-ref="sas" p:authenticationManager-ref="authenticationManager"
		p:authenticationFailureHandler-ref="customAuthenticationFailureHandler"
		p:authenticationSuccessHandler-ref="customAuthenticationSuccessHandler" />

	<!-- We just actually need to set the default failure url here -->
	<b:bean id="customAuthenticationFailureHandler"
		class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"
		p:defaultFailureUrl="/content/login/login?login_error=1" />

	<!-- We just actually need to set the default target url here -->
	<b:bean id="customAuthenticationSuccessHandler"
		class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler"
		p:defaultTargetUrl="/content/template.jsf" />

	<!-- The AuthenticationEntryPoint is responsible for redirecting the user 
		to a particular page, like a login page, whenever the server sends back a 
		response requiring authentication -->
	<!-- See Spring-Security Reference 5.4.1 for more info -->
	<b:bean id="authenticationEntryPoint"
		class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"
		p:loginFormUrl="/content/login/login" />


	<authentication-manager alias="authenticationManager">

		<authentication-provider user-service-ref="userDetailsService">
		</authentication-provider>

	</authentication-manager>

	<jdbc-user-service data-source-ref="dataSource"
		id="userDetailsService" users-by-username-query="SELECT login, senha, 'true' as enable FROM usuario WHERE login=?"
		authorities-by-username-query="SELECT usuario.login, perfil.desc_perfil FROM usuario,perfil WHERE usuario.id_perfil = perfil.id_perfil and usuario.login=?" />

	<!-- data source -->
	<b:bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<b:property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver" />
		<b:property name="url"
			value="jdbc:jtds:sqlserver://192.168.2.61:1433/baseTeste" />
		<b:property name="username" value="sa" />
		<b:property name="password" value="sql" />
	</b:bean>

	<b:bean id="sas"
		class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy"
		p:maximumSessions="1">
		<b:constructor-arg name="sessionRegistry" ref="sessionRegistry" />
	</b:bean>

	<b:bean id="concurrencyFilter"
		class="org.springframework.security.web.session.ConcurrentSessionFilter"
		p:sessionRegistry-ref="sessionRegistry" />

	<b:bean id="sessionRegistry"
		class="org.springframework.security.core.session.SessionRegistryImpl" />

	<!-- Declare a view resolver -->
	<b:bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		p:prefix="/WEB-INF/jsf/" p:suffix=".jsf" />


	<b:bean class="utils.ControleSpring" />

	<context:annotation-config/>

	<context:component-scan base-package="ui.cadastrarperfil"></context:component-scan>
	
</b:beans>

Eu criei um objeto no meu bean do tipo SessionRegistry que foi injetado via xml, porém eu só consigo esta informação no momento que inicia minha aplicação, sei disso porque usei @PostConstruct para encontrar o valor e o objeto está valorado.
Mas quando faço alguma solicitação ao meu bean obviamente o jsf cria uma nova instancia deste bean, consequentemente limpando este meu objeto… como eu poderia manter este objeto em memória para poder utilizá-lo ???

Meu bean:

package ui.cadastrarperfil;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import beans.perfilpermissao.PerfilBean;

@ManagedBean(name="cadastrarPerfil")
@Controller
@SessionScoped
@RequestMapping("/content")
public class InterfaceCadastrarPerfil {

	private PerfilBean perfilSelecionado;
	private List<PerfilBean> listaPerfil;

	private boolean ativosFiltro;
	private boolean inativosFiltro;
	private boolean desabilitaChecks;
	
@Autowired
	private SessionRegistryImpl sessionRegistry;

		 
	public InterfaceCadastrarPerfil(){
		
		System.out.println("ENTROU CONSTRUTOR--------------------------------------------------------------------------");
	}

	// M�TODOS
	
	@PostConstruct
	public void teste(){
		
		System.out.println(sessionRegistry);
	}

	public String inicializarTela() {

		int i = 1;

		/*
		 * UserDetails detalhe = (UserDetails)
		 * SecurityContextHolder.getContext()
		 * .getAuthentication().getPrincipal();
		 * 
		 * System.out.println("entrou");
		 * 
		 * String sessionId =
		 * RequestContextHolder.currentRequestAttributes().getSessionId();
		 * 
		 * System.out.println("Session ID: " + sessionId);
		 * 
		 * 
		 * List<SessionInformation> sessoes =
		 * this.getAllSessions(SecurityContextHolder
		 * .getContext().getAuthentication().getPrincipal(),true);
		 * 
		 * System.out.println("tamanho sessoes " + sessoes.size() );
		 * 
		 * for(SessionInformation s: sessoes){
		 * 
		 * System.out.println(s.getSessionId());
		 * 
		 * }
		 */
		
		
		
		//List<SessionInformation> sessoes = sessionRegistry.getAllSessions(SecurityContextHolder.getContext().getAuthentication()
		//				.getPrincipal(), true);

		//System.out.println(sessoes.size());
		
		//System.out.println("FUNCIONOU :):)");
		
		System.out.println(sessionRegistry);
		
				
		setDesabilitaChecks(false);

		return "INICIAR_CADASTRAR_PERFIL";
	}


	// GETTERS AND SETTERS

	public PerfilBean getPerfilSelecionado() {
		return perfilSelecionado;
	}

	public void setPerfilSelecionado(PerfilBean perfilSelecionado) {
		this.perfilSelecionado = perfilSelecionado;
	}

	public List<PerfilBean> getListaPerfil() {
		return listaPerfil;
	}

	public void setListaPerfil(List<PerfilBean> listaPerfil) {
		this.listaPerfil = listaPerfil;
	}

	public boolean isAtivosFiltro() {
		return ativosFiltro;
	}

	public void setAtivosFiltro(boolean ativosFiltro) {
		this.ativosFiltro = ativosFiltro;
	}

	public boolean isInativosFiltro() {
		return inativosFiltro;
	}

	public void setInativosFiltro(boolean inativosFiltro) {
		this.inativosFiltro = inativosFiltro;
	}

	public boolean isDesabilitaChecks() {
		return desabilitaChecks;
	}

	public void setDesabilitaChecks(boolean desabilitaChecks) {
		this.desabilitaChecks = desabilitaChecks;
	}

	public SessionRegistryImpl getSessionRegistry() {
		return sessionRegistry;
	}

	public void setSessionRegistry(SessionRegistryImpl sessionRegistry) {
		this.sessionRegistry = sessionRegistry;
	}

}

Já postei o mesmo problema no SPRING-FORUM mas ainda não obtive resposta para ele… pesquisei bastante mas não axo nada a respeito…agradeço muito se vocês puderem me ajudar !!!

Muito obrigado !!

Criado 18 de novembro de 2011
Ultima resposta 22 de nov. de 2011
Respostas 1
Participantes 1