Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:


NPI – Lightrun – Spring (partner)

We rely on other people’s code in our own work. Every day. It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production - debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky. It’s difficult to understand what talks to what and, specifically, which part of the underlying library is at fault.

Lightrun is a new kind of debugger.

It's one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics. No hotfixes, redeployments, or restarts required.

Learn more in this quick, 5-minute Lightrun tutorial:

>> The Essential List of Spring Boot Annotations and Their Use Cases

1. Overview

In this quick tutorial, we'll be exploring how to use the Spring Session backed with MongoDB, both with and without Spring Boot.

Spring Session can also be backed with other stores such as Redis and JDBC.

2. Spring Boot Configuration

First, let's look at the dependencies and the configuration required for Spring Boot. To start with, let's add the latest versions of spring-session-data-mongodb and spring-boot-starter-data-mongodb to our project:


After that, to enable Spring Boot auto-configuration, we'll need to add the Spring Session store-type as mongodb in the application.properties:


3. Spring Configuration Without Spring Boot

Now, let's take a look at the dependencies and the configuration required to store the Spring session in MongoDB without Spring Boot.

Similar to the Spring Boot configuration, we'll need the spring-session-data-mongodb dependency. However, here we'll use the spring-data-mongodb dependency to access our MongoDB database:


Finally, let's see how to configure the application:

public class HttpSessionConfig {

    public JdkMongoSessionConverter jdkMongoSessionConverter() {
        return new JdkMongoSessionConverter(Duration.ofMinutes(30));

The @EnableMongoHttpSession annotation enables the configuration required to store the session data in MongoDB.

Also, note that the JdkMongoSessionConverter is responsible for serializing and deserializing the session data.

4. Example Application

Let's create an application to test the configurations. We'll be using Spring Boot, as it's faster and requires less configuration.

We'll begin by creating the controller to handle requests:

public class SpringSessionMongoDBController {

    public ResponseEntity<Integer> count(HttpSession session) {

        Integer counter = (Integer) session.getAttribute("count");

        if (counter == null) {
            counter = 1;
        } else {

        session.setAttribute("count", counter);

        return ResponseEntity.ok(counter);

As we can see in this example, we're incrementing counter on every hit to the endpoint and storing its value in a session attribute named count.

5. Testing the Application

Let's test the application to see if we're actually able to store the session data in MongoDB.

To do so, we'll access the endpoint and inspect the cookie that we'll receive. This will contain a session id.

After that, we'll query the MongoDB collection to fetch the session data using the session id:

public void 
  givenEndpointIsCalledTwiceAndResponseIsReturned_whenMongoDBIsQueriedForCount_thenCountMustBeSame() {
    HttpEntity<String> response = restTemplate
      .exchange("http://localhost:" + 8080, HttpMethod.GET, null, String.class);
    HttpHeaders headers = response.getHeaders();
    String set_cookie = headers.getFirst(HttpHeaders.SET_COOKIE);


private String getSessionId(String cookie) {
    return new String(Base64.getDecoder().decode(cookie.split(";")[0].split("=")[1]));

6. How Does It Work?

Let's take a look at what goes on in the Spring session behind the scenes.

The SessionRepositoryFilter is responsible for most of the work:

  • converts the HttpSession into a MongoSession
  • checks if there's a Cookie present, and if so, loads the session data from the store
  • saves the updated session data in the store
  • checks the validity of the session

Also, the SessionRepositoryFilter creates a cookie with the name SESSION that is HttpOnly and secure. This cookie contains the session id, which is a Base64-encoded value.

To customize the cookie name or properties, we'll have to create a Spring bean of type DefaultCookieSerializer.

For instance, here we're disabling the httponly property of the cookie:

public DefaultCookieSerializer customCookieSerializer(){
    DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer();
    return cookieSerializer;

7. Session Details Stored in MongoDB

Let's query our session collection using the following command in our MongoDB console:


As a result, we'll get a BSON document similar to:

    "_id" : "5d985be4-217c-472c-ae02-d6fca454662b",
    "created" : ISODate("2019-05-14T16:45:41.021Z"),
    "accessed" : ISODate("2019-05-14T17:18:59.118Z"),
    "interval" : "PT30M",
    "principal" : null,
    "expireAt" : ISODate("2019-05-14T17:48:59.118Z"),

The _id is a UUID that will be Base64-encoded by the DefaultCookieSerializer and set as a value in the SESSION cookie. Also, note that the attr attribute contains the actual value of our counter.

8. Conclusion

In this tutorial, we've explored Spring Session backed with MongoDB — a powerful tool for managing HTTP sessions in a distributed system. With this purpose in mind, it can be very useful in solving the problem of replicating sessions across multiple instances of the application.

As usual, the source code is available over on GitHub.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:


Persistence footer banner
Comments are closed on this article!