在客户端和服务器运行在不同端口reactJS和nodeJS的系统中,使用Google身份验证处理登录

问题描述

当前,我正在使用客户端和服务器上的其他端口进行PROJ工作。每当在Server中成功登录时,我都会对客户端中的事件处理感到困惑。我也不知道如何在客户端登录。我正在使用PassportJS。 我添加一个按钮来处理客户端中的onClick事件,而不是通过以下方式开始调用服务器与Google进行身份验证:

let gg_window = window.open("http://localhost:7000/authentication/google/auth","_self");

我还配置了我的Google应用程序以进行身份​​验证,如下所示(客户端在端口9000上运行,服务器在端口7000上运行) Google Authentication configuration

在服务器中: 我做了一个端点来处理URL:

router.get('/google/auth',passport.authenticate('google',{
  scope:
    'https://www.googleapis.com/auth/plus.me https://www.google.com/m8/Feeds https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile'
  })
);

router.get('/google/auth/redirect',passport.authenticate('google'),(req,res) => {
    const token = jwt.sign(JSON.stringify(req.user),SECRET);
    res.redirect("http://localhost:9000/google/auth/success?username=" + req.user.username + "&token=" + token);
  });

我可以获取令牌,用户名...并可以重定向到客户端 在客户中 我正在使用Redux-Saga,之前使用用户名和密码进行常规登录。 我现在该怎么办?感谢您的帮助。

解决方法

我通过这种方式实现了此功能:

在客户端中

将组件制作为将端点“ / google / auth /成功”处理为:

  <Route
    component={ConfirmAccount}
    path="/google/auth/success"
  />

在ConfirmAccountView中,我进行了一个视图以确认用户输入的UserName。然后有一个按钮来确认帐户。

我使用了Hook的useEffect()来处理此View并将数据保存到localStorage中,例如:

  useEffect(() => {
    if (isLoggedIn === true) {
      localStorage.setItem("authorize_token",authorization_token)
      localStorage.setItem("user",username)
      history.push('/profile')
    }
    if (error) {
      NotificationManager.error(`${error}`,"Login Failed")
    }
    if (localStorage.getItem("authorize_token")) {
      history.push('/profile')
    }

  },[isLoggedIn,error]);

我还创建了一个connect函数来获取状态并将动作发布到reducer:

const mapStateToProps = createStructuredSelector({
  isLoggedIn: isLoggedIn(),authorization: authorization(),error: displayError()
});

const mapDispatchToProps = dispatch => {
  return {
    loginSuccessWithGG: username => {
      dispatch(loginSuccessWithGG(username)); // Action dispatch for signin
    }
  }
};

export default connect(mapStateToProps,mapDispatchToProps)(ConfirmAccount);

在Redux-Saga中,我做了一个动作,将动作SignInSuccessful调度到reducer,然后Reducer会将状态isLoggedIn设置为True。 现在工作了。