我已经为url'localhost:8000/api/posts'进行了令牌身份验证,根据django-cors头库,我还更改了settings.py文件。这是我的settings.py文件,
INSTALLED_APPS = [
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'rest_framework',
'rest_framework.authtoken'
]
这是我的中间件设置,
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
这是我的其他设置,
CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = ["http://127.0.0.1:4000"]
在这里,我只为"strong"提供了访问权限;http://127.0.0.1:4000">
这是我的客户端django项目视图文件,托管在"http://127.0.0.1:3000">
import requests
from django.http import HttpResponse
def get_token():
url = "http://127.0.0.1:8000/api/authentication/"
response = requests.post(url, data={'username':'thomas','password':'thomas1234567890'})
token=response.json()
return token
token=get_token()
def get_details():
url = "http://127.0.0.1:8000/api/posts/"
header = {"Authorization": "Token {}".format(token['token'])}
response = requests.get(url, headers = header)
return response.text
def homepage(request):
x= get_details()
return HttpResponse(x)
现在,即使我正在从django-cors origin白名单上没有提到的其他域请求数据,我也能够在没有任何错误的情况下获取数据,我无法限制其他域访问数据。有人能帮我解决这个问题吗。
将此设置用于您的应用程序。发生这种情况是因为您使用的是HTTPS
而不是HTTP
。
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
根据CORS_ALLOW_ALL_ORIGNS 的文档
如果为True,则允许所有原点其他设置限制允许的来源将被忽略默认为False。
因此,您的CORS_ALLOWED_ORIGINS似乎被忽略了,因为CORS_ALLALL_ORIGINS被明确设置为False,禁止所有来源。