Jon*_*IAR 8 django ajax google-chrome-extension django-csrf csrf-protection
我正在使用最新版本的 Django 和 Django Rest Framework。我的 Web 应用程序提供了一个当前仅由前端使用的 API。
我正在使用相同的 API 路由创建 chrome 扩展。
当我使用本地服务器runserver 命令时,我没有问题。当服务器在 HTTPS 后面运行时,我始终有 403 错误。
{"detail":"CSRF Failed: Referer checking failed - no Referer."}
Run Code Online (Sandbox Code Playgroud)
我使用的视图如下:
@method_decorator(csrf_exempt, name='dispatch')
class ObtainAuthToken(APIView):
permission_classes = (AllowAny,) #maybe not needed in your case
def post(self, request):
username = request.POST['username'].lower()
password = request.POST['password']
user = authenticate(username=username, password=password)
payload = dict()
if user is not None:
token, created = Token.objects.get_or_create(user=user)
payload['token'] = token.key
payload ["success"] = True
else:
payload['error'] = "Credentials not valid or user inactive"
payload ["success"] = False
payload["operation"] = "Obtain Authentication Token"
payload ["timestamp"] = get_timestamp()
return Response(payload)
Run Code Online (Sandbox Code Playgroud)
AJAX 调用如下:
$.ajax({
url: endpoint + "api/1.0/get_auth_token/",
type: 'POST',
// Fetch the stored token from localStorage and set in the header
data: formData,
dataType: "json",
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData:false,
xhrFields: {
withCredentials: false
},
headers: {
'Cache-Control': 'no-cache'
},
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRFToken', csrf_val);
},
success: function(response){
console.log(response);
}
});
Run Code Online (Sandbox Code Playgroud)
奇怪的是,当我使用 Postman 时,它在任何情况下都能完美运行。我将标题设置为相同,但仍然无法使其工作。
谢谢你的帮助
| 归档时间: |
|
| 查看次数: |
630 次 |
| 最近记录: |