Spring

Spring Boot Jwt인증시 static 리소스 CSRF토큰 재발급 문제

Gil Granger 2019. 6. 11. 11:09

세션이 아닌 JWT인증서버를 구축하여 CSRF방지를 포함한 로그인을 개발하는 도중 이슈가 발생된 일이다.

로그인성공하여 인증된 상태로 form으로 post요청을 할 경우 csrf토큰이 불일치 하는경우가 발생 하였다.

페이지를 로딩할때 정직인 리소스들의 요청들이 csrf토큰을 다시 generate하고 있었던 것이다.

디버그로 추척을 해보았더니 SessionManagementFilter에서  

SessionManagementFilter

sessionAuthenticationStrategy (CompositeSessionAuthenticationStrategy)를 보면 CsrfAuthenticationStrategy를 포함하고 있다는것을 알 수 있다.

CsrfAuthenticationStrategy

 

CsrfAuthenticationStrategy는 onAuthentication메소드에서 토큰여부를 체크하여 생성하고 있다.

 

정리하자면 정적인 리소스들의 요청들이 필터를 거쳐서 csrf토큰을 재생성하고 있었던 것이다.

 

이런 정책들이 config된 이유는  

WebSecurityConfigurerAdapter에 STATELESS SESSOIN으로 설정해 놓았기 때문이다.

SessionManagementConfigurer
SessionManagementConfigurer
SessionManagementFilter

이 같이 설정할 경우 NullSecurityContextRepositroy으로 가져가게 되므로 SecurityContext를 가지고 있지 않다는 조건으로 매번 확인하게 된다. (맨 위 SessionManagementFilter 이미지 참조)

 

즉 세션을 사용하고 있지 않는대 Jwt 인증 Filter를 통해서 매요청마다 인증을 하여 SecurityContext를 세션이 아닌 SecurityContextHolder(Threadlocal)에 저장하고 있어서 발생하는 문제이다.

 

 

 

 

설명은 약간 장황하게 했지만 이 이슈에 대해 아주 간단한 설정으로 해결했다.

jwt필터를 기존에 UsernamePasswordAuthenticationFilter 다음으로 위치해 놓았는데,

ExceptionTranslationFilter 이전으로 위치해서 인증을 하기 전에 SessionManagementFilter가 먼저 처리하도록 수정하였다.