Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable session and set session timeout in Spring Security

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.

like image 248
raju vaishnav Avatar asked Apr 22 '16 13:04

raju vaishnav


2 Answers

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()); } 
like image 170
munilvc Avatar answered Sep 28 '22 19:09

munilvc


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> 
like image 33
raju vaishnav Avatar answered Sep 28 '22 20:09

raju vaishnav