Phoenix CSRF token not matching

怎甘沉沦 提交于 2020-01-05 05:26:14

问题


Trying to get ajax working the Phoenix. I get the csrf token by doing the following so i have it:

<input type="hidden" id="_csrf_token"  name="_csrf_token" value="<%= get_csrf_token() %>">

Then use it like so:

$.ajax({
  type: "POST",
  url: "<%= lesson_path @conn, :create %>",
  beforeSend: function(xhr)
  {
    token = $('#_csrf_token').val();
    xhr.setRequestHeader('_csrf_token', token );
  },
  data: data,
  success: function(data, textStatus, jqXHR) {
    alert(textStatus);
  }
});

The issue is that the token i get is not the correct token. Looking at the google chrome inspector I get a 403 on the request saying that there is an invalid csrf token. The valid session token is always different than the token it gives me. Get something like this IiJndz5FeV9MMhIKMzggUTtmHUALAAAAkJ/6Yr/k4BxdiKmiaMUqsw== it usually wants something like this hHAg7V4xpjnZsM8Z+H1xw==

Any idea why I would be getting a different token than what it wants?

I have tried the following as well:

Plug.Conn.get_session(conn, :csrf_token)
Map.get(conn.req_cookies, "_csrf_token")

Both result in nothing being returned.


回答1:


The token may be sent by the request either via the params with key “_csrf_token” or a header with name “x-csrf-token”.

Try set your header with key:

x-csrf-token



回答2:


Thanks. Took me hours. I ended up with:

<div class="form-group">
  <form id="number" name="number" method="post">
    <meta name="csrf" content="<%= Plug.CSRFProtection.get_csrf_token() %>">
    <input id="_csrf_token" name="_csrf_token"
       type="hidden" value="<%= Plug.CSRFProtection.get_csrf_token() %>">
    <%= text_input :blocks, :num, value: "" %>
    <%= submit "Submit", id: "submit", class: "btn btn-primary" %>
  </form>
</div>

<script>
  var csrf = document.querySelector("meta[name=csrf]").content;

  $.ajax({
    url: "/posts",
    type: "post",
    data: {
      post: { title: post } })
    },
    headers: {
        "X-CSRF-TOKEN": csrf
    },
    dataType: "json",
    success: function (data) {
      console.log(data);
    }
  });
</script>

I don't know whether the X-CRSF-TOKEN header or the _csrf_token parameter are necessary, or both, so I'll try to find out by trial and error.



来源:https://stackoverflow.com/questions/39863118/phoenix-csrf-token-not-matching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!