Phoenix CSRF令牌不匹配 [英] Phoenix CSRF token not matching
问题描述
试图让Ajax在Phoenix上工作.我通过执行以下操作获得了csrf令牌,所以我拥有了它:
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() %>">
然后像这样使用它:
$.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);
}
});
问题是我获得的令牌不是正确的令牌.看着谷歌浏览器检查器,我得到一个403请求,说有一个无效的csrf令牌.有效的会话令牌始终不同于它给我的令牌.得到这样的东西IiJndz5FeV9MMhIKMzggUTtmHUALAAAAkJ/6Yr/k4BxdiKmiaMUqsw==
通常它想要这样的东西hHAg7V4xpjnZsM8Z+H1xw==
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?
我也尝试了以下方法:
Plug.Conn.get_session(conn, :csrf_token)
Map.get(conn.req_cookies, "_csrf_token")
两者都不会返回任何内容.
Both result in nothing being returned.
推荐答案
请求可以通过密钥"_csrf_token"的参数或名称为"x-csrf-token"的标头发送令牌.
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
这篇关于Phoenix CSRF令牌不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!