This guide describes how to use Spring Session to find sessions by username.

The completed guide can be found in the findbyusername application.

1. Assumptions

The guide assumes you have already added Spring Session using the built in Redis configuration support to your application. The guide also assumes you have already applied Spring Security to your application. However, we the guide will be somewhat general purpose and can be applied to any technology with minimal changes we will discuss.

If you need to learn how to add Spring Session to your project, please refer to the listing of samples and guides

2. About the Sample

Our sample is using this feature to invalidate the users session that might have been compromised. Consider the following scenario:

  • User goes to library and authenticates to the application

  • User goes home and realizes they forgot to log out

  • User can log in and terminate the session from the library using clues like the location, created time, last accessed time, etc.

Wouldn’t it be nice if we could allow the user to invalidate the session at the library from any device they authenticate with? This sample demonstrates how this is possible.

3. FindByIndexNameSessionRepository

In order to look up a user by their username, you must first choose a SessionRepository that implements FindByIndexNameSessionRepository. Our sample application assumes that the Redis support is already setup, so we are ready to go.

4. Mapping the username

FindByIndexNameSessionRepository can only find a session by the username, if the developer instructs Spring Session what user is associated with the Session. This is done by ensuring that the session attribute with the name FindByUsernameSessionRepository.PRINCIPAL_NAME_INDEX_NAME is populated with the username.

Generally, speaking this can be done with the following code immediately after the user authenticates:

String username = "username";
this.session.setAttribute(
		FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME, username);

5. Mapping the username with Spring Security

Since we are using Spring Security, the user name is automatically indexed for us. This means we will not have to perform any steps to ensure the user name is indexed.

6. Adding Additional Data to Session

It may be nice to associate additional information (i.e. IP Address, the browser, location, etc) to the session. This makes it easier for the user to know which session they are looking at.

To do this simply determine which session attribute you want to use and what information you wish to provide. Then create a Java bean that is added as a session attribute. For example, our sample application includes the location and access type of the session

public class SessionDetails implements Serializable {
	private String location;

	private String accessType;

	public String getLocation() {
		return this.location;
	}

	public void setLocation(String location) {
		this.location = location;
	}

	public String getAccessType() {
		return this.accessType;
	}

	public void setAccessType(String accessType) {
		this.accessType = accessType;
	}

	private static final long serialVersionUID = 8850489178248613501L;
}

We then inject that information into the session on each HTTP request using a SessionDetailsFilter. For example:

@Override
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
		FilterChain chain) throws IOException, ServletException {
	chain.doFilter(request, response);

	HttpSession session = request.getSession(false);
	if (session != null) {
		String remoteAddr = getRemoteAddress(request);
		String geoLocation = getGeoLocation(remoteAddr);

		SessionDetails details = new SessionDetails();
		details.setAccessType(request.getHeader("User-Agent"));
		details.setLocation(remoteAddr + " " + geoLocation);

		session.setAttribute("SESSION_DETAILS", details);
	}
}

We obtain the information we want and then set the SessionDetails as an attribute in the Session. When we retrieve the Session by username, we can then use the session to access our SessionDetails just like any other session attribute.

You might be wondering at this point why Spring Session does not provide SessionDetails functionality out of the box. The reason, is twofold. The first is that it is very trivial for applications to implement this themselves. The second reason is that the information that is populated in the session (and how frequently that information is updated) is highly application dependent.

7. Finding sessions for a specific user

We can now find all the sessions for a specific user.

@Autowired
FindByIndexNameSessionRepository<? extends Session> sessions;

@RequestMapping("/")
public String index(Principal principal, Model model) {
	Collection<? extends Session> usersSessions = this.sessions
			.findByIndexNameAndIndexValue(
					FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME,
					principal.getName())
			.values();
	model.addAttribute("sessions", usersSessions);
	return "index";
}

In our instance, we find all sessions for the currently logged in user. However, this could easily be modified for an administrator to use a form to specify which user to look up.

8. findbyusername Sample Application

8.1. Running the findbyusername Sample Application

You can run the sample by obtaining the source code and invoking the following command:

For the sample to work, you must install Redis 2.8+ on localhost and run it with the default port (6379). Alternatively, you can update the RedisConnectionFactory to point to a Redis server. Another option is to use Docker to run Redis on localhost. See Docker Redis repository for detailed instructions.

$ ./gradlew :spring-session-sample-boot-findbyusername:bootRun

You should now be able to access the application at http://localhost:8080/

8.2. Exploring the security Sample Application

Try using the application. Enter the following to log in:

  • Username user

  • Password password

Now click the Login button. You should now see a message indicating your are logged in with the user entered previously. You should also see a listing of active sessions for the currently logged in user.

Let’s emulate the flow we discussed in the About the Sample section

  • Open a new incognito window and navigate to http://localhost:8080/

  • Enter the following to log in:

    • Username user

    • Password password

  • Terminate your original session

  • Refresh the original window and see you are logged out