csrf().disable() 을 안한 경우
securityConfig.java
http.csrf().disable();
csrf() 사용 예시
head
<meta id="_csrf" name="_csrf" th:content="${_csrf.token}"/>
<meta id="_csrf_header" name="_csrf_header" th:content="${_csrf.headerName}"/>
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
예시 코드
<form class="row login_form" th:action="@{/auth}" id="contactForm" method="post">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
<div class="col-md-12 form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="아이디" onfocus="this.placeholder = ''"
onblur="this.placeholder = 'Username'" pattern="^[a-z0-9]*$" minlength="4" maxlength="16" required>
</div>
<div class="col-md-12 form-group">
<input type="password" class="form-control" id="password" name="password" placeholder="비밀번호" onfocus="this.placeholder = ''"
onblur="this.placeholder = 'Password'" pattern="^\d{4,}(?:[a-z@^*]*)?$" minlength="4" maxlength="16" required>
</div>
<div class="col-md-12 form-group">
<div class="creat_account">
<input type="checkbox" id="f-option2" name="selector">
<label for="f-option2">Keep me logged in</label>
</div>
</div>
<div class="col-md-12 form-group">
<button type="submit" value="submit" class="button button-login w-100">Log In</button>
<a href="#">Forgot Password?</a>
</div>
</form>
ajax 에서 데이터 전송할 때
const token = $("meta[name='_csrf']").attr("content")
const header = $("meta[name='_csrf_header']").attr("content");
beforeSend: function (xhr) {
xhr.setRequestHeader(header, token);
}
예시 코드
$("#idCheckBtn").click(function(){
if($("#id").val()==""){
alert("아이디를 입력하지 않으셨습니다.");
$("#id").focus();
return;
}
const token = $("meta[name='_csrf']").attr("content")
const header = $("meta[name='_csrf_header']").attr("content");
var test = {name : $("#id").val()}
$.ajax({
url:"/common/idCheck",
type:"post",
data:JSON.stringify(test),
dataType:"json",
contentType: "application/json",
cache: false,
success:function(result){
console.log(result);
var idChk = result;
if(idChk==false){
$("#idCheck").val("false");
$("#msg").html("<strong style='color:red'>기존에 사용되고 있는 아이디 입니다. 다시 입력하시기 바랍니다.</strong>");
$("#id").focus();
} else if(idChk==true){
$("#idCheck").val("true");
$("#msg").html("<strong style='color:blue'>사용가능한 아이디 입니다.</strong>");
} else if(idChk==""){
$("#msg").html("<strong>아이디가 확인되지 않았습니다. 다시 시도해주시기 바랍니다.</strong>");
}
},
beforeSend: function (xhr) {
xhr.setRequestHeader(header, token);
},
});
});