OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Getting Error: Forbidden (CSRF cookie not set.) when trying to make a post request to Django view

  • Thread starter Thread starter MuhaAllAmeen
  • Start date Start date
M

MuhaAllAmeen

Guest
I am trying to create a (chrome extension + Django) password manager that will read input boxes from forms and on clicking submit it will make a POST request to the Django view with the data which will then get stored on to the postgresql database. (Keep in mind, this is only a personal project.)

But on every request, I get the error: Forbidden (CSRF cookie not set.). Even though I see csrftoken cookie under the Applications tab in inspect. I am passing the csrf token along with the request so I can't figure out what the error is.

I have tried getting the csrf token from cookies using Cookies.get('csrftoken') and also setting the csrf token cookie after fetching it from Django as well.

This is what my view looks like in Django :

Code:
@ensure_csrf_cookie
def add(request):
    if request.method == "POST":
        website = request.POST['website']
        username = request.POST['username']
        password = request.POST['password']
        user = request.user
        encryptedPass = cryptography.crypto(password)
        credentials = Credentials.objects.create(email=username, password=encryptedPass)
        if Website.objects.filter(user = user.id).filter(name=website).exists():
            website_obj = Website.objects.filter(user = user.id).filter(name=website)
            # print(website_obj[0].credentials)
            website_obj[0].credentials.add(credentials)
        else:
            website_obj = Website.objects.create(user=user, name=website)
            website_obj.credentials.add(credentials) 
        if request.headers.get('X-Requested-With') == 'XMLHttpRequest': 
            return JsonResponse({'message':'Credentials Add'})      
        return redirect('add')
    return render(request,'add.html')

This is the view where I pass the csrf token to the chrome extension:

Code:
@ensure_csrf_cookie
def get_csrf_token(request):
    return JsonResponse({'csrfToken': django.middleware.csrf.get_token(request)})

I have tried everything in my settings.py:

Code:
ALLOWED_HOSTS = []
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'password_manager_app'
]

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_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True

CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False
CSRF_TRUSTED_ORIGINS = ["*"]
CSRF_ALLOWED_ORIGINS = ["*"]
CSRF_COOKIE_DOMAIN = "*"

I am making the post request using axios in my content-script.js:

Code:
export async function getCsrfToken(){
  const axios = require('axios')
  let token;
  const response = await axios.get('http://localhost:8000/get-csrf-token',{withCredentials:true}).then((response)=>{
    console.log(response.data.csrfToken)
    token = response.data.csrfToken
  })
  return token
}

export async function axiosaddCredentialsToDatabase(email,password,url){
  const token = await getCsrfToken()
  const axios = require('axios')
  axios.post('http://localhost:8000/add',{email,password,url},{
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'X-CSRFToken': token,
      'X-Requested-With': 'XMLHttpRequest',
    },
    withCredentials:true
  }).then((response)=>{
    console.log(response)
  })
}

I would appreciate any input. Thanks in advance :)

<p>I am trying to create a (chrome extension + Django) password manager that will read input boxes from forms and on clicking submit it will make a POST request to the Django view with the data which will then get stored on to the postgresql database. (Keep in mind, this is only a personal project.)</p>
<p>But on every request, I get the error: Forbidden (CSRF cookie not set.). Even though I see csrftoken cookie under the Applications tab in inspect. I am passing the csrf token along with the request so I can't figure out what the error is.</p>
<p>I have tried getting the csrf token from cookies using Cookies.get('csrftoken') and also setting the csrf token cookie after fetching it from Django as well.</p>
<p>This is what my view looks like in Django :</p>
<pre><code>@ensure_csrf_cookie
def add(request):
if request.method == "POST":
website = request.POST['website']
username = request.POST['username']
password = request.POST['password']
user = request.user
encryptedPass = cryptography.crypto(password)
credentials = Credentials.objects.create(email=username, password=encryptedPass)
if Website.objects.filter(user = user.id).filter(name=website).exists():
website_obj = Website.objects.filter(user = user.id).filter(name=website)
# print(website_obj[0].credentials)
website_obj[0].credentials.add(credentials)
else:
website_obj = Website.objects.create(user=user, name=website)
website_obj.credentials.add(credentials)
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return JsonResponse({'message':'Credentials Add'})
return redirect('add')
return render(request,'add.html')
</code></pre>
<p>This is the view where I pass the csrf token to the chrome extension:</p>
<pre><code>@ensure_csrf_cookie
def get_csrf_token(request):
return JsonResponse({'csrfToken': django.middleware.csrf.get_token(request)})
</code></pre>
<p>I have tried everything in my settings.py:</p>
<pre><code>ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
'password_manager_app'
]

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_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = True

CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False
CSRF_TRUSTED_ORIGINS = ["*"]
CSRF_ALLOWED_ORIGINS = ["*"]
CSRF_COOKIE_DOMAIN = "*"
</code></pre>
<p>I am making the post request using axios in my content-script.js:</p>
<pre><code>export async function getCsrfToken(){
const axios = require('axios')
let token;
const response = await axios.get('http://localhost:8000/get-csrf-token',{withCredentials:true}).then((response)=>{
console.log(response.data.csrfToken)
token = response.data.csrfToken
})
return token
}

export async function axiosaddCredentialsToDatabase(email,password,url){
const token = await getCsrfToken()
const axios = require('axios')
axios.post('http://localhost:8000/add',{email,password,url},{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-CSRFToken': token,
'X-Requested-With': 'XMLHttpRequest',
},
withCredentials:true
}).then((response)=>{
console.log(response)
})
}
</code></pre>
<p>I would appreciate any input. Thanks in advance :)</p>
 

Latest posts

I
Replies
0
Views
1
impact christian
I
Top