如何使用节点 google 客户端 api 获取带有已获取令牌的用户配置文件?
How to use the node google client api to get user profile with already fetched token?
通过 curl
获取用户个人资料信息
curl -i https://www.googleapis.com/userinfo/v2/me -H "Authorization: Bearer a-google-account-access-token"
通过 node https get 请求获取用户个人资料信息
const https = require('https');
function getUserData(accessToken) {
var options = {
hostname: 'www.googleapis.com',
port: 443,
path: '/userinfo/v2/me',
method: 'GET',
json: true,
headers:{
Authorization: 'Bearer ' + accessToken
}
};
console.log(options);
var getReq = https.request(options, function(res) {
console.log("\nstatus code: ", res.statusCode);
res.on('data', function(response) {
try {
var resObj = JSON.parse(response);
console.log("response: ", resObj);
} catch (err) {
console.log(err);
}
});
});
getReq.end();
getReq.on('error', function(err) {
console.log(err);
});
}
var token = "a-google-account-access-token";
getUserData(token)
如果我已经拥有访问令牌,我如何使用此google node api client library获取用户个人资料信息?我可以使用上面的代码来获取配置文件,但我认为使用 google api 库可能更好,但我不知道如何使用此节点 google api 客户端库。
玩这个可以得到一个临时的访问令牌playground
您可以使用 the google node API client library 检索用户个人资料。在这种情况下,请检索访问令牌和刷新令牌作为 https://www.googleapis.com/auth/userinfo.profile
的范围。示例脚本如下。使用本示例时,请设置您的ACCESS TOKEN。
示例脚本:
var google = require('googleapis').google;
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2();
oauth2Client.setCredentials({access_token: 'ACCESS TOKEN HERE'});
var oauth2 = google.oauth2({
auth: oauth2Client,
version: 'v2'
});
oauth2.userinfo.get(
function(err, res) {
if (err) {
console.log(err);
} else {
console.log(res);
}
});
结果:
{
id: '#####',
name: '#####',
given_name: '#####',
family_name: '#####',
link: '#####',
picture: '#####',
gender: '#####',
locale: '#####'
}
如果我误解了你的问题,我很抱歉。
2021年解决方案
这个答案可能会偏离最初提出的问题,但我认为这对某些通过生成 AuthUrl 并将其发送到客户端然后接收在后端获取 google 用户信息的人很有用用户从客户端授予权限后回调URL中的数据响应。
一些全局声明
import { google } from "googleapis";
const Oauth2Client = new google.auth.OAuth2(
googleCredentials.CLIENT_ID,
googleCredentials.CLIENT_SECRET,
googleCredentials.REDIRECT_URI
);
使用范围
生成授权URL
const SCOPE = [
'https://www.googleapis.com/auth/userinfo.profile', // get user info
'https://www.googleapis.com/auth/userinfo.email', // get user email ID and if its verified or not
];
const auth_url = Oauth2Client.generateAuthUrl({
access_type: "offline",
scope: SCOPE,
prompt: "consent",
state: "GOOGLE_LOGIN",
});
return res.json({ url: auth_url }); // send the Auth URL to the front end
在回调中获取用户数据
let code = req.query.code; // get the code from req, need to get access_token for the user
let { tokens } = await Oauth2Client.getToken(code); // get tokens
let oauth2Client = new google.auth.OAuth2(); // create new auth client
oauth2Client.setCredentials({access_token: tokens.access_token}); // use the new auth client with the access_token
let oauth2 = google.oauth2({
auth: oauth2Client,
version: 'v2'
});
let { data } = await oauth2.userinfo.get(); // get user info
console.log(data);
如有任何困惑或错误,欢迎在评论中讨论
Based on this anser:
这是实现相同结果的另一种较短的方法。
const { google } = require('googleapis');
const oauth2Client = new google.auth.OAuth2()
const tokenInfo = await oauth2Client.getTokenInfo(*YourAccessToken*);
console.log(tokenInfo);
您还可以解码来自 oAuth2Client.getToken()
的响应中的 id_token
。
请记住,您需要为您的应用启用必要的范围才能使响应具有此 id_token
。例如,假设我们只需要用户的电子邮件。所以我们将使用,
https://www.googleapis.com/auth/userinfo.email
要解码令牌,
const response = await oAuth2Client.getToken(code);
const userInfo = JSON.parse(Buffer.from(response.tokens.id_token.split('.')[1], 'base64').toString());
console.log(userInfo);
这将输出,
{
"iss": "https://accounts.google.com",
"azp": "1234987819200.apps.googleusercontent.com",
"aud": "1234987819200.apps.googleusercontent.com",
"sub": "10769150350006150715113082367",
"at_hash": "HK6E_P6Dh8Y93mRNtsDB1Q",
"hd": "example.com",
"email": "jsmith@example.com",
"email_verified": "true",
"iat": 1353601026,
"exp": 1353604926,
"nonce": "0394852-3190485-2490358"
}
这个标记只是一个 JWT
object which can be decoded eaisily. You can check this documentation 并且看到甚至 Google 推荐这个。此方法的优点是您无需向 Google API 发出额外请求即可获取用户信息。
通过 curl
获取用户个人资料信息curl -i https://www.googleapis.com/userinfo/v2/me -H "Authorization: Bearer a-google-account-access-token"
通过 node https get 请求获取用户个人资料信息
const https = require('https');
function getUserData(accessToken) {
var options = {
hostname: 'www.googleapis.com',
port: 443,
path: '/userinfo/v2/me',
method: 'GET',
json: true,
headers:{
Authorization: 'Bearer ' + accessToken
}
};
console.log(options);
var getReq = https.request(options, function(res) {
console.log("\nstatus code: ", res.statusCode);
res.on('data', function(response) {
try {
var resObj = JSON.parse(response);
console.log("response: ", resObj);
} catch (err) {
console.log(err);
}
});
});
getReq.end();
getReq.on('error', function(err) {
console.log(err);
});
}
var token = "a-google-account-access-token";
getUserData(token)
如果我已经拥有访问令牌,我如何使用此google node api client library获取用户个人资料信息?我可以使用上面的代码来获取配置文件,但我认为使用 google api 库可能更好,但我不知道如何使用此节点 google api 客户端库。
玩这个可以得到一个临时的访问令牌playground
您可以使用 the google node API client library 检索用户个人资料。在这种情况下,请检索访问令牌和刷新令牌作为 https://www.googleapis.com/auth/userinfo.profile
的范围。示例脚本如下。使用本示例时,请设置您的ACCESS TOKEN。
示例脚本:
var google = require('googleapis').google;
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2();
oauth2Client.setCredentials({access_token: 'ACCESS TOKEN HERE'});
var oauth2 = google.oauth2({
auth: oauth2Client,
version: 'v2'
});
oauth2.userinfo.get(
function(err, res) {
if (err) {
console.log(err);
} else {
console.log(res);
}
});
结果:
{
id: '#####',
name: '#####',
given_name: '#####',
family_name: '#####',
link: '#####',
picture: '#####',
gender: '#####',
locale: '#####'
}
如果我误解了你的问题,我很抱歉。
2021年解决方案
这个答案可能会偏离最初提出的问题,但我认为这对某些通过生成 AuthUrl 并将其发送到客户端然后接收在后端获取 google 用户信息的人很有用用户从客户端授予权限后回调URL中的数据响应。
一些全局声明
import { google } from "googleapis";
const Oauth2Client = new google.auth.OAuth2(
googleCredentials.CLIENT_ID,
googleCredentials.CLIENT_SECRET,
googleCredentials.REDIRECT_URI
);
使用范围
生成授权URLconst SCOPE = [
'https://www.googleapis.com/auth/userinfo.profile', // get user info
'https://www.googleapis.com/auth/userinfo.email', // get user email ID and if its verified or not
];
const auth_url = Oauth2Client.generateAuthUrl({
access_type: "offline",
scope: SCOPE,
prompt: "consent",
state: "GOOGLE_LOGIN",
});
return res.json({ url: auth_url }); // send the Auth URL to the front end
在回调中获取用户数据
let code = req.query.code; // get the code from req, need to get access_token for the user
let { tokens } = await Oauth2Client.getToken(code); // get tokens
let oauth2Client = new google.auth.OAuth2(); // create new auth client
oauth2Client.setCredentials({access_token: tokens.access_token}); // use the new auth client with the access_token
let oauth2 = google.oauth2({
auth: oauth2Client,
version: 'v2'
});
let { data } = await oauth2.userinfo.get(); // get user info
console.log(data);
如有任何困惑或错误,欢迎在评论中讨论
Based on this anser:
这是实现相同结果的另一种较短的方法。
const { google } = require('googleapis');
const oauth2Client = new google.auth.OAuth2()
const tokenInfo = await oauth2Client.getTokenInfo(*YourAccessToken*);
console.log(tokenInfo);
您还可以解码来自 oAuth2Client.getToken()
的响应中的 id_token
。
请记住,您需要为您的应用启用必要的范围才能使响应具有此 id_token
。例如,假设我们只需要用户的电子邮件。所以我们将使用,
https://www.googleapis.com/auth/userinfo.email
要解码令牌,
const response = await oAuth2Client.getToken(code);
const userInfo = JSON.parse(Buffer.from(response.tokens.id_token.split('.')[1], 'base64').toString());
console.log(userInfo);
这将输出,
{
"iss": "https://accounts.google.com",
"azp": "1234987819200.apps.googleusercontent.com",
"aud": "1234987819200.apps.googleusercontent.com",
"sub": "10769150350006150715113082367",
"at_hash": "HK6E_P6Dh8Y93mRNtsDB1Q",
"hd": "example.com",
"email": "jsmith@example.com",
"email_verified": "true",
"iat": 1353601026,
"exp": 1353604926,
"nonce": "0394852-3190485-2490358"
}
这个标记只是一个 JWT
object which can be decoded eaisily. You can check this documentation 并且看到甚至 Google 推荐这个。此方法的优点是您无需向 Google API 发出额外请求即可获取用户信息。