错误保存代码: 使用 passport-google 时出现 GaxiosError: 无效请求。

huangapple go评论82阅读模式
英文:

Error saving code: GaxiosError: invalid_request when using passport-google

问题

以下是您要翻译的内容:

这是我的POST请求

app.post('/auth/google', async (req, res) => {
    try {
        const {
            code
        } = req.body;
      
    } catch (error) {
       
    }
});

我从前端获取令牌

4/0AbUR2VMmkydX1bHZeUIq6xm8558a8EyxdNhc0q2ouILfp2Cc3gL3mSd3w83Qn6JJ4jaqdg

请问如何验证代码并使用Google身份验证库获取用户详细信息

const verifyGoogleAccessToken = async (accessToken) => {
    oauth2Client.setCredentials({
        access_token: accessToken
    });

    const userinfo = await oauth2Client.request({
        url: "https://www.googleapis.com/oauth2/v3/userinfo",
    });

    return userinfo.data;
};

请帮忙,我已经在这上面忙了几天了。

英文:

this my post request

app.post('/auth/google', async (req, res) => {
    try {
        const {
            code
        } = req.body;
      
    } catch (error) {
       
    }
});

i'm getting the token from my front end

 4/0AbUR2VMmkydX1bHZeUIq6xm8558a8EyxdNhc0q2ouILfp2Cc3gL3mSd3w83Qn6JJ4jaqdg

please how can i verify the code and get the user details using google-auth-library

const verifyGoogleAccessToken = async (accessToken) => {
    oauth2Client.setCredentials({
        access_token: accessToken
    });

    const userinfo = await oauth2Client.request({
        url: "https://www.googleapis.com/oauth2/v3/userinfo",
    });

    return userinfo.data;
};

please i need help,i've been on this for days

答案1

得分: 1

  1. 从前端调用 Google SDK。
  2. 提取代码或访问令牌并发送到您的后端进行验证。
  3. 使用您的后端 Google API 验证代码或令牌。
  4. 如果验证成功,在后端登录它们,然后发送响应到前端。
const express = require('express');
const axios = require('axios');
const cors = require('cors');

const { OAuth2Client } = require('google-auth-library');
const oauth2Client = new OAuth2Client()

const app = express();

// 为所有路由启用 CORS
app.use(cors());
  app.post('/auth', async (req, res) => {
    try {
      const code = req.headers.authorization;
      console.log('Authorization Code:', code);

      // 用授权代码交换访问令牌
      const response = await axios.post(
        'https://oauth2.googleapis.com/token',
        {
          code,
          client_id: '58730156701-d27fqgjb0.apps.googleusercontent.com',
          client_secret: 'GOCSPX-u02eNiucPXxRAsQVi',
          redirect_uri: 'postmessage',
          grant_type: 'authorization_code'
        }
      );
      const accessToken = response.data.access_token;
      console.log('Access Token:', accessToken);

      // 使用访问令牌获取用户详细信息
      const userResponse = await axios.get(
        'https://www.googleapis.com/oauth2/v3/userinfo',
        {
          headers: {
            Authorization: `Bearer ${accessToken}`
          }
        }
      );
      const userDetails = userResponse.data;
      console.log('User Details:', userDetails);

      // 处理用户详细信息并执行必要的操作

      res.status(200).json({ message: 'Authentication successful' });
    } catch (error) {
      console.error('Error saving code:', error);
      res.status(500).json({ message: 'Failed to save code' });
    }
  });


app.listen(4000, () => {
    console.log('Server running on port 4000');
});
英文:
  1. Call the Google SDK from the frontend.
  2. Extract the code or access token and send to your backend for verification.
  3. Use your backend Google api to verify the code or token.
  4. If verified, sign them in the backend and then send a response to frontend
const express = require('express');
const axios = require('axios');
const cors = require('cors');
const { OAuth2Client } = require('google-auth-library');
const oauth2Client = new OAuth2Client()
const app = express();
// Enable CORS for all routes
app.use(cors());
app.post('/auth', async (req, res) => {
try {
const code = req.headers.authorization;
console.log('Authorization Code:', code);
// Exchange the authorization code for an access token
const response = await axios.post(
'https://oauth2.googleapis.com/token',
{
code,
client_id: '58730156701-d27fqgjb0.apps.googleusercontent.com',
client_secret: 'GOCSPX-u02eNiucPXxRAsQVi',
redirect_uri: 'postmessage',
grant_type: 'authorization_code'
}
);
const accessToken = response.data.access_token;
console.log('Access Token:', accessToken);
// Fetch user details using the access token
const userResponse = await axios.get(
'https://www.googleapis.com/oauth2/v3/userinfo',
{
headers: {
Authorization: `Bearer ${accessToken}`
}
}
);
const userDetails = userResponse.data;
console.log('User Details:', userDetails);
// Process user details and perform necessary actions
res.status(200).json({ message: 'Authentication successful' });
} catch (error) {
console.error('Error saving code:', error);
res.status(500).json({ message: 'Failed to save code' });
}
});
app.listen(4000, () => {
console.log('Server running on port 4000');
});

答案2

得分: 0

通过授权码获取访问令牌。在设置oauth2Client的凭据之后,有两种选择来获取用户信息:

  • 使用googleapis
  • oauth2Client.request({url: 'https://www.googleapis.com/oauth2/v3/userinfo'})

一个可工作的示例:

//@ts-nocheck
import { OAuth2Client } from 'google-auth-library';
import { google } from 'googleapis';
import http from 'http';
import url from 'url';

const keys = require('../../../.svc/client_secret.json');

const oAuth2Client = new OAuth2Client(keys.web.client_id, keys.web.client_secret, keys.web.redirect_uris[0]);
const authorizeUrl = oAuth2Client.generateAuthUrl({
  access_type: 'offline',
  scope: 'https://www.googleapis.com/auth/userinfo.profile',
});

http
  .createServer(async (req, res) => {
    try {
      if (req.url && req.url.indexOf('/oauth2callback') > -1) {
        const qs = new url.URL(req.url, 'http://localhost:3000').searchParams;
        const code = qs.get('code');
        console.log(`Code is ${code}`);

        const r = await oAuth2Client.getToken(code);
        oAuth2Client.setCredentials(r.tokens);
        console.info('Tokens acquired.');

        const res1 = await oAuth2Client.request({
          url: 'https://www.googleapis.com/oauth2/v3/userinfo',
        });
        console.log('res1.data: ', res1.data);

        const oauth2 = google.oauth2({ version: 'v2', auth: oAuth2Client });
        const res2 = await oauth2.userinfo.get();
        console.log('res2.data', res2.data);

        res.end('Authentication successful! Please return to the console.');
      }
    } catch (e) {
      console.error(e);
    }
  })
  .listen(3000, () => console.log(`Open ${authorizeUrl}`));

服务器日志:

$ npx ts-node index.ts 
Open https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&response_type=code&client_id=16536262744-7ob1su0o1hn4t79482e41mirhc102mvh.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Foauth2callback
Code is 4/0AbUR2VMmkydX1bHZeUIq6xm8558a8EyxdNhc0q2ouILfp2Cc3gL3mSd3w83Qn6JJ4jaqdg
Tokens acquired.
res1.data:  {
  sub: '104760625496851302622',
  name: 'slideshowp2',
  given_name: 'slideshowp2',
  picture: 'https://lh3.googleusercontent.com/a/AAcHTtf5h0cmKv3cOX8AEMN9jNpaRxpU2Hv2CJEe54EL=s96-c',
  locale: 'zh-CN'
}
res2.data {
  id: '104760625496851302622',
  name: 'slideshowp2',
  given_name: 'slideshowp2',
  picture: 'https://lh3.googleusercontent.com/a/AAcHTtf5h0cmKv3cOX8AEMN9jNpaRxpU2Hv2CJEe54EL=s96-c',
  locale: 'zh-CN'
}

包版本:

"google-auth-library": "^8.8.0",
"googleapis": "^118.0.0",
英文:

Retrieve access token via authorization code. After setting the credentials for oauth2Client, there are two choices to get the user info:

  • use googleapis library
  • oauth2Client.request({url: 'https://www.googleapis.com/oauth2/v3/userinfo'})

A working example:

//@ts-nocheck
import { OAuth2Client } from 'google-auth-library';
import { google } from 'googleapis';
import http from 'http';
import url from 'url';

const keys = require('../../../.svc/client_secret.json');

const oAuth2Client = new OAuth2Client(keys.web.client_id, keys.web.client_secret, keys.web.redirect_uris[0]);
const authorizeUrl = oAuth2Client.generateAuthUrl({
  access_type: 'offline',
  scope: 'https://www.googleapis.com/auth/userinfo.profile',
});

http
  .createServer(async (req, res) => {
    try {
      if (req.url && req.url.indexOf('/oauth2callback') > -1) {
        const qs = new url.URL(req.url, 'http://localhost:3000').searchParams;
        const code = qs.get('code');
        console.log(`Code is ${code}`);

        const r = await oAuth2Client.getToken(code);
        oAuth2Client.setCredentials(r.tokens);
        console.info('Tokens acquired.');

        const res1 = await oAuth2Client.request({
          url: 'https://www.googleapis.com/oauth2/v3/userinfo',
        });
        console.log('res1.data: ', res1.data);

        const oauth2 = google.oauth2({ version: 'v2', auth: oAuth2Client });
        const res2 = await oauth2.userinfo.get();
        console.log('res2.data', res2.data);

        res.end('Authentication successful! Please return to the console.');
      }
    } catch (e) {
      console.error(e);
    }
  })
  .listen(3000, () => console.log(`Open ${authorizeUrl}`));

Server logs:

$ npx ts-node index.ts 
Open https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&response_type=code&client_id=16536262744-7ob1su0o1hn4t79482e41mirhc102mvh.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Foauth2callback
Code is 4/0AbUR2VMmkydX1bHZeUIq6xm8558a8EyxdNhc0q2ouILfp2Cc3gL3mSd3w83Qn6JJ4jaqdg
Tokens acquired.
res1.data:  {
  sub: '104760625496851302622',
  name: 'slideshowp2',
  given_name: 'slideshowp2',
  picture: 'https://lh3.googleusercontent.com/a/AAcHTtf5h0cmKv3cOX8AEMN9jNpaRxpU2Hv2CJEe54EL=s96-c',
  locale: 'zh-CN'
}
res2.data {
  id: '104760625496851302622',
  name: 'slideshowp2',
  given_name: 'slideshowp2',
  picture: 'https://lh3.googleusercontent.com/a/AAcHTtf5h0cmKv3cOX8AEMN9jNpaRxpU2Hv2CJEe54EL=s96-c',
  locale: 'zh-CN'
}

package versions:

"google-auth-library": "^8.8.0",
"googleapis": "^118.0.0",

huangapple
  • 本文由 发表于 2023年6月16日 15:36:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76487931.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定