React and express Authentication checking authentication on each request

Issue

So I am making an application with React on the front end and express on the backend. The way my application works on the front end is I have two apps: an authenticated app and an unauthenticated app.

const {authenticated} = useAuth().authData;
return authenticated ? <AuthenticatedApp/> : <UnauthenticatedApp/>

Here the authenticated variable comes from an AuthContext that I can access globally throughout the application. What it does is store the authenticated value in localStorage. What I am stuck on is when/where I set this authenticated value. In my express backend I have a middleware that checks if the session is authenticated (the user has logged in).

app.use((req, res, next) => {
console.log('Checking session...');
if (!req.session.authenticated) {
    const err = new Error('Not authenticated!');
    err.status = 401;
    return next(err);
} else {
    return next();
}

});

I originally had a function called checkSession that would make a call to express to check if the session is authenticated. This would occur as a separate request along with every request. I see a lot of overhead in this so I am looking for an alternative. What I am considering to do now is set a header value on every response from express like so.

app.use((req, res, next) => {
console.log('Checking session...');
if (!req.session.authenticated) {
    const err = new Error('Not authenticated!');
    err.status = 401;
    return next(err);
} else {
    res.setHeader('Authenticated', true);
    return next();
}

});

And then I would access this in every response on the front end and do the following.

setAuthenticated(res.header.authenticated)

Is there a simpler way to do this without making two API calls for each request or having to write setAuthenticated() in every response from the backend? What I am essentially trying to fix is the user manually changing the localStorage value for authenticated to something that isn’t null.

Solution

You can update the "authenticated" state in local storage only once when the app is loaded, or even when you log the user in. If someone updates that state in the local storage it should be "their problem". Of course, your backend should separately authenticate incoming requests, based on tokens or cookies, not the value from the local storage. Should the user make a request to a secured endpoint, without valid authentication credentials (access token or cookie) then the backend should respond with a 401 response. The front end can catch 401 responses from your backend and then update the "authenticated" state in local storage, and as a result, render the unauthenticated app.

Answered By – Michal Trojanowski

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published