未经授权访问此资源/ API(GCP)

时间:2020-11-03 06:36:37

标签: node.js gmail-api google-admin-sdk google-workspace google-api-nodejs-client

我设置了一个具有域范围委派的服务帐户,并通过JWT方法传递了客户电子邮件,私钥,范围和用户电子邮件,以模拟G-Suite用户。然后,我从Admin API获取特定的用户信息,并使用它来创建电子邮件签名并将其推送到Gmail API。如果我传递给JWT方法的用户电子邮件是超级管理员,则效果很好,但是如果我尝试传递任何其他用户,则会收到错误响应“未授权访问此资源/ api”。关于如何使它与域中的常规用户帐户一起使用的任何想法?

以下是代码。 (genSignature.js)

const { google } = require('googleapis');
const privatekey = require('../private-key.json');

const scopes = [
    'https://www.googleapis.com/auth/gmail.settings.basic',
    'https://www.googleapis.com/auth/gmail.settings.sharing', 
    'https://www.googleapis.com/auth/admin.directory.user', 
    'https://www.googleapis.com/auth/admin.directory.user.readonly'
];

const auth = async (user) => {
    try {
        const jwtClient = new google.auth.JWT(
            privatekey.client_email,
            null, 
            privatekey.private_key,
            scopes,
            user // User who will be impersonated using the JWT client.
        );

        await jwtClient.authorize();
        return jwtClient;

    } catch (err) {

        console.log(err.message);

    };
};

function genSig(e) {

    auth(e).then((jwtClient) => {

        // Authenticate with the gmail API.
        const gmail = google.gmail({
            version: 'v1', 
            auth: jwtClient
        }); 

        // Authenticate with the admin API.
        const dir = google.admin({
            version: 'directory_v1', 
            auth: jwtClient
        });


        // Get users contact and job data from the directory. This data will be used as variables in their email signature. 
        dir.users.get({ userKey: e }, (err, response) => {
            if (err) {
                console.log(err.message);
            } else {
                let phones = response.data.phones;
                let workPhone = '';

                if (phones) {
                    for (i = 0; i < phones.length; i++) {
                        if (phones[i].type == 'work') {
                            workPhone = phones[i].value;
                        };
                    };
                };

                function getUserData() {
                    let userData = {
                        name: response.data.name.fullName, 
                        email: response.data.primaryEmail, 
                        phone: workPhone, 
                        avatar: response.data.thumbnailPhotoUrl, 
                        department: response.data.organizations[0].department, 
                        title: response.data.organizations[0].title
                    }; 
                    return userData;
                };

                let requestBody = {
                    signature: 'Test' 
                };

                // Update the users email signature for their primary email.
                gmail.users.settings.sendAs.update({ userId: e, sendAsEmail: e, requestBody }, (err, response) => {
                    if (err) {
                        console.log(err.message);
                    } else {
                        console.log(response.data);
                    };
                });
            };
        });
    });
}

module.exports = genSig;

(signatures.js)

const express = require('express');
const router = express.Router();
const genSig = require('../../functions/genSignature');

// Get webhooks from Google.
router.post('/', (req, res) => {

    let email = req.body.email;
    let emailStr = email.toString();
    console.log(emailStr);
    genSig(emailStr);


    res.status(200).json({
        "msg": "data recieved..."
    });
});

module.exports = router;

(index.js)

const express = require('express');
const app = express();

app.use(express.json());
app.use('/email-signature', require('./routes/api/signatures'));

const PORT = process.env.PORT || 6000;

app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));

以下是一些屏幕截图。

API configuration on G-Suite

Service Account Setup

Successful request vs unsuccessful request

1 个答案:

答案 0 :(得分:1)

您需要模拟管理员:

只有具有用户管理权限的帐户(例如超级管理员或用户管理管理员)才能访问Users: get。您必须考虑到,这是Admin SDK的一部分,将由管理员帐户使用。

如果您尝试通过Try this API on the reference docs进行调用,您还可以检查这是不可能的(您将得到相同的消息:Not Authorized to access this resource/api)。

使用具有域范围权限的服务帐户没关系:当服务帐户冒充其他用户时,它只能访问该用户可以访问的资源。< / p>

解决方案:

在这种情况下,如果您要从Admin SDK检索用户数据,则模拟帐户应具有用户管理特权。

但是由于调用Gmail API方法不需要这些特权,因此您可以在调用Users: get时模拟一个管理员帐户,而在调用users.settings.sendAs.update时模拟一个普通帐户。

参考:

相关问题