尝试更改域用户的Gmail签名时,OAuth2身份验证失败

时间:2017-03-28 17:41:35

标签: google-apps-script oauth google-oauth gmail-api

我正在尝试实现一个脚本,该脚本将遍历我的域中的每个用户并设置自定义签名以符合公司要求。根据论坛帖here,如果我创建一个作为具有域范围委派的服务帐户运行的Apps脚本,我可以这样做。我已经创建了我的服务帐户,并确保将委派设置为域范围。我还将OAuth2库添加到了我的项目中。使用我自己的电子邮件地址运行此代码,我收到错误消息'访问权限未授予或已过期。 (第352行,文件"服务",项目" OAuth2")。'我尝试联系Google云支持以帮助实施OAuth2,他们将我发送到此处。我可以获得帮助,让我的域名工作并朝着正确的方向前进吗?

我目前的代码版本:



var EMAIL = Session.getActiveUser().getEmail();

var SERVICEACCT = {
  clientID: PropertiesService.getScriptProperties().getProperty('clientId'),
  fileText: PropertiesService.getScriptProperties().getProperty('clientSecretFile'), 
  projectID: PropertiesService.getScriptProperties().getProperty('clientProjectID'),
  privateKeyID: PropertiesService.getScriptProperties().getProperty('privateKeyID'),
  privateKey: PropertiesService.getScriptProperties().getProperty('clientSecretKey'),
  clientEmail: PropertiesService.getScriptProperties().getProperty('clientEmail'),
  authURL: PropertiesService.getScriptProperties().getProperty('clientAuthURI'),
  tokenURL: PropertiesService.getScriptProperties().getProperty('clientTokenURI'),
  providerURL: PropertiesService.getScriptProperties().getProperty('providerCertURL'),
  clientURL: PropertiesService.getScriptProperties().getProperty('clientCertURL'),
  map : PropertiesService.getScriptProperties().getKeys()
};


function gmailSignatureImage() {
   Logger.log(SERVICEACCT.clientEmail);
    var email = EMAIL;

  var service = getDomWideDelegationService('Gmail: ', 'https://www.googleapis.com/auth/gmail.settings.sharing', email);

    var resource = { signature: '<div><strong>My signature image</strong></div>' +
          '<div><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Google_2015_logo.svg/251px-Google_2015_logo.svg.png" '+ 
          'alt="" border="0" /></div>' };

    var requestBody                = {};
    requestBody.headers            = {'Authorization': 'Bearer ' + service.getAccessToken()};
    requestBody.method             = "PUT";
    requestBody.contentType        = "application/json";
    requestBody.payload            = JSON.stringify(resource);
    requestBody.muteHttpExceptions = false;

    var emailForUrl = encodeURIComponent(email);
    var url = 'https://www.googleapis.com/gmail/v1/users/me/settings/sendAs/' + emailForUrl;
    var setSignatureResponse = UrlFetchApp.fetch(url, requestBody);
}


// these two things are included in the .JSON file that you download when creating the service account and service account key
    var OAUTH2_SERVICE_ACCOUNT_PRIVATE_KEY  = SERVICEACCT.privateKey;
    var OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL = SERVICEACCT.clientEmail;


function getDomWideDelegationService(serviceName, scope, email) {

    Logger.log('starting getDomainWideDelegationService for email: ' + email);

    return OAuth2.createService(serviceName + email)
    // Set the endpoint URL.
    //.setTokenUrl('https://accounts.google.com/o/oauth2/token')
      .setTokenUrl(SERVICEACCT.tokenURL)
    // Set the private key and issuer.
    .setPrivateKey(OAUTH2_SERVICE_ACCOUNT_PRIVATE_KEY)
    .setIssuer(OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL)

    // Set the name of the user to impersonate. This will only work for
    // Google Apps for Work/EDU accounts whose admin has setup domain-wide
    // delegation:
    // https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
    .setSubject(email)

    // Set the property store where authorized tokens should be persisted.
    .setPropertyStore(PropertiesService.getScriptProperties())

    // Set the scope. This must match one of the scopes configured during the
    // setup of domain-wide delegation.
    .setScope(scope);

 }
&#13;
&#13;
&#13;

此外,以下是将我的SERVICEACCT对象打印到控制台(为保密而清理)的结果:

&#13;
&#13;
[17-03-28 13:32:13:515 EDT] Service Account
[17-03-28 13:32:13:515 EDT] Client ID: 1234567891011121314
[17-03-28 13:32:13:516 EDT] Project ID: project-id-12345678910112
[17-03-28 13:32:13:516 EDT] Private Key ID: 871**CONFIDENTIAL DATA**ad60
[17-03-28 13:32:13:517 EDT] Client Email: gsig-828@project-id-[Project ID].iam.gserviceaccount.com
[17-03-28 13:32:13:518 EDT] Auth URI: : https://accounts.google.com/o/oauth2/auth
[17-03-28 13:32:13:518 EDT] Token URI: https://accounts.google.com/o/oauth2/token
[17-03-28 13:32:13:519 EDT] Provider Certification URL: https://www.googleapis.com/oauth2/v1/certs
[17-03-28 13:32:13:519 EDT] Client Certification URL: https://www.googleapis.com/robot/v1/metadata/[projectID].iam.gserviceaccount.com
[17-03-28 13:32:13:519 EDT] Private Key: 
--------------------------------------------------------------------------------------------------------------------------------------
-----BEGIN PRIVATE KEY-----***CONFIDENTIAL KEY***\n-----END PRIVATE KEY-----\n
--------------------------------------------------------------------------------------------------------------------------------------
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

确保您的服务已获得授权。您可以参考此related thread,建议重置服务/清除您的使用属性。 Google仅在您首次授权服务时返回刷新令牌,因此如果它丢失,则在将来的授权中无法恢复。此外,请尝试撤消此脚本/项目的访问权限重新授权。

  

我已撤销所有访问权限,然后我再次生成许可证,我会等待一段时间,看看它是否会再次过期。

     

一旦您授予权限,就不会删除对该应用程序的访问权限。我想通过此权限,Google会刷新令牌。

这是另一个可能有用的SO帖子:Automated OAuth2 token not working - Google Apps Script