I want to be able to log out all logged in users programmatically. How do you force logout all users on some event?
Basic Configuration The basic configuration of Spring Logout functionality using the logout() method is simple enough: @Configuration @EnableWebSecurity public class SecSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(final HttpSecurity http) throws Exception { http //... .
For accessing the list of all logged in users you need to inject SessionRegistry instance to your bean. But before injecting session registry you need to define session management part in your spring-security.
According to Spring Security 4.0.0 document: 4.2.4 Logout Handling. The logout element adds support for logging out by navigating to a particular URL. The default logout URL is /logout, but you can set it to something else using the logout-url attribute.
Spring Security provides login and logout features that we can use in our application. It is helpful to create secure Spring application.
First define HttpSessionEventPublisher in web.xml
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
Then define <session-management>
in your spring security.xml file.
Now, use SessionRegistry
in your controller method to invalidate all sessions. Below code retrieves all active sessions.
List<SessionInformation> activeSessions = new ArrayList<SessionInformation>();
for (Object principal : sessionRegistry.getAllPrincipals()) {
for (SessionInformation session : sessionRegistry.getAllSessions(principal, false)) {
activeSessions.add(session);
}
}
On Each active session, you can call expireNow()
method to expire or invalidate them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With