How to redirect to correct client route after social auth with Passport (react, react-router, express, passport)

后端 未结 2 1253
無奈伤痛
無奈伤痛 2021-02-02 03:29

I have a React/Redux/React Router front end, Node/Express back end. I’m using Passport (various strategies including Facebook, Google and Github) for authentication.

2条回答
  •  清酒与你
    2021-02-02 03:36

    Depending on your application architecture, I can give you a couple of ideas, but they are all based on the fundamental :

    Once you have backend handling authentication, you need to store the state of the user in your backend as well ( via session cookie / JWT )

    You can create a cookie-session store for your express app which cookie, you need to configure properly to use both the domains ( the backend domain and the front-end domain ) or use JWT for this.

    Let's go with more details

    Use React to check the authentication state

    You can implement an end-point in express called /api/credentials/check which will return 403 if the user is not authenticated and 200 if is.

    In your react app you will have to call this end-point and check if the user is authenticated or not. In case of not authenticated you can redirect to /login in your React front-end.

    I use something similar :

    class AuthRoute extends React.Component {
        render() {
    
            const isAuthenticated = this.props.user;
            const props = assign( {}, this.props );
    
            if ( isAuthenticated ) {
                 return ;
            } else {
                 return ;
            }
    
        }
    }
    

    And then in your router

    
    
    

    In my root component I add

    componentDidMount() {
        store.dispatch( CredentialsActions.check() );
    }
    

    Where CredentialsActions.check is just a call that populates props.user in case we return 200 from /credentials/check.

    Use express to render your React app and dehydrate the user state inside the react app

    This one is a bit tricky. And it has the presumption that your react app is served from your express app and not as static .html file.

    In this case you can add a special which will be served by express if the user was authenticated.

    By doing this you can do:

    const isAuthenticated = window.authenticated;
    

    This is not the best practice, but it's the idea of hydrate and rehydration of your state.

    References :

    1. Hydration / rehydration in Redux
    2. Hydrate / rehydrate idea
    3. Example of React / Passport authentication
    4. Example of cookie / Passport authentication

提交回复
热议问题