언어 및 프레임워크/SPRING
Spring Boot - Request method 'POST' not supported 에러
개발참치
2021. 10. 17. 17:07
문제
Spring Security 설정한 Spring Boot 환경과 React 서버사이드 환경 연동 중
관련 에러가 발생하였습니다.
분석
Sprign Security는 기본적으로 CSRF에 대한 설정이 필요하므로 일어난 문제입니다.
참고 - CSRF (tistory.com)
해결
Back-end 단위 해결
SecurityConfig.java에 아래와 같이 csrf 토큰을 무시해줄 url을 추가해주시면 됩니다.
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 생략
.and() // 생략 (and는 필요시 )
.csrf()
.ignoringAntMatchers("/member/signup")
.ignoringAntMatchers("/member/signin")
.and() // 생략 (and는 필요시 )
// 생략
}
Front-end 단위 해결
Form 추가로 해결
아래 태그 하나만 추가해도 말끔히 해결이 됩니다.
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
Ajax 설정으로 해결
$.ajax({
url : "/test",
type : "post",
data : data,
beforeSend : function(xhr)
{ /*데이터를 전송하기 전에 헤더에 csrf값을 설정한다*/
xhr.setRequestHeader("${_csrf.headerName}", "${_csrf.token}");
},
success : function(result){