본문 바로가기
front-end/script

[jQuery] form 또는 ajax post 요청 시 csrf token 설정

by moonsiri 2021. 11. 4.
728x90
반응형

https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html

 

Cross-Site Request Forgery Prevention - OWASP Cheat Sheet Series

Cross-Site Request Forgery Prevention Cheat Sheet Introduction Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious web site, email, blog, instant message, or program causes a user's web browser to perform an unwanted action

cheatsheetseries.owasp.org

 

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>

<head>

    <sec:authorize access="isAuthenticated()">
        <!-- csrf 처리 -->
        <sec:csrfMetaTags />
        <script>
            try {
                let csrfParameter = $("meta[name='_csrf_parameter']").attr("content");
                let csrfHeader = $("meta[name='_csrf_header']").attr("content");
                let csrfToken = $("meta[name='_csrf']").attr("content");

                // ajax가 호출 되는 전역
                $.ajaxSetup({
                    beforeSend: function(xhr, settings) {
                        if (!/^(GET|HEAD|OPTIONS)$/i.test(settings.type) && !this.crossDomain) {
                            xhr.setRequestHeader(csrfHeader, csrfToken)
                        }
                    }
                });

                // form
                $("form").each(function() {
                    let input = $("<input/>").attr({name:csrfParameter, type:"hidden", value:csrfToken});
                    $(this).append(input);
                });
            } catch(e) {
                console.log(e);
            }
        </script>
        <!-- csrf 처리 -->
    </sec:authorize>
</head>
728x90
반응형

댓글