Application property "server.servlet.session.timeout" is not working in Spring Boot project
Asked Answered
W

6

18

According to the documentation of Spring Boot, session timeout can be configured by setting

server.servlet.session.timeout= 300s

in application.properties file. In this post and in Spring Boot documentation it is also said so. But unfortunately this is not working for me.

Is there any other configuration to get expected result?

Worden answered 15/1, 2019 at 6:35 Comment(7)
The server.* properties will only work if you use the embedded container. If you are deploying to Tomcat those won't work as Spring Boot isn't controlling the container.Athletics
@M.Deinum, Can you give me any suggestion about, how can I set session timeout in my project which is currently running on server ?Worden
By including a web.xml or web-fragment.xml and set the session timeout in that way just as you regularly would do.Athletics
@M.Deinum, Can you please give me any reference ?Worden
A reference to what? Just check how you would set the session timeout in a regular web application. That applies here as well.Athletics
@M.Deinum, Where I will have to put web.xml in spring boot project ? In resource folder ?Worden
No as stated in the normal location the WEB-INF folder. It is a regular WAR you are deploying, there is no magic in there.Athletics
W
8

I am posting answer because this scenario is new for me. And I haven't got proper solution step by step. According to the suggestion of M. Deinum I created a web.xml file under WEB-INF folder. Project structure is like

src
 |_ main
     |_ java
     |_ resources
     |_ webapp
         |_ WEB-INF
              |_ web.xml

And in web.xml I configured <session-timeout>...</session-timeout>

My web.xml is like

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">


    <session-config>
        <session-timeout>5</session-timeout>
    </session-config>

</web-app>

And now session time of my webapp in server is working according to my configuration. Thanks goes to M. Deinum

Worden answered 15/1, 2019 at 8:42 Comment(0)
S
10

You can use Approach 1:

server.servlet.session.timeout=30s
server.servlet.session.cookie.max-age=30s

It is working fine for me

Shayn answered 15/1, 2019 at 6:46 Comment(1)
In my case just the cookie max age property was enough.Contemptuous
W
8

I am posting answer because this scenario is new for me. And I haven't got proper solution step by step. According to the suggestion of M. Deinum I created a web.xml file under WEB-INF folder. Project structure is like

src
 |_ main
     |_ java
     |_ resources
     |_ webapp
         |_ WEB-INF
              |_ web.xml

And in web.xml I configured <session-timeout>...</session-timeout>

My web.xml is like

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">


    <session-config>
        <session-timeout>5</session-timeout>
    </session-config>

</web-app>

And now session time of my webapp in server is working according to my configuration. Thanks goes to M. Deinum

Worden answered 15/1, 2019 at 8:42 Comment(0)
R
8

A possible cause for this problem might be using @EnableRedisHttpSession. As explained in this answer:

By using @EnableRedisHttpSession you are telling Spring Boot that you want to take complete control over the configuration of Redis-based HTTP sessions. As a result, its auto-configuration backs off and server.servlet.session.timeout has no effect. If you want to use server.servlet.session.timeout then you should remove @EnableRedisHttpSession. Alternatively, if you want to use @EnableRedisHttpSession then you should use the maxInactiveIntervalInSeconds attribute to configure the session timeout.

Hope this helps someone.

Rebato answered 20/11, 2019 at 14:48 Comment(0)
F
4

server.servlet.session.timeout only works for spring boot embedded container.

If you want to deploy the application to an external container, implement HttpSessionListener and ServletRequestListener.

@Component
public class MyHttpSessionListener implements HttpSessionListener {
    @Value("${server.servlet.session.timeout}")
    Duration sessionTimout;

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        event.getSession().setMaxInactiveInterval((int) sessionTimout.getSeconds());
    }
}

@Component
public class MyServletRequestListener implements ServletRequestListener {
    @Value("${server.servlet.session.timeout}")
    Duration sessionTimout;
    
    @Override
    public  void requestInitialized(ServletRequestEvent sre) {
        HttpSession sh = ((HttpServletRequest) sre.getServletRequest()).getSession(false);

        if (sh != null) {
            long t = sh.getCreationTime();
            long duration = (System.currentTimeMillis() - t) / 1000;

            if (duration > sessionTimout.getSeconds()) {
                sh.invalidate();
            }
        }
    }

}

Flaunt answered 17/7, 2019 at 9:19 Comment(0)
M
1

Follow the below solution.

  1. Set the session time out in application.properties file like below.

    server.servlet.session.timeout=01m
    
  2. Specify the invalid session URL in WebSecurityConfiguration file like below

    http.sessionManagement().invalidSessionUrl("/sessionexpired");
    
  3. Configure the session expired mapping in controller class like below

    @RequestMapping(value = "/sessionexpired", method = RequestMethod.GET)
    public ModelAndView sessionexpired(HttpServletRequest request,
             HttpServletResponse response) {
    
             return new ModelAndView("sessionexpired");
    
    }
    
Maddox answered 23/9, 2022 at 10:39 Comment(0)
B
0

In my case, my app runs on Tomcat server, application.properties set did not work. This one works:

        @Component
        public class SavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
        @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        
                SavedRequest savedRequest = requestCache.getRequest(request, response);
                String userRole = authentication.getAuthorities().stream().findFirst().get().getAuthority();
//see here timeout duration set
                request.getSession().setMaxInactiveInterval(3600);
        
                List<String> permissions = new ArrayList<>();
    ...
    }

and set it to security configure method's

.successHandler()

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private SavedRequestAwareAuthenticationSuccessHandler successHandler;

@Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .authorizeRequests()
                .antMatchers("/rest/api/**", "/logout")
                .authenticated()
                .and()
                .cors()
                .configurationSource(corsConfigurationSource())
                .and()
                .formLogin()
                .failureHandler(new SimpleUrlAuthenticationFailureHandler())
                .successHandler(successHandler)
                .and()
                .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout", HttpMethod.POST.toString()))
                .clearAuthentication(true)
                .invalidateHttpSession(true)
                .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(restAuthenticationEntryPoint)
                .and()
                .csrf()
                .disable();
    }
Brat answered 1/2 at 11:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.