Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

node.js - Logout when token expired only when page is refreshed? Why?

i am finding difficult to understand if when token is expired and logout action is performed, this last action is only executed when the page is refreshed. Although when token expire the 401 code is thrown it still make the protected route visible and only with a refresh it logs out and goes to login.. Is it supposed to be like this or should not be happening and i am missing something?

Here's the code in front

import React, { useEffect } from 'react';
import { Route, Redirect } from 'react-router-dom';
import {useDispatch} from 'react-redux'
import { logoutUser } from '../redux/ActionCreators';
import { baseUrl } from '../shared/baseUrl'

export const PrivateRoute = ({ component: Component, ...rest }) => {

    const dispatch = useDispatch()    
    
    useEffect(() => {
        // send jwt to API to see if it's valid
        let token = localStorage.getItem("token");
        if (token) {
            fetch(baseUrl + "protected", {
                method: "POST",
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ token })
            })
                .then((res) => {
                    return res.json()
                })
                .then((json) => {
                    if (json.success) {
                    }
                })
                .catch((err) => {
                    dispatch(logoutUser())
                })
        } else {
            dispatch(logoutUser())
        }        
            
        }, [])
        
        
    return (<Route {...rest} render={props => (
        localStorage.getItem('token')
            ? <Component {...props} />
            : <Redirect to={{ pathname: '/users/login', state: { from: props.location } }} />
    )} />)
}

and the api called

protectedRouter.route('/')
    .options(cors.corsWithOptions, (req, res) => { res.sendStatus(200) })
    .get(cors.cors, authenticate.verifyUser, authenticate.verifyAdmin, async (req, res, next) => {
        res.statusCode = 403
        res.end('Operation not supported')
    })
    .post(cors.corsWithOptions,  async (req, res, next) => {
        const token = req.body.token
        
        if (token) {
         try {
          return jwt.verify(token, process.env.secretKey);
         } catch (err) {
          return null;
         }
        }
        return null;
}) 
question from:https://stackoverflow.com/questions/65928268/logout-when-token-expired-only-when-page-is-refreshed-why

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Can be various workaround, the easiest would be just re-render the component. just an example. Might not be the cleanest, but it will give you an idea

const dispatch = useDispatch();
const { token, setToken } = useDispatch();

useEffect(() => {
        // send jwt to API to see if it's valid
        const token_from_storage = localStorage.getItem("token");
        setToken(token_from_storage);
        
        if (token_from_storage) {

        fetch(baseUrl + "protected", {
            method: "POST",
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ token })
        })
            .then((res) => {
                return res.json()
            })
            .then((json) => {
                if (json.success) {
                }
            })
            .catch((err) => {
                setToken(undefined);
                dispatch(logoutUser())
            })
    } else {
        setToken(undefined);
        dispatch(logoutUser())
    }
}, [])
            
    return (<Route {...rest} render={props => (
                token
                    ? <Component {...props} />
                    : <Redirect to={{ pathname: '/users/login', state: { from:                       
             props.location } }} />
            )} />)

It will re-render the component when the token is invalidated or is not found from the storage. HTH.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...