ajaxのPOST送信で403が返却される場合の対処方法


  • ログイン後、ajaxでPOST送信した時に403が返却される場合、CSRFをリクエストヘッダーに設定すればPOST送信が出来るようになる
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
      xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(function() {
    let token = $("meta[name='_csrf']").attr("content");
    let header = $("meta[name='_csrf_header']").attr("content");
    $(document).ajaxSend(function(e, xhr, options) {
        xhr.setRequestHeader(header, token);
    });
    $(document).off('click', '#hoge').on('click', '#hoge', function() {
        $.ajax({
            type : "post",
            //type : "get",
            url : "api/hoge",
            contentType : "application/json"
        })
        .done( (result) => {
            alert(result.msg);
        })
    })
});
</script>
</head>
<body>
    <input type="button" id="hoge" value="ボタン" />
</body>
<meta th:name="_csrf" th:content="${_csrf.token}"/>
<meta th:name="_csrf_header" th:content="${_csrf.headerName}"/>
</html>