I have done token authentication for the url 'localhost:8000/api/posts' and according to django-cors-headers library I have also changed the settings.py file. Here is my settings.py file,
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'
]
Here is my middleware settings,
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',
]
Here are my other settings,
CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = ["http://127.0.0.1:4000"]
Here I have given access only for "http://127.0.0.1:4000"
This is my client django project views file which is hosted on "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)
Now even though I am requesting for the data from other domain which is not mentioned on django cors origin whitelist, I am able to fetch the data without any error, I am not able to restrict other domains for accessing the data. Can anyone please help me in solving this issue.