【发布时间】:2021-12-14 06:58:07
【问题描述】:
我正在尝试列出经过身份验证的 Google 帐户下的企业。我已经完成了 Oauth2 流程并获得了包含 access_token, id_token,refresh_token and expiry_date
现在,当我尝试列出该帐户下的企业时,我不断收到Unauthorized Error。
以下是我的流程:
initOAuth2Client() {
return new google.auth.OAuth2(
process.env.GOOGLE_CLIENT_ID,
process.env.GOOGLE_CLIENT_SECRET,
process.env.GOOGLE_REDIRECT_URL
);
}
//Authorization Code
async authenticateAgainstGoogleMyBusiness() {
let oauth2Client = module.exports.initOAuth2Client();
const scopes = [
'https://www.googleapis.com/auth/business.manage',
'https://www.googleapis.com/auth/userinfo.profile'
];
const state = ....
const url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: scopes,
state: state,
prompt: 'consent'
});
}
然后对于我的 Oauth 回调处理程序,我有这个
async googleOAuthCallbackHandler(req, res) {
let oauth2Client = module.exports.initOAuth2Client();
let { code, state } = req.query;
const oauth2Client = module.exports.initOAuth2Client();
const { tokens } = await oauth2Client.getToken(code);
//this is where I saved the tokens exactly as received.
}
async fetchGoogleMyBusinessAccounts() {
let {access_token} = fetchTokenFromDatabase(); //This is how I retrieved the access tokens saved by the previous function.
console.log(`Fetching GMB Accounts`);
let accountsUrls = `https://mybusinessaccountmanagement.googleapis.com/v1/accounts`;
try {
let headers = {
'Authorization': `Bearer ${access_token}`
}
let response = axios.get(accountsUrls, {
headers: headers
});
let data = response.data;
console.log(`GMB Accounts response = ${JSON.stringify(data, null, 2)}`);
} catch (e) {
console.log('Error retrieving GMB Accounts:Full error below:');
console.log(e); //I keep getting Unauthorized even though I authorized the process on the oauth consent screen
}
}
我该如何解决这个问题?
【问题讨论】:
-
完整的错误信息是什么。请附上您的授权码。您如何获得此访问令牌。
-
@DaImTo 感谢您的回复。我已经用授权代码流更新了问题。
-
您确定您已通过具有访问权限的用户进行身份验证吗?
-
是的,我做到了。当 Oauth 同意屏幕出现时,我选中了与允许用户管理我的业务和个人资料有关的复选框。
-
或者,我还需要添加 id_token 才能使 access_token 起作用吗?因为我真的不知道为什么它不起作用
标签: node.js google-cloud-platform google-oauth google-my-business-api google-my-business