如何从服务器上的回调向客户端发送Oauth令牌?

时间:2018-08-21 13:25:31

标签: express login oauth-2.0 axios passport-google-oauth

我正在使用expressJs和护照进行身份验证。我正在使用Google Oauth2.0通过标准Passport GoogleStrategy登录。在客户端,我使用axios向服务器发送登录请求。我的登录路线是:

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

router.get(
    "/google/callback",
    passport.authenticate("google", { failureRedirect: "/"}),
    function(req, res) {

        const token = jwt.sign({id: req.user.id}, configAuth.secretKey);
        console.log("generated token: ", token);
        res.json({success: true, token: 'bearer ' + token});

    }
);

我正在使用回调中的用户信息来生成要发送给客户端的JWT。

在客户端,我使用axios发送请求并获取JWT并将其存储在localstore中。

axios.get('http://localhost:3001/google')
  .then((result) => {
    console.log("result", result);
    localStorage.setItem('jwtToken', result.data.token);
  })
  .catch((error) => {
    // if(error.response.status === 401) {
    //   this.setState({ message: 'Login failed. Username or password not match' });
    // }
    console.log("Login error", error);
  });

但是Axios不等待重定向发生,而是返回带有Loading ...消息的HTML文档。如果您尝试在浏览器中访问API,它将返回所需的JSON对象。有没有办法等待重定向。我应该使用另一个库发送登录请求吗?

我尝试使用

将令牌作为url参数发送
  

res.redirect()

,但是客户端和服务器位于不同的端口,因此无法正常工作。 还有另一种方法吗?

2 个答案:

答案 0 :(得分:0)

Google的OAuth2路径会重定向您的浏览器,从而导致页面重新加载,这需要两次完成。结果,您的客户端代码

axios.get('http://localhost:3001/google')
  .then((result) => {
    console.log("result", result);
    localStorage.setItem('jwtToken', result.data.token);
  })...

将永远不会到达.then()块。您可能会在浏览器中看到它。您单击按钮或其他内容以导航到'http://localhost:3001/google',然后localhost:3001服务器将浏览器重定向到Google登录页面。现在,您的浏览器位于登录页面上,它不再存储上面的axios.get语句-该网页代码已消失。

您需要使用服务器发送以响应

的客户端代码处理JWT。
axios.get('http://localhost:3001/google/callback').

这是浏览器在OAuth2路径中的最后停留站-一旦到达该位置,就不会再次重定向。您可以将axios.get函数放在该客户端代码的上方。

答案 1 :(得分:0)

如果您还没有解决问题,则可以使用“ googleTokenStategy”替代通行证js上的googleOAuth来解决。这样,您可以使用react的GoogleLogin插件从前端接收访问令牌,并通过axios.post将其发送到后端链接,然后设置jwt。参考here