programing

스프링 부트 세션 시간 초과

starjava 2023. 9. 4. 19:30
반응형

스프링 부트 세션 시간 초과

server.session-timeout내장된 Tomcat에서만 작동하는 것 같습니다.

세션 최대 간격 시간을 확인하기 위해 로그 문을 넣었습니다.Tomcat에 war 파일을 수동으로 배포한 후 기본 세션 시간 초과 값(30분)이 여전히 사용되고 있음을 알게 되었습니다.

spring-boot(내장된 Tomcat용이 아니라 독립 실행형 애플리케이션 서버용)으로 세션 시간 초과 값을 설정하려면 어떻게 해야 합니까?

[누군가 이것이 유용하다고 생각할 경우를 대비하여]

Spring Security를 사용하는 경우 SimpleUrlAuthentication을 확장할 수 있습니다.SuccessHandler 클래스를 지정하고 인증 성공 처리기에서 세션 시간 초과를 설정합니다.

public class NoRedirectSavedRequestAwareAuthenticationSuccessHandler
       extends SimpleUrlAuthenticationSuccessHandler {

    public final Integer SESSION_TIMEOUT_IN_SECONDS = 60 * 30;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication)
                                        throws ServletException, IOException {

        request.getSession().setMaxInactiveInterval(SESSION_TIMEOUT_IN_SECONDS);

        // ...
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .anyRequest()
            .authenticated()
            .and()
            .formLogin()
            .loginProcessingUrl("/login")
            .successHandler(new NoRedirectSavedRequestAwareAuthenticationSuccessHandler())
            .failureHandler(new SimpleUrlAuthenticationFailureHandler())
            .and().httpBasic();
    }

}

독립 실행형 서버에 Spring Boot 앱을 배포할 때 세션 시간 초과 구성은 다른 전쟁 배포에서와 동일한 방식으로 수행됩니다.

Tomcat의 경우 세션 시간 초과를 설정할 수 있습니다.maxInactiveInterval의 관리자 요소 속성server.xml또는 를 사용합니다.session-timeout요소가 web.xml에 있습니다.첫 번째 옵션은 Tomcat 인스턴스에 배포된 모든 앱에 영향을 미칩니다.

당신은, 제가 알고 있듯이, 서블릿 API나 Spring API에서 세션 시간 제한을 설정하기 위한 직접적인 호출이 없다는 것을 발견했습니다.그것의 필요성은 여기저기서 논의되고 있지만, 아직 해결되지 않았습니다.

당신이 원하는 것을 할 수 있는 우회적인 방법이 있습니다.세션의 시간 초과를 설정하는 세션 수신기를 구성할 수 있습니다.코드 예제가 포함된 기사를 http://fruzenshtein.com/spring-java-configuration-session-timeout 에서 발견했습니다.

그게 도움이 되길 바랍니다.

세션 제한 시간을 설정하는 방법을 보여주는 Justin의 답변을 기반으로 합니다.AuthenticationSuccessHandlerSpring Security를 사용하여, 저는 다음을 만들었습니다.SessionTimeoutAuthSuccessHandler:

public class SessionTimeoutAuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
  public final Duration sessionTimeout;

  public SessionTimeoutAuthSuccessHandler(Duration sessionTimeout) {
    this.sessionTimeout = sessionTimeout;
  }

  @Override
  public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication auth) throws ServletException, IOException {
    req.getSession().setMaxInactiveInterval(Math.toIntExact(sessionTimeout.getSeconds()));
    super.onAuthenticationSuccess(req, res, auth);
  }
}

사용 중:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .anyRequest().authenticated()
      .and().formLogin().loginPage("/login")
      .successHandler(new SessionTimeoutAuthSuccessHandler(Duration.ofHours(8))).permitAll()
      .and().logout().logoutUrl("/logout").permitAll();   
  }
...
}

확장 대상 편집SavedRequestAwareAuthenticationSuccessHandler보다는SimpleUrlAuthenticationSuccessHandler재인증 후 원래 요청이 손실되지 않도록 보장합니다.

application.properties에서

#session timeout (in secs for spring, in minutes for tomcat server/container)
server.session.timeout=1

나는 그것을 테스트하고 일하고 있습니다!톰캣이 몇 분 안에 부동산을 가져간 것으로 밝혀졌습니다.

사용하다HttpSessionListener

@Configuration
public class MyHttpSessionListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent event) {
        event.getSession().setMaxInactiveInterval(30);
    }
}

@Ali 답변을 보완하여 다음을 만들 수도 있습니다.session.timeout변수가 있는 변수application.yml파일로 작성하여 수업에 사용합니다.이것은 Spring Boot war 및 외장 Tomcat과 잘 작동할 것입니다.

application.yml

  session:
    timeout: 480 # minutes

세션 수신기(사용)@Configuration주석)

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
class SessionListener implements HttpSessionListener {

    @Value("${session.timeout}")
    private Integer sessionTimeout;

    @Override
    public void sessionCreated(HttpSessionEvent event) {
        event.getSession().setMaxInactiveInterval(sessionTimeout);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent event) {}

}

사용한ServletContextInitializer

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
@Configuration
public class MyServletContextInitializer implements ServletContextInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.setSessionTimeout(1);
    }
}

언급URL : https://stackoverflow.com/questions/28103852/spring-boot-session-timeout

반응형