The following is added to the Config class that inherits WebSecurityConfigurerAdapter.
@Bean
public <S extends Session> SessionRegistry sessionRegistry(FindByIndexNameSessionRepository<S> sessionRepository) {
return new SpringSessionBackedSessionRegistry<>(sessionRepository);
}
Add the generated SessionRegistry to the HttpSecurity settings.
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/secure.html").authenticated().anyRequest().permitAll()
// login settings
.and().formLogin()
// ligout settings
.and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
//Additional minutes from here
.and().sessionManagement()
//Maximum number of sessions allowed per user
// -1 is unlimited
.maximumSessions(-1)
//Session Registry used for multiple logouts
.sessionRegistry(sessionRegistry(null))
//URL to transition to when the session expires(If you do not set it, an error message will appear on that screen.)
.expiredUrl("/login?logout");
}
The setting is over
After that, you can get a list of sessions of the same user using Session Registry as a controller or service.
The following is an example of the process to log out the same user session excluding the currently logged-in session.
@Autowired
private SessionRegistry sessionRegistry;
@RequestMapping("/logoutAnother")
public String logoutAnother(HttpSession currentSession) {
String sessionId = currentSession.getId();
Optional<Object> principal = Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.map(authentication -> authentication.getPrincipal());
if (principal.isPresent()) {
//Get the session list of the same user who is currently logged in
List<SessionInformation> sessions = sessionRegistry.getAllSessions(principal.get(), false);
for (SessionInformation session : sessions) {
if (sessionId.equals(session.getSessionId())) {
//Do not log out only for the current session
continue;
}
//Session expired and logged out
session.expireNow();
}
}
return "redirect:/";
}
You can get the session list of the same user as the user information passed to the first argument with sessionRegistry.getAllSessions.
If you want to get the session list of any user instead of the logged-in user, you can get it by entering the ID of any user in the first argument. (Assuming that an administrator etc. forcibly logs out any user)
//String
List<SessionInformation> sessions = sessionRegistry.getAllSessions("user", false);
// UserDetails: userDeails.getUsername() => "user"
List<SessionInformation> sessions = sessionRegistry.getAllSessions(userDeails, false);
// Principal: principal.getName() => "user"
List<SessionInformation> sessions = sessionRegistry.getAllSessions(principal, false);
--Example
Recommended Posts