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

Asked
Active3 hr before
Viewed126 times

7 Answers

routeroutercorrectclientredirectreact
90%

1. When user tries to access protected route, redirect to /login with React-Router.,2. In /login component, save previous route to localStorage so I can later redirect back there after authentication:,Unauthenticated user attempts to access protected client route (something like /posts/:postid, and is redirected to /login. (React Router is handling this part)

First define a <PrivateRoute> component:

// App.jsx

const PrivateRoute = ({ component: Component, loggedIn, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props =>
        loggedIn === true ? (
          <Component {...rest} {...props} />
        ) : (
          <Redirect
            to={{ pathname: "/login", state: { from: props.location } }}
          />
        )
      }
    />
  );
};

Then pass the loggedIn property to the route:

// App.jsx

<PrivateRoute
  loggedIn={this.props.appState.loggedIn}
  path="/poll/:id"
  component={ViewPoll}
/>

2. In /login component, save previous route to localStorage so I can later redirect back there after authentication:

// Login.jsx

componentDidMount() {
   const {
      from
   } = this.props.location.state || {
      from: {
         pathname: "/"
      }
   };
   const pathname = from.pathname;
   window.localStorage.setItem("redirectUrl", pathname);
}

3. In SocialAuth callback, redirect to profile page on client, adding userId and token as route params

// auth.ctrl.js

exports.socialAuthCallback = (req, res) => {
   if (req.user.err) {
      res.status(401).json({
         success: false,
         message: `social auth failed: ${req.user.err}`,
         error: req.user.err
      })
   } else {
      if (req.user) {
         const user = req.user._doc;
         const userInfo = helpers.setUserInfo(user);
         const token = helpers.generateToken(userInfo);
         return res.redirect(`${CLIENT_URL}/user/${userObj._doc._id}/${token}`);
      } else {
         return res.redirect('/login');
      }
   }
};

4. In the Profile component on the client, pull the userId and token out of the route params, immediately remove them using window.location.replaceState, and save them to localStorage. Then check for a redirectUrl in localStorage. If it exists, redirect and then clear the value

// Profile.jsx

componentWillMount() {
   let userId, token, authCallback;
   if (this.props.match.params.id) {
      userId = this.props.match.params.id;
      token = this.props.match.params.token;
      authCallback = true;

      // if logged in for first time through social auth,
      // need to save userId & token to local storage
      window.localStorage.setItem("userId", JSON.stringify(userId));
      window.localStorage.setItem("authToken", JSON.stringify(token));
      this.props.actions.setLoggedIn();
      this.props.actions.setSpinner("hide");

      // remove id & token from route params after saving to local storage
      window.history.replaceState(null, null, `${window.location.origin}/user`);
   } else {
      console.log("user id not in route params");

      // if userId is not in route params
      // look in redux store or local storage
      userId =
         this.props.profile.user._id ||
         JSON.parse(window.localStorage.getItem("userId"));
      if (window.localStorage.getItem("authToken")) {
         token = window.localStorage.getItem("authToken");
      } else {
         token = this.props.appState.authToken;
      }
   }

   // retrieve user profile & save to app state
   this.props.api.getProfile(token, userId).then(result => {
      if (result.type === "GET_PROFILE_SUCCESS") {
         this.props.actions.setLoggedIn();
         if (authCallback) {
            // if landing on profile page after social auth callback,
            // check for redirect url in local storage
            const redirect = window.localStorage.getItem("redirectUrl");
            if (redirect) {
               // redirect to originally requested page and then clear value
               // from local storage
               this.props.history.push(redirect);
               window.localStorage.setItem("redirectUrl", null);
            }
         }
      }
   });
}
load more v
88%

1. When user tries to access protected route, redirect to /login with React-Router.,2. In /login component, save previous route to localStorage so I can later redirect back there after authentication:,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.

First define a <PrivateRoute> component:

// App.jsx

const PrivateRoute = ({ component: Component, loggedIn, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props =>
        loggedIn === true ? (
          <Component {...rest} {...props} />
        ) : (
          <Redirect
            to={{ pathname: "/login", state: { from: props.location } }}
          />
        )
      }
    />
  );
};
load more v
72%

I broke down this tutorial into two parts. The first part focuses on building authentication routes in the backend. The second part focuses on building UI components in the front-end using React.,/routes/auth-routes.js contains all the authentication endpoints.,User clicks on login button which redirects to Twitter OAuth authentication page.

I separated server and client logic in different folders to be clear and clean. My server is running on localhost:4000, whereas the client is running on localhost:3000. (Feel free to define your own port.)

| --twitter - auth - project | | --server | | | --index.js | | | --package.json | | --client | | | --src | | | | --index.jsx | | | | --package.json
load more v
65%

Correctly implementing authentication and error messages that mitigate user ID and password enumeration.,You can also use custom domains to let Auth0 do the authentication heavy lifting for you without compromising on branding experience.,In this tutorial, you'll learn how to secure Node.js web application built with the Express framework. You'll use Passport.js with Auth0 to manage user authentication and protect routes of a client that consumes an API. The client is server-side rendered using Pug templates styled with CSS.

🛠️️ Clone the project repository:

git clone - b starter git @github.com: auth0 - blog / wab - portal - express.git
load more v
75%

Authenticating Users in a Node App using Express & Passport (Part One),Local Authentication Using Passport in Node.js,User Authentication with Passport and Koa

Pretag
 Pretag team - issue, fix, solve, resolve
40%

If our application is functioning properly we should see a message, part of which reads, "listening on port 5000!" or whichever port you indicated your application to run on. Go ahead and kill the server by pressing Control-C, it is time to add our templates so that we will have something pretty to look at!,Write routes for our Local functionality,Even though we have not set up our Passport Strategies yet, we can now run our application and view the homepage and sign in page from our browsers. We are well on our way!

From a shell on your local machine, connect to your new server with the following command. Replace "YOUR.VPS.IP" with your server's public IP address.

ssh root @YOUR.VPS.IP
load more v
22%

Well, we’re finally at the end. In this article, we learned how to implement local authentication using Passport in a Node.js application. In the process, we also learned how to connect to MongoDB using Mongoose.,In this tutorial, I’ll demonstrate how to use Passport to implement local authentication (that is, logging in with a username and password) with a MongoDB back end. If you’re looking to implement authentication via the likes of Facebook or GitHub, please refer to this tutorial.,That’s all for the Mongoose setup. We can now move on to implementing our Passport strategy.

Pretag
 Pretag team - issue, fix, solve, resolve

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