2017-12-16 7 views
2

내 아약스 호출은 처음에는 작동했지만 두 번째에는 작동하지 않고 다음과 같은 결과를 반환합니다. 요청한 동작은 허용되지 않습니다. 상태 코드가 아래AJAX는 codeigniter에서 두 번째로 csrf 토큰 문제가 작동하지 않습니다.

컨트롤러 방법 403 금지 콘솔 헤더 ..

public function authenticate() { 
    echo json_encode('sachin'); 
} 

jQuery를 기능

$("#adminFrmSubmitBtn").on('click',function(){ 
    if($("#admin_login_frm").valid()){ 
     var frmData=$(this).closest('form').serialize(); 
     frmData+='&'+$.param({'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'}); 
     $.ajax({ 
      url:'<?php echo base_url('login/authenticate12'); ?>',//$(this).closest('form').attr('action'), 
      method:$(this).closest('form').attr('method'), 
      data:frmData, 
      success:function(response){ 
       console.log(response); 
      } 
     }); 
    }else{ 
     return false; 
    } 
}); 

html로 코드

<form action="<?php echo base_url('login/authenticate'); ?>" method="post" name="admin_login_frm" id="admin_login_frm">    
     <input type="text" name="user_name" class="form-control" placeholder="Email"> 
     <input type="password" name="user_password" class="form-control" placeholder="Password"> 
     <button type="button" class="btn btn-primary btn-block btn-flat" > 
</form> 
+0

'$ config [ 'csrf_regenerate']'의 설정 값은 무엇입니까? –

+0

CSRF로 무엇을 아카이브하려고합니까 ?? –

+0

[이 포럼 답변은 json 응답으로 새 CSRF 토큰을 전달하고 CSRF의 숨김 필드 및 다음 ajax 호출의 사용자 이름을 업데이트 할 것을 제안합니다.] (https://forum.codeigniter.com/thread-61278-post-327081) .html # pid327081) – ourmandave

답변

1

새로운 CSRF 토큰을 얻으려면. Codeigniter가 CSRF 토큰을 쿠키에 저장하기 때문에 Javascript를 사용하여 쿠키를 얻어야합니다.

보기 (.php) 파일에 아래 코드를 입력하십시오.

<script type="text/javascript"> 

    function get_cookie(cname) { //using this function we can get cookie 
     var name = cname + "="; 
     var ca = document.cookie.split(';'); 
     for(var i=0; i<ca.length; i++) { 
      var c = ca[i]; 
      while (c.charAt(0)==' ') c = c.substring(1); 
      if (c.indexOf(name) == 0) return c.substring(name.length,c.length); 
     } 
     return ""; 
    } 

    $.ajax({ 
     type: "POST", 
     url: "YOUR-URL", 
     data: {"<?php echo $this->security->get_csrf_token_name(); ?>":csrf_token}, //Add your data which you want to post 
     dataType: "json", 
     success: function(resp){    
     }, 
     error: function(jqXHR, textStatus, errorThrown){ 
      alert('Something is wrong'); 
      window.location.reload(); 
     } 
    }); 

</script>