Django + Vue 403 Forbidden Error On axios.get - django

I'm trying to log the user but the Django rest API can't see the current jwt token of the logging user and I'm getting a 403 error. The API is working fine on the Postman with all the Authentication aspects. I have tried some advised solutions but they don't seem to work.
Attempt 1
axios.defaults.headers.common["authorization"] =
"Bearer " + localStorage.getItem("jwt");
await axios.get(api-link)
Attempt 2
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
axios.defaults.xsrfCookieName = "csrftoken";
axios.defaults.withCredentials = true;
await axios.get(api-link)
Attempt 3
await axios.get(api-link.{
{
headers:{header stuff}
},
{withCredentials: true}
)
(Basically adding headers and credentials inside the get request.)
Django settings.py
I couldn't find a standard for this, currently I'm using this one for testing:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'users',
]
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_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = ['http://127.0.0.1:8000', 'http://localhost:8000']
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
]
}
CSRF_COOKIE_NAME = "XSRF-TOKEN"

Related

How to fetch data from an api in React Native from Django rest framework using axios

This is the context Provider That has my state that is fetched from the rest framework api.
import axios from 'axios';
export const PostContext = createContext();
const PostContextProvider = (props) => {
const [ posts, setPosts ] = useState([]);
useEffect(() => {
axios.get('http://127.0.0.1:8000/api/products/')
.then(res => {
setPosts(res.data)
})
.catch(err => {
console.log(err);
})
}, []);
return(
<PostContext.Provider value={{ posts }}>
{props.children}
</PostContext.Provider>
)
}
export default PostContextProvider**
When I try to console log it I get an this error in my emulator console.log
Unrecognized event: {"type":"client_log","level":"log","data":["[]"]}
Array []
When I check my browser, I got this error.
DevTools failed to load SourceMap: Could not load content for http://127.0.0.1:8000/static/rest_framework/css/bootstrap.min.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
I tried to configure my backend using cors headers and the code looks like this
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'django_filters',
# 'rest_framework_filters',
'shop.apps.ShopConfig',
'cart.apps.CartConfig',
]
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_ORIGIN_ALLOW_ALL = True
# CORS_ORIGIN_WHITELIST = (
# 'http://localhost:19002/'
# )
if you haven't created any static files ( js or css ) in your django repo then comment out
'django.contrib.staticfiles',
or in setting STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
gussing this after showing your error. This might help!

django-cors-header not working as expected when using Postman

I'm trying to use my DRF API in my React Web App with Axios but I'm getting CORS policy blocked.
I've checked the headers using POSTMAN and seems like django-cors-header is not actually embedding the Access-Control-Allow-Origin: *
This is my settings.py from Django:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'trvl',
'rest_framework',
'coreapi',
'django_filters',
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False
And this is what I get from POSTMAN
How can I fix this so every response has the Access-Control-Allow-Origin : *
I had the exact same scenario as you. Same frontend and backend.
I was able to resolve my issue by adding this to my settings.py in addition to everything you listed.
CORS_REPLACE_HTTPS_REFERER = True
In settings.py
set ALLOWED_HOSTS = [] to ALLOWED_HOSTS = ["*"]

Django RestFrameWork Post Request with csrf

I am a newbie to django/django-rest-framework. I am experimenting with React for the frontend and Django-rest-framework for the backend. The client and server are on different domains. I was able to make a GET request, for POST request I also manage to do it but only with the csrf_exempt decorator, which is not ideally. The django documentation recommended me to use CSRF_TRUSTED_ORIGINS to avoid csrf verification but that also doesn't work for me. Here's my settings.py
INSTALLED_APPS = [
'api.apps.ApiConfig',
'rest_framework',
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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_WHITELIST = (
'localhost:3000',
)
CSRF_TRUSTED_ORIGINS = [
'localhost:3000'
]
Should I start implementing jwt-authentication to avoid this situation ? What is the best approach to this problem?

Django-rest cross origin request fails

I have installed django-cors-headers and my seetings.py has following:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'rest_framework_docs',
'tasks'
]
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_ORIGIN_ALLOW_ALL = True
However, I still get Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response error when I hit the url from my Angular frontend.
Am I missing any configuration?
You need to add:
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = False
To your settings.py too and it will work ;)
The problem wasn't on backend side, I had a function in my angular service as following:
getTasks(): Observable<Task[]> {
let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
let options = new RequestOptions({ headers: headers });
return this.http.get(this.taskUrl, options)
.map(this.extractData)
.catch(this.handleError);
}
Which had to be:
getTasks(): Observable<Task[]> {
return this.http.get(this.taskUrl)
.map(this.extractData)
.catch(this.handleError);
}
In my case it worked when backend(django) and frontend(angular) worked on the same hosts. Like django server on localhost:8000 and angular server on localhost:4200.

Django Angular cors error: access-control-allow-origin not allowed

I have implemented auth in my django app using django-rest-auth. My settings in settings.py:
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'django.contrib.sites',
'allauth',
'allauth.account',
'rest_auth.registration',
'corsheaders',
'rest_framework_docs',
'tasks'
]
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',
]
ROOT_URLCONF = 'urls'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
ALLOWED_HOSTS = ['*']
SITE_ID = 1
I am logged in from my frontend- I receieved a token with I have stored in my local storage. Now I making a simple GET request like following:
getTasks(): Observable<Task[]> {
let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
let options = new RequestOptions({ headers: headers, withCredentials: true });
return this.http.get(this.taskUrl, options)
.map(this.extractData)
.catch(this.handleError);
}
But it gives me : Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response. although I am including withCredentials.
What am I doing wrong?
P.S: If I remove options from POST then there is no error but I get incorrect data because my backend returns data for a specific user.
Remove this line,
let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
from your getTasks() function. You don't need to specify those options to the server. django-cors-headers takes care of that.