So I'm making a protected route with react-router-dom
. And it works, sort of.
However it only works when I manually remove token from localStorage (from the browser' GUI).
Then I'm redirected to /login , and after successful login I can access my /profile . However, once token expires, it won't remove token from localStorage and won't return false from checkAuth()
to <AuthRoute />
which is inside render()
. Any tips how to deal with this?
import React, { Component } from 'react';
import jwt from 'jsonwebtoken';
import {
BrowserRouter,
Route,
Redirect,
Switch
} from 'react-router-dom';
import Login from './components/Login';
import Profile from './components/Profile';
const checkAuth = () => {
const token = localStorage.getItem('token');
const currentTime = Math.floor(new Date().getTime() / 1000);
const { exp } = jwt.decode(token);
if (!token) {
return false;
}
if (exp < currentTime) {
localStorage.removeItem('token');
return false;
}
return true;
};
const AuthRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={props =>
checkAuth() ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: '/login',
state: { from: props.location }
}}
/>
)
}
/>
);
class App extends Component {
render() {
return (
<BrowserRouter>
<Switch>
<Route exact path="/login" component={Login} />
<AuthRoute exact path="/profile" component={Profile} />
</Switch>
</BrowserRouter>
);
}
}
export default App;
checkAuth()
will call on refresh the page and on changing routes. Also make sure your if condition working properly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.