首页 > 解决方案 > 带有 DwD 的 GSuite 服务帐户未经授权访问用户的 Gmail 帐户

问题描述

我有一个启用了域范围委派的 G Suite 服务帐户,并且我想模拟域上的用户。然而,我的每一次尝试都遇到了一个错误,说我未经授权。有没有人经历过这种情况并且可能知道发生了什么?

我已经按照这些说明进行操作,这些也是。我创建了一个新的服务帐户,(如上所述)启用了 DwD,并在管理控制台中添加了必要的范围:https ://mail.google.com https://www.googleapis.com/auth/gmail.settings.sharing https://www.googleapis.com/auth/gmail.settings.basic https://www.googleapis.com/auth/admin.reports.audit.readonly

(此外,该域已验证。)

从那里,我尝试使用以下代码在 NodeJS 客户端中授权此帐户:

const {google} = require('googleapis');
const fs = require('fs');
const auth = JSON.parse(fs.readFileSync('xxx.json'));

const jwt = new google.auth.JWT(
    auth.client_email, 
    null, 
    auth.private_key, 
    [
        'https://mail.google.com/',
        'https://www.googleapis.com/auth/gmail.settings.sharing',
        'https://www.googleapis.com/auth/gmail.settings.basic',
        'https://www.googleapis.com/auth/admin.reports.audit.readonly'
    ],
    'user@domain.com'
);

jwt.authorize((err, res) => {
    if (err) console.log(err);
    else console.log(res);
});

如果我删除user@domain.com并尝试在不冒充电子邮件的情况下进行授权,它可以工作;我收到一个访问令牌。但是,出于我的目的,我需要能够模拟,如果我尝试这样做,我会收到带有以下消息的 401:

GaxiosError: unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.

据我所知,服务帐户应该被授权模拟域上的用户。有谁知道为什么会发生这种情况?

标签: node.jsrestgoogle-cloud-platformgoogle-workspacegoogle-api-nodejs-client

解决方案


最后,是我傻了。在管理控制台中,我一直用空格分隔范围,而实际上它们应该用逗号分隔:' https://mail.google.com , https://...'


推荐阅读