如何使 Passport Google OAuth2.0 与 React-google-login 一起使用?

Ale*_*aga 5 node.js google-oauth reactjs passport.js

我的应用程序使用 Passport Google OAuth2.0,但我发现我需要在前端获得响应来设置授予对私有路由的访问权限的自定义挂钩的状态,而这对于 Passport 来说似乎不可能,因此我遇到了这个react-google-login npm 包,它允许我定义onSuccess回调。

现在,是否可以使这个 React 包与 Passport Google OAuth 策略一起使用而不会发生冲突?我希望 Passport 继续处理数据库上的用户创建并生成 JWT 令牌。我只是不知道如何让他们以我可以回调的方式相互通信onSuccess

我的Google策略和身份验证路线完全是这样的:

护照.js

passport.use(
    new GoogleStrategy(
      {
        clientID: process.env.GOOGLE_CLIENT_ID,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET,
        callbackURL: `${serverUrl}${process.env.GOOGLE_CALLBACK_URL}`,
      },
      function (accessToken, refreshToken, profile, cb) {
        User.findOrCreate(
          { googleId: profile.id },
          { first_name: profile.displayName, email: profile._json.email },
          function (err, user) {
            return cb(err, user);
          }
        );
      }
    )
  );
Run Code Online (Sandbox Code Playgroud)

auth.js

router.get(
  "/google",
  passport.authenticate("google", {
    scope: ["email", "profile"],
  })
);

const clientUrl =
  process.env.NODE_ENV === "production"
    ? process.env.CLIENT_URL_PROD
    : process.env.CLIENT_URL_DEV;

router.get(
  "/google/movie-log",
  passport.authenticate("google", {
    failureRedirect: clientUrl + "/login",
    session: false,
  }),
  (req, res) => {
    const token = req.user.generateJWT();

    res.cookie("access_token", token, { httpOnly: true, sameSite: true });

    res.redirect(clientUrl + "/diary");
  }
);

module.exports = router;
Run Code Online (Sandbox Code Playgroud)

反应组件:

登录.js

function handleSuccess(response) {
    authContext.setIsAuthenticated(true);
    navigate(state?.path || "/diary");
    console.log("Successfully authenticated");
}

function handleFailure(response) {
    console.log("Authentication failed");
}

<GoogleLogin
  clientId="my client ID"
  uxMode="redirect"
  scope="profile email"
  redirectUri="http://localhost:5000/auth/google/movie-log"
  onSuccess={handleSuccess}
  onFailure={handleFailure}
  cookiePolicy={"single_host_origin"}
/>
Run Code Online (Sandbox Code Playgroud)