상세 컨텐츠

본문 제목

최초로그인시 새로고침되는 버그 픽스 | 스프링부트, SpringSecurity6, 지연된 CSRF 토큰 옵트아웃

Project/Meta ESG

by yooputer 2024. 8. 28. 20:52

본문

문제상황

  • 로컬에서는 문제가 없는데, 개발서버나 운영서버에서는 로그인을 2번해야 로그인이 된다
  • 최초로 로그인을 하면 새로고침이 되고, 그 후에 로그인을 하면 로그인이 된다. 

분석

  •  XSRF-TOKEN 쿠키가 존재하면 로그인이 된다.
  •  XSRF-TOKEN이 없는 상태로 로그인을 하면 새로고침된 후 XSRF-TOKEN이 생긴다. 
  •  로그아웃을 하면 XSRF-TOKEN이 사라진다. 
  •  로컬에서는 항상 XSRF-TOKEN이 존재한다. 

문제 해결 과정

1. '왜 최초 로그인 화면에서 CSRF 토큰이 발급되지 않았을까?'

2. 공식 문서에 따르면 CSRF 토큰을 lazy하게 발급하는게 디폴트라고 한다. 
(https://docs.spring.io/spring-security/reference/servlet/exploits/csrf.html#deferred-csrf-token)

3. '아 그러면 모든 요청에 대해 CSRF 토큰을 발급하도록 설정하면 되겠구나!'

@Configuration
@EnableWebSecurity
public class SecurityConfig {
	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		XorCsrfTokenRequestAttributeHandler requestHandler = new XorCsrfTokenRequestAttributeHandler();
		// set the name of the attribute the CsrfToken will be populated on
		requestHandler.setCsrfRequestAttributeName(null);
		http
			// ...
			.csrf((csrf) -> csrf
				.csrfTokenRequestHandler(requestHandler)
			);
		return http.build();
	}
}

 

 

 

 

 

~ 문제 해결 ~ 

관련글 더보기