How do I use a flask REST api for authenticating in a react app?

Viewed 31

I am trying to create a frontend for a database, and I have created a REST api in flask which authenticates using a JWT stored in an httpOnly cookie. I need to make sure if a user tries to access a page that authentication is checked by the react frontend and the flask backend. The resources all have the @jwt_required decorator, so they cannot be accessed without one. What I need to do is redirect the user to my react login screen if they have not yet authenticated with the api. I have a solution that kind of works, but it uses an asynchronous fetch call to the api to check if the user is currently authenticated. Below is the code I am using.

App.js

    function App() {

  return (
    <Routes>
      <Route path="/" element={<Login />} />
      <Route path="/dashboard" element={<AuthCheck><Dashboard /></AuthCheck>} />
    </Routes>
  )
}

As you can see, I have wrapped the child component in the component I am using to check authentication.

AuthCheck.js

const AuthCheck = ({ children }) => {

    const navigate = useNavigate();
    const fetchData = async () => {
        const res = await fetch("/authcheck", {
            mode: 'cors',
            method: "GET",
            credentials: 'include',
            headers: { 'Content-Type': 'application/json' }
        })
        if (!res.ok) {
            navigate('/');
        }
    }

    useEffect(() => {
        fetchData();
    })

    return children;
}

I am checking the credentials with the api using the authcheck resource in the api. This does technically work, but since I am using an async function, it will render the entire child component first and then redirect me if not authenticated. Is there any way to get around rendering the child component before authenticating?

I am open to trying a different form of authentication all together if need be, but I have read that using an httpOnly cookie with csrf protection on the flask backend for jwt authentication is a secure way to go.

0 Answers
Related