标签: django-cors-headers

CORS:当credentials标志为true时,无法在Access-Control-Allow-Origin中使用通配符

我有一个涉及的设置

前端服务器(Node.js,domain:localhost:3000)<--->后端(Django,Ajax,域:localhost:8000)

浏览器< - webapp < - Node.js(服务应用)

浏览器(webapp) - > Ajax - > Django(服务ajax POST请求)

现在,我的问题在于CORS设置,webapp使用它来向后端服务器进行Ajax调用.在chrome中,我一直在努力

当credentials标志为true时,无法在Access-Control-Allow-Origin中使用通配符.

在Firefox上也不起作用.

我的Node.js设置是:

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:8000/');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
};
Run Code Online (Sandbox Code Playgroud)

而在Django我使用这个中间件 与此相伴

webapp发出如下请求:

$.ajax({
    type: "POST",
    url: 'http://localhost:8000/blah',
    data: {},
    xhrFields: {
        withCredentials: true
    },
    crossDomain: true,
    dataType: 'json',
    success: successHandler
});
Run Code Online (Sandbox Code Playgroud)

因此,webapp发送的请求标头如下所示:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept"
Access-Control-Allow-Methods: 'GET,PUT,POST,DELETE'
Content-Type: application/json 
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: …
Run Code Online (Sandbox Code Playgroud)

django ajax node.js cors django-cors-headers

254
推荐指数
7
解决办法
36万
查看次数

AngularJS + Django Rest Framework + CORS(CSRF Coo​​kie未显示在客户端)

我正在使用和Django Rest Framework + Django CORS Headers在AngularJS中开发一个1页的应用程序.

我的问题是,当我联系后端时,"csrftoken"cookie永远不会出现在我的浏览器中.

例如:我正在使用帖子进行登录.我正确地获得了"sessionid"cookie,但是"csrftoken"从未出现,因此我无法从我的客户端发出适当的帖子,因为我因为缺少csrf令牌而被拒绝.

  • 我已经分析了API的响应头,而csrftoken则不然.
  • 我直接在其余的API浏览器中查看,它显示在那里很好.
  • 只是要指出,我可以做我的第一个POST登录,因为Django Rest Framework只强制CSRF用于经过身份验证的用户.如果我尝试重新登录它将失败,因为它出现了"sessionid"-cookie.
  • 我并没有试图绕过CSRF保护,就像stackoverflow上的一些帖子所暗示的那样.

前/后端的一些代码片段.这些是未完成的片段,所以不要挂在写得不好的代码上.

后端API LoginView

class LoginView(APIView):

renderer_classes = (JSONPRenderer, JSONRenderer)

def post(self, request, format=None):
    serializer = LoginSerializer(data=request.DATA)

    if serializer.is_valid():
        userAuth = authenticate(username=serializer.data['username'], password=serializer.data['password'])

        if userAuth:

            if userAuth.is_active:
                login(request, userAuth)

                loggedInUser = AuthUserProfile.objects.get(pk=1)
                serializer = UserProfileSerializer(loggedInUser)

                user = [serializer.data, {'isLogged': True}]



        else:
            user = {'isLogged': False}

        return Response(user, status=status.HTTP_200_OK)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Run Code Online (Sandbox Code Playgroud)

客户端AngularJS登录控制器

.controller('LoginCtrl', ['$scope', '$http', 'uService', '$rootScope', function(scope, $http, User, rootScope) {

scope.login = function() { …
Run Code Online (Sandbox Code Playgroud)

django cors angularjs django-rest-framework django-cors-headers

33
推荐指数
4
解决办法
3万
查看次数

导入错误django corsheaders

我是django的初学者.我正在做基于它的项目.项目有两个阶段.我完成了第一阶段并将代码上传到amazon ec2实例.在完成第二阶段后,我加入一些包等python-social-auth,django-cors-headers,django-easy-maps,crispyforms.但是现在它显示了corsheaders的导入错误,这个我已经检查了虚拟环境和corsheaders包的追溯

Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 242, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 280, in execute
translation.activate('en-us')
File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/__init__.py", line 130, in activate
return _trans.activate(language)
File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 188, in activate
_active.value = translation(language)
File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line 177, in translation
default_translation = _fetch(settings.LANGUAGE_CODE)
File "/usr/local/lib/python2.7/dist-packages/django/utils/translation/trans_real.py", line …
Run Code Online (Sandbox Code Playgroud)

python django amazon-ec2 django-cors-headers

24
推荐指数
4
解决办法
4万
查看次数

django-cors-headers不起作用

django-cors-headers不起作用

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.gis',
    'corsheaders',
    'rest_framework',
    'world',
    'userManager',
    'markPost',
    'BasicServices',
)


MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
Run Code Online (Sandbox Code Playgroud)

一切都很正常,但没有奏效

这里我的回复标题

Cache-Control: max-age=0
Content-Type: text/html; charset=utf-8
Date: Tue, 20 Jan 2015 13:16:17 GMT
Expires: Tue, 20 Jan 2015 13:16:17 GMT
Last-Modified: Tue, 20 Jan 2015 13:16:17 GMT
Server: WSGIServer/0.1 Python/2.7.8
Set-Cookie: csrftoken=snXksqpljbCLW0eZ0EElFxKbiUkYIvK0; expires=Tue, 19-Jan-2016 13:16:17 GMT; Max-Age=31449600; Path=/
Vary: Cookie
X-Frame-Options: SAMEORIGIN
Run Code Online (Sandbox Code Playgroud)

python django django-cors-headers

19
推荐指数
7
解决办法
2万
查看次数

Django Python休息框架,在Chrome中请求的资源上没有'Access-Control-Allow-Origin'标头,在firefox中工作

我在同一个问题上研究并阅读了不少Stackoverflow帖子.没有人解决我的问题.

我的问题是我的控制台中出现了"... No'Access-Control-Allow-Origin'标头出现在所请求的资源上......"错误.

我在用:

Chrome版本57.0.2987.133 Firefox版本52.0.2

Python 2.7 Django 1.11a1

AngularJS

我正在使用MAMP来提供我的前端Angular内容,以及用于后端内容的django服务器.

在我的django设置中,我已经包含了cors中间件,并尝试了白名单方法并将所有设置为true:

MIDDLEWARE = [

    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

]

CORS_ORIGIN_ALLOW_ALL = True
Run Code Online (Sandbox Code Playgroud)

在谷歌浏览器上我仍然收到此错误:

localhost /:1 XMLHttpRequest无法加载{my endpoint url}.已从{my endpoint url}重定向到{my endpoint url with a}已被CORS策略阻止:请求的资源上没有"Access-Control-Allow-Origin"标头.因此,不允许原始{request url}访问.

它适用于Firefox,我无法弄清楚为什么它不适用于谷歌浏览器.我还没有尝试过任何其他类型的浏览器.非常感谢任何帮助,谢谢.

python django google-chrome django-rest-framework django-cors-headers

15
推荐指数
4
解决办法
2万
查看次数

Django/DRF - 405 DELETE操作不允许使用方法

我正在使用本地计算机上的两台开发服务器(node&django).

我已经添加django-cors-headers到项目中以允许所有来源和方法(在dev上)具有以下设置:

CORS_ORIGIN_ALLOW_ALL = 'ALL'
CORS_ALLOW_METHODS = (
        'GET',
        'POST',
        'PUT',
        'PATCH',
        'DELETE',
        'OPTIONS'
    )
Run Code Online (Sandbox Code Playgroud)

尝试DELETE时我得到405.查看响应标头

HTTP/1.0 405 METHOD NOT ALLOWED
Date: Mon, 03 Nov 2014 10:04:43 GMT
Server: WSGIServer/0.1 Python/2.7.5
Vary: Cookie
X-Frame-Options: SAMEORIGIN
Content-Type: application/json
Access-Control-Allow-Origin: *
Allow: GET, POST, HEAD, OPTIONS
Run Code Online (Sandbox Code Playgroud)

请注意,DELETE&PATCH/ PUT不在允许的方法列表中.

我的配置中是否缺少某些内容?

django cors django-rest-framework django-cors-headers

14
推荐指数
2
解决办法
1万
查看次数

CORS 在 Django 中不起作用,但设置似乎正确

我正在尝试从不同子域上的 React Native Web 前端对 Django 进行 POST 调用。

我以为我已经正确配置了 CORS,但事实似乎并非如此。

这是我的 Django settings.py 的样子:

CORS_ALLOW_CREDENTIALS = True

CORS_ALLOW_HEADERS = ['*']

CORS_ALLOWED_ORIGINS = ['https://api.example.com', 'https://example.com', 'https://www.example.com' ]

CSRF_TRUSTED_ORIGINS = [
    'https://api.example.com', 'https://example.com', 'https://www.example.com'
]

ALLOWED_HOSTS = ["0.0.0.0", "api.example.com", "example.com"]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
]

INSTALLED_APPS = [
     ...
    'corsheaders',
     ...
]
Run Code Online (Sandbox Code Playgroud)

我到底做错了什么?我收到的错误是这样的:

Access to XMLHttpRequest at 'https://api.example.com/api/v1/pagescreate/' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the …
Run Code Online (Sandbox Code Playgroud)

python django http cors django-cors-headers

11
推荐指数
2
解决办法
1万
查看次数

Django Localhost CORS无法正常工作

我有一个本地Django设置如下

Django Rest Framework:localhost:8000

AngularJS frontend:local apache running on http://localservername

我安装了django-cors-headers,在我的settings.py,我设置了我的

CORS_ORIGIN_WHITELIST = (
    'http://localhost',
    'localservername',
    'http://localservername',
    '127.0.0.1'
)


MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
Run Code Online (Sandbox Code Playgroud)

但是,No 'Access-Control-Allow-Origin' header is present on the requested resource.每当我点击任何API时,我都会收到错误Rest Framework.如果我设置了CORS_ORIGIN_ALLOW_ALL = True,那么API的工作正常,但对我的服务器端数据来说是非常不安全的.

我需要更改什么来解决这个问题?

python django cors angularjs django-cors-headers

10
推荐指数
2
解决办法
7300
查看次数

尝试在 settings.py 文件中设置 corsheaders 时

(corsheaders.E014) CORS_ORIGIN_WHITELIST 中的 Origin ' http://localhost:4200/ ' 不应该有路径。我收到此错误。

CORS_ORIGIN_WHITELIST = (' http://localhost:4200/ ',)

CORS_ORIGIN_WHITELIST 中的Origin ' http://localhost:4200/ ' 不应该有路径。我收到此错误。

django django-cors-headers

10
推荐指数
1
解决办法
5320
查看次数

iOS 和 Android 应用程序应使用什么 CORS 策略?

我正在构建一个供 iOS/Android 应用程序使用的 API。该应用程序使用 JSON Web Token 对用户进行身份验证。当我尝试从本机应用程序与 API 进行交互时,我遇到了 CORS 问题。因此,我为所有来源添加了 CORS 标头(仅适用于以 开头的 url /api/)。现在工作正常,但我想知道我所做的是否不是一个潜在的漏洞?

我应该允许所有来源吗?如果本机应用程序要请求 API,有什么方法可以提前知道 Origin 主机?

我很困惑。在此先感谢您的帮助。

api rest cors django-rest-framework django-cors-headers

8
推荐指数
1
解决办法
7666
查看次数