Marco Sulla
Marco Sulla

Reputation: 15930

How can I get a list of all sessions in Spring?

I'm developing a web app using Spring Boot 2 and Gradle. I currently implemented a custom remember me mechanism (WITHOUT Spring Security), and I added also a series cookie, as described here.

Now I want to invalidate all user's session in case the token does not match. I would get all sessions of the user (a Bean that I save in "userSession" attribute). How can I do?

PS: I'm not using Spring Security.

Upvotes: 5

Views: 17125

Answers (2)

Witold Krzemiński
Witold Krzemiński

Reputation: 33

There is module for that in Spring called Spring Session which can easily manage all actual sessions. Link for Spring Session documentation

To run it basically you must add dependency in pom.xml:

    <dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-jdbc</artifactId>
    </dependency>

and add some config properties to application.properties:

spring.session.store-type=jdbc
spring.session.jdbc.initializer.enabled=true
spring.session.jdbc.schema=classpath:org/springframework/session/jdbc/schema-qlserver.sql 
spring.session.jdbc.table-name=SPRING_SESSION

In "spring.session.jdbc.schema=" you can pick your own type of DB or use a embedded one like H2. Spring will automatically create tables for sessions from inbuilt scripts where the sessions will be stored.

Upvotes: 0

Venu Duggireddy
Venu Duggireddy

Reputation: 806

You have to create a custom HttpSession holder object that will hold active sessions that you can iterate and invalidate based on your conditions.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class HttpSessionConfig {

    private static final Map<String, HttpSession> sessions = new HashMap<>();

    public List<HttpSession> getActiveSessions() {
        return new ArrayList<>(sessions.values());
    }

    @Bean
    public HttpSessionListener httpSessionListener() {
        return new HttpSessionListener() {
            @Override
            public void sessionCreated(HttpSessionEvent hse) {
                sessions.put(hse.getSession().getId(), hse.getSession());
            }

            @Override
            public void sessionDestroyed(HttpSessionEvent hse) {
                sessions.remove(hse.getSession().getId());
            }
        };
    }
} 

Upvotes: 9

Related Questions