Django 개발

[Django] postman 로그인 API CSRF token missing 오류 해결

나도개발자 2022. 2. 21. 10:42

postman에서 django-rest-auth를 사용하여 로그인 url로 데이터를 전송했더니 아래와 같은 오류가 표시되었다.

"detail": "CSRF Failed: CSRF token missing or incorrect."

 

 

원인을 서치해보니 DEFAULT_PERMISSION_CLASSES 설정 때문이었다. postman을 사용할 때만 임시로 SessionAuthentication을 주석처리한 후 BasicAuthentication으로 테스트해볼 수도 있지만 이왕이면 깔끔한 해결 방법을 찾고 싶었다.

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
    	'rest_framework.authentication.SessionAuthentication',
	),
}

 

 

StackOverflow 참고

 

CSRF Failed: CSRF token missing or incorrect

I'm using Django 1.7 and django-rest-framework. I made an API that returns me some JSON data putting this in my settings.py REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.

stackoverflow.com

답변 작성자도 "Permanent Solution: If you are using Postman, "이라고 말하고 있다.

'DEFAULT_AUTHENTICATION_CLASSES': [
    # 'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.BasicAuthentication',
]

 


 

 

해결방법

CSRF token은 전송할 때마다 갱신되기 때문에 매번 token 값을 수정해주지 않고 자동화할 수 있는 방법이 필요하다. 일단 Headers 탭에 새로운 변수를 추가해준다.

X-CSRFToken - {{csrftoken}}

 

 

그 다음 Tests 탭으로 들어가 아래 코드를 추가해주면 쿠키에서 csrftoken을 받아 postman 변수에 저장해주는 것이다.

var xsrfCookie = postman.getResponseCookie("csrftoken"); 
postman.setGlobalVariable('csrftoken', xsrfCookie.value);

반응형