0


来自客户端 react 应用程序的 react-google-login 使用发布请求客户端代码将响应发送回 Nodejs 服务器-

import axios from 'axios';
import React, { Component } from 'react';
import GoogleLogin from 'react-google-login';
import refreshTokenSetup from '../../utils/refreshToken';

const clientId =
 'xxxxxx-xfdgsdjg3gfxxxxxxxxxxx.apps.googleusercontent.com';


function Login() {
 const onSuccess = (res) => {
   console.log('Login Success: currentUser:', res.profileObj);
   alert(
     `Logged in successfully welcome ${res.profileObj.name} . \n See console for full profile object.`
   );
   axios
     .post('http://localhost:5000/auth/checkToken', { body: res.tokenId })
     .then()
     .catch((err) => {
       console.log(err);
     });
 };

 const onFailure = (res) => {
   console.log('Login failed: res:', res);
   alert(
     `Failed to login.  Please ping this to repo owner twitter.com/sivanesh_fiz`
   );
 };

 return (
   <div>
     <GoogleLogin
       clientId={clientId}
       buttonText='Login'
       onSuccess={onSuccess}
       onFailure={onFailure}
       cookiePolicy={'single_host_origin'}
       style={{ marginTop: '100px' }}
       isSignedIn={true}
     />
   </div>
 );
}

export default Login;

后端路线-

const { OAuth2Client } = require('google-auth-library');
const key = require('../config/key');
module.exports = {
  checkToken: (req, res, next) => {
    console.log('checking begins...', req.body);

    const client = new OAuth2Client(key.GOOGLE_CLIENT_ID);
    async function verify() {
      const ticket = await client.verifyIdToken({
        idToken: req.body,
        audience: key.GOOGLE_CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
        // Or, if multiple clients access the backend:
        //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
      });
      const payload = ticket.getPayload();
      const userid = payload['sub'];
      // If request specified a G Suite domain:
      // const domain = payload['hd'];
    }
    verify().catch(console.error);
  },
};

上述代码参考了官方 Google 文档,网址为 - https://developers.google.com/identity/sign-in/web/backend-auth

现在一切正常,用户在客户端登录,tokenId 被发送回服务器,并且可以通过控制台记录它来验证,即使在https://jwt.io/上,但显示以下错误 -

TypeError: jwt.split is not a function
    at OAuth2Client.verifySignedJwtWithCertsAsync (E:\Projects\EAbackend\node_modules\google-auth-library\build\src\auth\oauth2client.js:528:30)
    at OAuth2Client.verifyIdTokenAsync (E:\Projects\EAbackend\node_modules\google-auth-library\build\src\auth\oauth2client.js:394:34)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async verify (E:\Projects\EAbackend\middleware\auth.js:9:22)
4

1 回答 1

0

问题在于idToken: req.body,
req.body存在令牌的主体对象,只需将其更改为 req.body.body 即可解决错误。
这个问题可能非常初级,但花了我很多时间,并且没有可用的在线资源可以为我指明任何方向。
检查 POST 请求,您会发现错误。

于 2021-03-27T13:55:08.317 回答