I am new to Spring Security and I am working on a login, logout, and session timeout feature. I have configured my code by referring to this document. My code looks below:
@Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/admin/**") .access("hasRole('ROLE_USER')").and().formLogin() .loginPage("/login").failureUrl("/login?error") .usernameParameter("username") .passwordParameter("password") .and().logout().logoutSuccessUrl("/login?logout").and().csrf(); http.sessionManagement().maximumSessions(1).expiredUrl("/login?expired"); }
Override the class AbstractSecurityWebApplicationInitializer
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer { @Override public boolean enableHttpSessionEventPublisher() { return true; } }
I need clarification on whether I am doing it right, if it looks good, then where I need to setup the session timeout. I am doing it fully based on annotation.
If you are using JavaConfig and do not want to use XML you can create a HttpSessionListener
and use getSession().setMaxInactiveInterval()
, then in the Initializer
add the listener in onStartup()
:
public class SessionListener implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent event) { System.out.println("session created"); event.getSession().setMaxInactiveInterval(15); } @Override public void sessionDestroyed(HttpSessionEvent event) { System.out.println("session destroyed"); } }
Then in the Initializer:
@Override public void onStartup(ServletContext servletContext) throws ServletException { super.onStartup(servletContext); servletContext.addListener(new SessionListener()); }
I was able to solve above issue by adding below config in web.xml only. any better way will be accepted.
<session-config> <session-timeout>20</session-timeout> </session-config>
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