Home > database >  Allow all ips in CSRF_TRUSTED_ORIGIN django
Allow all ips in CSRF_TRUSTED_ORIGIN django

Time:05-31

How to allows all/ any ips in CSRF_TRUSTED_ORIGIN of django Backend django restapi are running and frontend is on angular in one system and we are trying to access with system ip in another system, i am able to access frontend and while accessing backend POST method API's are not working it's showing not found in csrf trusted origins. In settings.py i made get dynamic ips.

import socket
def get_ipaddress(): 
    
   host_name = socket.gethostname()
   ip_address = socket.gethostbyname(host_name) 
   return "http://" ip_address ":4200"

ALLOWED_HOSTS=["*"]
CSRF_TRUSTED_ORIGINS=[get_ipaddress()]

Tried to use csrf_excempt , but it's not working. Version of django4.0.1, Angular 16

CodePudding user response:

For CSRF you need only to whitelist/allow the IP of the server where your angular app is hosted. While you are running angular app you should whitelist the url you access your angular app in browser e.g: "http://localhost:4200" or http://192.168.1.1:4200. or https://whateveryourwebappurlis.com.

This is the URL you use to load the app in browser. You need to whitelist this.


CSRF_TRUSTED_ORIGINS=["http://localhost:4200", "https://whateveryourwebappis.com"]

Make sure that you are passing this is in the origin header of your request to django app.

Read more at: https://docs.djangoproject.com/en/4.0/ref/settings/#csrf-trusted-origins

In case you already haven't whitelisted the methods and headers, please do that as well in your settings.

CORS_ALLOW_ALL_ORIGINS=False

CSRF_TRUSTED_ORIGINS = [
    "http://yourwhitelistedip.com",
]

CORS_ALLOW_METHODS = [
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
]

CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]

CodePudding user response:

socket.gethostbyname(host_name.local)

When used the above line in the get_ipaddress, it got worked

  • Related