nOybek
nOybek

Reputation: 405

CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted origins

Please help me solve the problem. I was building an app consisting of Django Rest Framework and ReactJS. I used ViewSets.

my error: Screenshot of the error

Demo

response data:

{"detail":"CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted origins."}

DeleteLead function in ReactApp

 export const deleteLead = (id) => (dispatch) => {
  axios
    .delete(`/api/leads/${id}/`)
    .then((res) =>
      dispatch({
        type: DELETE_LEAD,
        payload: id,
      })
    )
    .catch((err) => {
      console.log(err);
    });
};

LeadViewSet: from rest_framework import viewsets, permissions from .serializsers import LeadSerializers from leads.models import Lead

# lead viewset
class LeadViewSet(viewsets.ModelViewSet):
    queryset = Lead.objects.all()
    # permission - bu ruxsat beruvchi
    permission_classes = [
        permissions.AllowAny # barcha uchun ruxsat
    ]
    serializer_class = LeadSerializers

LeadSerzializers:

# lead serializer
class LeadSerializers(serializers.ModelSerializer):
    class Meta:
        model=Lead
        fields="__all__"

Lead model:

class Lead(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField(max_length=100, unique=True)
    message = models.TextField(max_length=500, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

Upvotes: 14

Views: 17276

Answers (4)

adarsh
adarsh

Reputation: 11

I was also getting the same issue while performing the API testing in postman and i resolved the this issues by clearing the cookies in postman tool

Upvotes: 0

imdsrs
imdsrs

Reputation: 1

To all the people who are doing this locally, this might be because you are logged-in to the Django admin panel. Logging out fixed the error.

All the CSRF solution is the right way to do it. However, if you are building a local project, this solution may work.

This is because, Django expects a CSRF token when a user session exists and since Django uses cookie sessions by default, which are susceptible to cross site request forgery (CSRF). Of course when there is no user logged in there is no reason to use CSRF because there is no cookie to protect so the request will work without the token.

Upvotes: 0

iChux
iChux

Reputation: 2386

Adding more to what Jaime wrote, I have this:

python manage.py shell <<EOF
from django.conf import settings
from urllib.parse import urlparse

print([urlparse(origin).netloc.lstrip("*") for origin in settings.CSRF_TRUSTED_ORIGINS])
print({origin for origin in settings.CSRF_TRUSTED_ORIGINS if "*" not in origin})
EOF

Running the above will reveal what the set details for CSRF_TRUSTED_ORIGINS are.

I had a situation where I was correct but then, somewhere below the settings file, this same setting was referring to a localhost:7007, and it was already deployed.

The above helped me detect and fix it. And if your app is inside a docker container, start it as:

docker exec -i add-container-name-here python manage.py shell

and the other parts of it will remain the same as shown above.

a sample of the error page on deployment

Upvotes: 0

Jaime Ortiz
Jaime Ortiz

Reputation: 1319

Try to set your CSRF trusted origins, allowed host and in the settings file like this

CSRF_TRUSTED_ORIGINS = [
    'http://localhost:8000'
],
ALLOWED_HOSTS = [
    'localhost',
],
CORS_ORIGIN_WHITELIST = [
    'http://localhost:8000',
]

Upvotes: 23

Related Questions