问题描述
我以前从未开发过Chrome扩展程序,目前正在为我的Django驱动的应用程序开发Chrome扩展程序(具有链接提交功能).当我尝试使用扩展名提交链接时,出现以下错误:
I've never developed Chrome extensions before and currently working on the Chrome extension (with link submission functionality) for my Django-powered app. When I try to submit a link using the extension I get the following error:
'POST http://127.0.0.1:8000/add_link_from_extension 403 (FORBIDDEN)'
这可以通过在postdata JSON中传递csrfmiddlewaretoken来解决,但是,显然我做不到
This can be solved by passing csrfmiddlewaretoken in the postdata JSON, however, obviously I can't do
<script>var csrfmiddlewaretoken = "{{ csrf_token }}"</script>
Chrome扩展程序的html文件中的
.您如何将csrf_token从Django传递到Chrome扩展程序的JavaScript?另外,是否还有其他方法可以解决此问题?这是Chrome扩展程序中JS代码的相关部分:
in the html file from Chrome extension. How would you pass csrf_token from Django to Chrome extension's JavaScript? Alternatively, is there any other way around this issue? Here's the relevant portion of the JS code from the Chrome extension:
postdata = {
"url":url.value
//"csrfmiddlewaretoken": csrfmiddlewaretoken
};
$.post('http://' + "127.0.0.1:8000" + '/add_link_from_extension', postdata, success);
推荐答案
您可以尝试使用CSRF令牌设置cookie(请参阅: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax ).或者,只需使用 csrf_exempt
.
You can try to set a cookie with the CSRF token (see: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax). Or, simply decorate your view with csrf_exempt
.
我个人认为这两种方法都不理想.确实,如果要允许通过浏览器扩展之类的工具对网站进行外部访问,则应设置并使用API,尤其是如果要允许任何形式的写访问,则应添加带有OAuth之类的身份验证层. django-tastypie
是一个不错的嵌入式API解决方案,您可以尝试,并且支持开箱即用的OAuth.
Personally, I find both methods sub-optimal. Really, if you're going to allow external access to your site through something like a browser extention, you should set up and use an API, and in particular, if you're going to allow any sort of write access, you should add an authentication layer with something like OAuth. django-tastypie
is a good drop-in API solution you can try, and it supports OAuth out of the box.
这篇关于POST 403禁止在后端使用Django进行Chrome扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!