Anon957
Anon957

Reputation: 560

Django comments CSRF error

Getting a csrf error I cant figure out how to fix, i have rest auth working, user is able to update their details like so: enter image description here

but with Django Comments i get this csrf error using the same csrf token Error:

enter image description here

I would like to get rid of this error on the /comments/post/ endpoint, such that this endpoint behaves similar to /rest-auth/user/ view which accepts an "Authorization: Token 792b5fb27b4fe805e895c91274f26b6ab13cb654" header field to relevant provide data to the authenticated user.

The following is an exert of the csrf related decotaros on the respective views shown in the screen shots: From the /comments/post/ endpoint

@csrf_protect
@require_POST
def post_comment(request, next=None, using=None):
    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()
    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name() or request.user.get_username()
        if not data.get('email', ''):
            data["email"] = request.user.email

From the /rest-auth/user/ endpoint

@api_view(['GET'])
@permission_classes((IsAuthenticated, ))
def get_user(request, **kwargs):
    pk = request.data['pk']

    user = MyUser.objects.get(pk=pk)
    serializers = UsersSerializer(user)
    return Response(serializers.data)

Upvotes: 1

Views: 204

Answers (3)

ArdentBlaze
ArdentBlaze

Reputation: 103

The decorators for your endpoints are different, thus you need to adjust the headers accordingly. For your /rest-auth/ view the WWW-Authenticate header is required as mentioned here.

The comments view /comments/ endpoint has the csrf_protect decorators which means that the header must match the csrf-token returned in the cookie,as Fede mentions in your header you only require 'X-CSRFToken' with the matching value from the cookie.

Upvotes: 1

Fede Scuoteguazza
Fede Scuoteguazza

Reputation: 73

I think you are using django-rest-framework which comes with the csfr token exempt by default, but postman is sending a csfr token that is why you are getting that error.

cleaning the cookies might solve the problem.

Upvotes: 1

mariodev
mariodev

Reputation: 15559

You're using the wrong content type. Please change it into application/json and try again.

Upvotes: 2

Related Questions