WindsomeProject - ajax 요청 시 무반응

박민수·2023년 12월 12일
0

WindsomeProject

목록 보기
2/32
post-thumbnail

아이디 중복검사를 위해 AJAX를 통해 서버로 데이터를 전송하려고 시도했으나, 서버에 데이터가 전달되지 않았다. Spring Security에서 모든 권한을 허용해 줬음에도 불구하고 계속해서 403 에러가 발생했다.

확인해 본 결과 CSRF 토큰이 누락된 것이 문제였다.

따라서 AJAX 요청을 보내기 전에 헤더에 CSRF 토큰을 담아서 요청하니 데이터가 정상적으로 전달되었다.

@Bean
protected SecurityFilterChain configure(HttpSecurity http) throws Exception {
        http
			.csrf(AbstractHttpConfigurer::disable)
            .authorizeHttpRequests(auth -> auth
				.requestMatchers(
					new AntPathRequestMatcher("/"),
					new AntPathRequestMatcher("/login"),
					new AntPathRequestMatcher("/join"),
					new AntPathRequestMatcher("/join/**"),
					new AntPathRequestMatcher("/css/**"),
										new AntPathRequestMatcher("/imgs/**"),
					new AntPathRequestMatcher("/js/**"),
					new AntPathRequestMatcher("/h2-console/**"),
					new AntPathRequestMatcher("/profile")
				).permitAll()
				.anyRequest().authenticated())
			.logout((logout) -> logout
				.logoutSuccessUrl("/"));
	return http.build();
}
<script>
	//아이디 중복검사
	$('.id_input').on("propertychange change keyup paste input", function() {
		const memberId = $('.id_input').val();
		const data = {memberId : memberId}

		$(function () {
			var token = $("input[name='_csrf']").val();
			var header = "X-CSRF-TOKEN";
			$(document).ajaxSend(function(e, xhr, options) {
				xhr.setRequestHeader(header, token);
			});
		});

		$.ajax({
			type: "POST",
			url: "/join/memberIdChk",
			data: data
		})
	})
</script>
profile
안녕하세요 백엔드 개발자입니다.

0개의 댓글

관련 채용 정보