Django Framework CSRF verification failed with 403 Forbidden error. Request aborted for non-HTML python script

I am using Django Framework with DRF to generate APIs at the backend. I am using python script as an standalone windows based application to retrieve and send data to the backend server which is Django. It is not HTML application and no Cookies are involved. It is simply running python script with "request" library. I am also using JWT authentication token to secure my requests to server. While making request to fetch the token to the server I am getting below error:

CSRF verification failed. Request aborted.

You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.

If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests.

Reason given for failure: CSRF cookie not set.

My Settings.py is as below:

MIDDLEWARE = [
    'autobiz.middleware.WebSocketMiddleware',
    'django_tenants.middleware.main.TenantMainMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    "corsheaders.middleware.CorsMiddleware",
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True


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",

REST_FRAMEWORK={
    'DEFAULT_FILTER_BACKENDS':['django_filters.rest_framework.DjangoFilterBackend', ],
#    'DEFAULT_AUTHENTICATION_CLASSES':[ 'rest_framework.authentication.BasicAuthentication','rest_framework.authentication.TokenAuthentication','rest_framework.authentication.SessionAuthentication',],
    'DEFAULT_AUTHENTICATION_CLASSES':['rest_framework_simplejwt.authentication.JWTAuthentication',],
    'DEFAULT_PERMISSION_CLASSES': ['rest_framework.permissions.IsAdminUser', 'rest_framework.permissions.IsAuthenticated',],
}

My urls.py is as below:

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('abpublic.urls'), name='index'),
    path('api/token/', csrf_exempt(jwt_views.TokenObtainPairView.as_view()), name='token_obtain_pair'),
    path('api/token/refresh/', csrf_exempt(jwt_views.TokenRefreshView.as_view()), name='token_refresh'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

My views.py is as below:

class UsersViewSet(viewsets.ModelViewSet):
    queryset = Users.objects.all()
    serializer_class = UsersSerializer
    permission_classes = (IsAuthenticated,)
    filterset_fields = ['empid', 'password', 'type', 'reporting_to', 'role', 'active', 'last_login_date',
                        'last_created_date',
                        'last_login_time', 'last_created_time', 'joindate', 'leavedate', ]

Now in python script, I am first trying to retrieve token and then provide as a header to the query. But, while generating token I am facing the issue.

 # Request the token
                token_response = requests.post(tenant + "api/token/", data=credentials)

                # Check if the request was successful
                if token_response.status_code == 200:
                    tokens = token_response.json()
                    access_token = tokens.get('access')  # The access token
                    print(access_token)
                    refresh_token = tokens.get('refresh')  # The refresh token
                else:
                    print('Failed to obtain token:', token_response.status_code, token_response.text)
                    access_token = None

                # Token has changed, split the token into its components
                token_parts = token.split('#')
                if len(token_parts) != 6:
                    print("Invalid token format")
                    continue

I have tried searching and applied some solutions as below:

    path('api/token/', csrf_exempt(jwt_views.TokenObtainPairView.as_view()), name='token_obtain_pair'),

Also tried adding,

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True

But no solution is working. As it is not HTML application, I wonder how to secure my queries.

Вернуться на верх