I have a React app that connects to an API. I'm using React-Router and I'm trying to implement authentication check to redirect the user to the login page if not authenticated with the API. Here is the routing part of App.js:
...
render() {
return (
<div className="Margins">
<BurgerMenu
isAuthenticated={this.state.isAuthenticated}
logoutCallback={this.logoutCallback}
/>
<Routes>
<Route
path="/"
element={
<AuthenticationRequired
isAuthenticated={this.state.isAuthenticated}
setAuthenticationCallback={this.setAuthenticationCallback}
>
<Home />
</AuthenticationRequired>
}
/>
<Route
path="/product"
element={
<AuthenticationRequired
isAuthenticated={this.state.isAuthenticated}
setAuthenticationCallback={this.setAuthenticationCallback}
>
<Product />
</AuthenticationRequired>
}
/>
<Route
path="/login"
element={
<Login
setTokenCallback={this.setTokenCallback}
isAuthenticated={this.state.isAuthenticated}
/>
}
/>
<Route path="/contact" element={<Contact />} />
<Route path="/register" element={<Register />} />
</Routes>
</div>
);
}
}
export default App;
There are two authenticated endpoints: "/"
and "/product"
. The AuthenticationRequired
component is as follow:
import {Component} from "react";
import { Navigate } from "react-router-dom";
import axios from "axios";
let config = require("../config.json");
class AuthenticationRequired extends Component {
constructor(props) {
super(props);
this.state = {
isAuthenticated: props.isAuthenticated,
setAuthentication: props.setAuthenticationCallback
};
}
checkAuthentication() {
if (this.props.isAuthenticated) return;
console.log("check authentication")
axios.get(config.AUTHENTICATION_CHECK_URL,
{ withCredentials: true }
)
.then((response) => {
this.props.setAuthenticationCallback(true);
})
.catch((error) => {
this.props.setAuthenticationCallback(false);
})
}
render() {
this.checkAuthentication();
if (this.props.isAuthenticated) return this.props.children;
return <Navigate to="/login" replace />;
}
}
export default AuthenticationRequired;
So it basically checks if the user is authenticated by making an API call. If the session cookie is valid, the servers sends a 200 response code and the user is allowed to access the route. When connecting to the "/"
route, it works as expected. However, when trying to access "/product"
, the .then function never gets executed so I end up being redirected to the login page. I checked in the network tab of my browser and a get request is being sent to the server which replies with a 200 status code so I would expect the .then
to be executed but it's not. I don't understand what's going on here.