spring-boot security csrf를 사용하는 경우 데이터 입력

오세훈·2023년 11월 11일
0

spring-boot

목록 보기
2/7

csrf().disable() 을 안한 경우

securityConfig.java

// csrf를 사용할 경우 주석처리, 
// 사용하지 않을 경우 아래와 같은 코드를 추가
http.csrf().disable();

csrf() 사용 예시

<!-- csrf -->
        <meta id="_csrf" name="_csrf" th:content="${_csrf.token}"/>
        <meta id="_csrf_header" name="_csrf_header" th:content="${_csrf.headerName}"/>

form 에서 데이터 전송할 때

<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 에서 데이터 전송할 때

// scrf token 정보 추가
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;
  }
  // scrf token 정보 추가
  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;	//true 또는 false를 받음
      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);
    },
  });
});
profile
자바 풀 스택 주니어 개발자

0개의 댓글