POST 403 Forbidden for Chrome extension with Django 在后端 [英] POST 403 Forbidden for Chrome extension with Django on the backend

查看:34
本文介绍了POST 403 Forbidden for Chrome extension with Django 在后端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前从未开发过 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 Forbidden for Chrome extension with Django 在后端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆