0

Am trying to implement a log in function with Django rest framework but any time I try to log in from react-native frontend to my rest API it keep throwing this error forbidden (CSRF cookie not set.) I have look on stack overflow for similar problems and solution but somehow all the solutions I had tried so far hadn't given me a workaround success over my challenge. I tried setting the CSRF_COOKIE_SECURE to False as this solution suggested https://stackoverflow.com/a/38531887/11891228 but it didn't work in my case and also tried other solution on here. So it is worth asking for help from anyone who might have experience with this challenge.

import React, { useState } from 'react';
import { View, TextInput, Button, StyleSheet,Image } from 'react-native';

const Login = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const getCSRFToken = async () => {
    try {
      const response = await fetch('http://192.168.100.53:3000/api/gettoken/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username,
          password,
        }),
      });

      if (response.ok) {
        const { csrftoken } = await response.json();
        return csrftoken;
      } else {
        throw new Error('Failed to retrieve CSRF token');
      }
    } catch (error) {
      console.error('Error:', error.message);
      throw error;
    }
  };

  const handleLogin = async () => {
    try {
      const csrftoken = await getCSRFToken();

      const response = await fetch('http://192.168.100.53:3000/api/api-auth/login/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-CSRFTOKEN': csrftoken,
        },
        body: JSON.stringify({
          username,
          password,
        }),
      });

      if (response.ok) {
        // Handle successful authentication
        console.log('Login successful');
        const data = await response.json();
        console.log('Response:', data);
      } else {
        // Handle authentication error
        console.error('Login failed');
        throw new Error('Authentication failed');
      }
    } catch (error) {
      // Handle network error or authentication failure
      console.error('Error:', error.message);
    }
  };

Here my setting for the CSRF Cookies from Django settings

CORS_ALLOW_CREDENTIALS = False

CSRF_COOKIE_SECURE = False

SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SAMESITE = 'Strict'
SESSION_COOKIE_SAMESITE = 'Strict'
CSRF_COOKIE_HTTPONLY = False  # False since we will grab it via universal-cookies
SESSION_COOKIE_HTTPONLY = True

Urls.py

router = routers.DefaultRouter()
router.register(r'account-list',UserAccountViewSet,basename="account")
urlpatterns = [
    path('',include(router.urls)),
    re_path(r'^api-auth/', include('rest_framework.urls')),
    path('gettoken/', obtain_auth_token), 
    
]
Godda
  • 951
  • 1
  • 10
  • 26

0 Answers0