본문 바로가기

FrontEnd/Javascript

Fetch API & 스프링 시큐리티 CSRF

1. FetchAPI로 AJAX로 보낼때. 

-> 이 예제에서 타임리프를 적용하여 가져왔음

-> head에 meta정보를 넣어주고  fetch API 보낼때 header에 넣어서 전송.

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta id="_csrf" name="_csrf" th:content="${_csrf.token}"/>
    <meta id="_csrf_header" name="_csrf_header" th:content="${_csrf.headerName}"/>
    <title>Title</title>
<script>
    const header = document.querySelector('meta[name="_csrf_header"]').content;
    const token = document.querySelector('meta[name="_csrf"]').content;
    const byFetch = () => {
        fetch("http://localhost:8080/hi", {
            method: "POST",
            headers: {
                'header': header,
                "Content-Type": "application/json",
                'X-CSRF-Token': token
            },
            body: JSON.stringify({
                title: "hello"
            }),
        })
            .then((response) => response.json())
            .then((data) => console.log(data));
    };

</script>
</head>
<body>
    <h1>dashboard</h1>
    
    <input type="button" value="fetch" onclick="byFetch()">

</body>

</html>

 

2. 만약 폼태그로 보낸다면 스프링 시큐리티가 <input hidden>으로 csrf 토큰을 넣어준다. 

 

 

출처

Fetch API

DaleSeo: https://www.daleseo.com/js-window-fetch/

생활코딩: https://www.youtube.com/watch?v=ufjCFdG_4fo

sisiblog: https://sisiblog.tistory.com/261

 

CSRF

kimujin99.log: https://velog.io/@kimujin99/Side-project-Spring-Security-CSRF-Token-%ED%99%9C%EC%9A%A9%ED%95%98%EA%B8%B01

그날그날메모: https://memo-the-day.tistory.com/145

혼자 깨닫기 위함: https://twoline.tistory.com/37