React-Django: "Authentication credentials were not provided." when refreshing http://localhost:8000/

26 views Asked by At

I am building a React-Django app with JWT authentication. I implemented my JWT authentication following this tutorial https://www.youtube.com/watch?v=sZxxU9zqCGU&list=PLJRGQoqpRwdfoa9591BcUS6NmMpZcvFsM&index=7 but at time 16:58, when I refresh, I get a 401 response Authentication credentials were not provided. I get the same error when I tried to directly access localhost:8000. I am able to perform all other functions ( login, logout, go to other pages) without any trouble, I can even refresh my webpage when I at other pages and it will redirect me to localhost:8000. However, I am able to access and refresh my web page at port 3000 without any problem.

I tried using interceptor to include the access token in every request, but to no avail:

import axios from "axios";
import store from "./store";
import { refreshAccessToken, logout } from "./actions/auth";

axios.defaults.baseURL = process.env.REACT_APP_API_URL;

axios.interceptors.request.use(
    (config) => {
        const state = store.getState();
        const token = state.auth.access;
        if (token) {
            config.headers["Authorization"] = `JWT ${token}`;
        }
        return config;
    },
    (error) => Promise.reject(error)
);

axios.interceptors.response.use(
    (response) => response,
    async (error) => {
        const originalRequest = error.config;
        if (error.response.status === 401 && !originalRequest._retry) {
            originalRequest._retry = true;
            try {
                if (!originalRequest.url.includes("/auth/jwt/refresh/")) {
                    await store.dispatch(refreshAccessToken());
                    const state = store.getState();
                    const newToken = state.auth.access;
                    originalRequest.headers[
                        "Authorization"
                    ] = `JWT ${newToken}`;
                    return axios(originalRequest);
                }
            } catch (refreshError) {
                return Promise.reject(refreshError);
            }
        }
        return Promise.reject(error);
    }
);
0

There are 0 answers