Reputation: 3466
I am trying to join Backend (Express JS) and Frontend (React JS). Right now I am trying to understand how to handle session management.
When a user logins using a form made with React JS, the backend returns a HS-256 JWT token with the user information as a payload.
To avoid unlogged users from fetching data I read that the frontend has to send the bearer token as header and this works fine. But I am not able to find a way of how to avoid the users of using the application in first place, I mean, when every page loads.
Right now my Login code looks like this:
import React, { useEffect, useState } from 'react';
import { useCookies } from 'react-cookie';
export default () => {
const [cookies, setCookie] = useCookies(['auth']);
const [redirect, setRedirect] = useState(false);
const handleSubmit = async e => {
e.preventDefault();
const response = await fetch('server/auth/login', options);
const {token} = await response.json();
setCookie('token', token, { path: '/' });
};
useEffect(() => {
if (cookies.auth) {
setRedirect(true);
}
}, [cookies]);
if (redirect) {
return <Redirect to="/admin" />;
}
return <form onSubmit={handleSubmit}>...</form>
};
I don't know how to use this information in each component to proper set user restrictions. What should I do in order to achieve this?
Upvotes: 0
Views: 3063
Reputation: 3413
What you'd want to do is initially check if the by user is authenticated by checking for a the token in local storage / cookie. If so, allow the user to proceed to the route they have visited, if not redirect them back to the login screen ( or error screen). Typically, React users use routing libraries such as react-router-dom
. On the documentation of the site, they go over how to go about authentication. Happy coding https://reacttraining.com/react-router/web/example/auth-workflow
Upvotes: 3
Reputation: 498
You have to save the token in local storage, so that whenever the user refreshes the page, the token would still exists.
const handleSubmit = async e => {
e.preventDefault();
const response = await fetch('server/auth/login', options);
const {token} = await response.json();
setCookie('token', token, { path: '/' });
localStorage.setItem('token', token);
};
// Check if token exists
const token = localStorage.getItem('token');
if (token && token !== '') {
return <Redirect to="/admin" />;
}
return <form onSubmit={handleSubmit}>...</form>
Note that you still have to validate that token on your server-side script before actually allowing the user to access your admin page.
Upvotes: -1
Reputation: 2268
Just store the token in local storage and in your router use protected wrappers to routes. If the token doesn't exist or is expired, return redirect to Login.js.
The best way to handle it would be to use an identity and Auth provider like Auth0 and read their documentation for react applications. it's really easy to set up and achieve what you are trying to do out of the box.
Here's an example from my application:
function PrivateRoute({ component: Component, ...rest }) {
return (
<AuthContext.Consumer>
{auth => (
<Route
{...rest}
render={props => {
if (!auth.isAuthenticated()) return auth.login();
return <Component auth={auth} {...props} />;
}}
/>
)}
</AuthContext.Consumer>
);
}
Upvotes: 0