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
288 views
in Technique[技术] by (71.8m points)

reactjs - React site - On Refresh, Auth Route does not have access to auth context data

I have my React application working pretty well with authentication using a session cookie from Node Express. Then on refresh, I got logged out. So I added a function to my top level App.js to check if the user is logged in and valid. That worked great. Then I added a custom AuthRoute to my application. It checks the auth context to see if the user is authenticated or not. On refresh, it does not see the updated auth context and kicks the user back to the login. Here is my AuthRoute.js:

import { Redirect, Route } from 'react-router-dom';

import { NonAuthRoutes } from '../config/AuthRoutesLogic';
import { useGlobalAuthContext } from '../context/authContext';

const AuthRoute = ({
    Component,
    path,
    exact = false,
    requiredRoles
}) => {
    const isAuthed = !!useGlobalAuthContext().user.email;
    console.log({ isAuthed });
    console.log(useGlobalAuthContext().user);

    const userRole = useGlobalAuthContext().user.type;
    const userHasRequiredRole = requiredRoles.includes(userRole);
    console.log(userRole, userHasRequiredRole);
    const message = 'Please log in to view this page';
    return (
        <Route
            exact={exact}
            path={path}
            render={(props) =>
                isAuthed && userHasRequiredRole ? (
                    <Component {...props} />
                ) : (
                    <Redirect
                        to={{
                            // pathname: userHasRequiredRole
                            //  ? NonAuthRoutes.login
                            //  : NonAuthRoutes.unauthorized,
                            pathname: NonAuthRoutes.login,
                            state: {
                                message,
                                requestedPath: path
                            }
                        }}
                    />
                )
            }
        />
    );
};

export default AuthRoute;

And here is my function from my App.js that runs on refresh to verify the user:

const checkForLoggedInUser = () => {
        axios.get(baseURL + '/users/user').then((res) => {
            console.log({ res });
            if (res.data.user) {
                console.log('there is a logged in user!');
                setAuthData((prevState) => {
                    return {
                        ...prevState,
                        loading: false,
                        user: {
                            email: res.data.user.email,
                            type: res.data.user.type,
                            customer: res.data.user.customer
                        }
                    };
                });
            } else {
                // we have no valid logged in user
                console.log('no logged in user!');
                setAuthData((prevState) => {
                    return {
                        ...prevState,
                        loading: false,
                        user: {
                            email: '',
                            type: '',
                            customer: ''
                        }
                    };
                });
            }
        });
    };

To sum it up: The cookie persists. The user is still logged in. AuthRoute.js is just kicking them back to login page because isAuthed is false.


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

1 Reply

0 votes
by (71.8m points)

I think it will depend on how you've configured the server/authentication.

Clearly its working when it receives from the /user endpoint, which makes me think the issue is with the session cookie staying set between refresh.

Open your devtools to the application tab and find the cookie thats set when you hit the /user endpoint. Reload and confirm it persists, if not then you have your root cause, this might be because the domains don't match/secure cookie on non https/expiry time on the cookie etc. might be worth providing a codesandbox/repo link if possible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...