我正在制作一个网站,前面是业务,但后面都是 Django。 Django 是我关心的。
每个请求都需要一个 CSRF 令牌。其实就是两个令牌。一个由 cookie 自动设置,另一个必须作为 POST 参数提供。
所以我有一个发送令牌的 API 端点。然后我使用该令牌来发出其他请求。
但这感觉就像有一个警卫,没有密码就不让你进去,但如果你向他要密码,他会很乐意告诉你密码。这对谁有帮助?
编辑:我希望这不会太尴尬,我对这些工具很陌生。
姜戈:
def initialize(request):
"""
Queried by the front end when the page first loads.
Sends back csrf_token, which is needed by all POST requests (this one uses GET), and user name associated with the
current request - that is, the user that's logged in.
"""
data = dict()
data['csrf_token'] = get_token(request)
data['logged_in_user_name'] = auth.get_user(request).get_username()
return HttpResponse(json.dumps(data), status = status.HTTP_200_OK)
反应/Redux:
var csrfToken = null as null | string;
/**
* This function fetches the CSRF token that is necessary for POST requests from the server.
* Also gets the logged-in user name and adds it to the state.
*
* @param dispatch A function that updates the store by dispatching an action.
*/
export async function initializeCsrf(dispatch: Dispatch)
{
if (csrfToken)
{
return csrfToken;
}
try
{
const response = await fetch(`${Ernots.APIURLPrefix}initialize`,
{
method: 'GET',
mode: 'cors',
credentials: 'include',
});
var json = await response.json();
csrfToken = json.csrf_token;
dispatch(loginActions.setLoggedInUserName(json.logged_in_user_name));
dispatch(requestActions.setBackendUnreachable(false));
return csrfToken;
}
catch(e)
{
dispatch(requestActions.setBackendUnreachable(true));
}
}
您无法将密码提供的保护与 CSRF 保护令牌进行比较。