模拟访问Gmail API

时间:2015-10-27 11:02:09

标签: oauth-2.0 google-api impersonation gmail-api

我已经生成了Access Token OAuth通过使用管理员帐户进行身份验证然后尝试获取所有内容 使用Gmail API的标签 (https://developers.google.com/apis-explorer/#p/gmail/v1/gmail.users.labels.list) 对于同一域中的其他用户。但面临错误的问题:委托 否认为xyz@domain.com。

以下是代码:

string uri = "https://www.googleapis.com/oauth2/v3/token";
            string results = string.Empty;
            string responseString = null;
            using (var clientForToken = new HttpClient())
            {
                var values = new List<KeyValuePair<string, string>>();

                values.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
                values.Add(new KeyValuePair<string, string>("code", code));
                //values.Add(new KeyValuePair<string, string>("sub", "pluto@metamini.com"));
                values.Add(new KeyValuePair<string, string>("client_id", Convert.ToString(ConfigurationManager.AppSettings["ida:ClientId"])));
                values.Add(new KeyValuePair<string, string>("client_secret", Convert.ToString(ConfigurationManager.AppSettings["ida:ClientSecret"])));
                values.Add(new KeyValuePair<string, string>("redirect_uri", "http://localhost:6402/Home/ClaimExchangeServerAccessToken"));
                var content = new FormUrlEncodedContent(values);

                var response = clientForToken.PostAsync(uri, content).Result;
                responseString = response.Content.ReadAsStringAsync().Result;
            }

            var newToken = AccessTokenFromJson(responseString);

            //Uri requestUri = new Uri("https://www.googleapis.com/admin/directory/v1/users?domain=mydomain.com");
            Uri requestUri = new Uri("https://www.googleapis.com/gmail/v1/users/xyz@mydomain.com/labels");

            var httpRequest = new HttpRequestMessage()
            {
                RequestUri = requestUri,
                Method = HttpMethod.Get,
            };
            httpRequest.Headers.TryAddWithoutValidation("Authorization", string.Format("Bearer {0}", newToken));
            //httpRequest.Headers.TryAddWithoutValidation("sub", "pluto@metamini.com");

            var clientHandler = new HttpClientHandler()
            {
                AutomaticDecompression = System.Net.DecompressionMethods.None
            };
            var client = new HttpClient(clientHandler);
            HttpResponseMessage responseMessage = null;

            responseMessage = client.SendAsync(httpRequest).Result;
            Stream receiveStream = responseMessage.Content.ReadAsStreamAsync().Result;
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
            string data = readStream.ReadToEnd();

但得到以下错误回复:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "forbidden",
    "message": "Delegation denied for mickey@metamini.com"
   }
  ],
  "code": 403,
  "message": "Delegation denied for mickey@metamini.com"
 }
}

请帮帮我。

2 个答案:

答案 0 :(得分:1)

即使您是管理员,也无法使用一个用户登录并控制其他用户的Gmail帐户。

您必须使用server2server通信,如下所述: https://developers.google.com/identity/protocols/OAuth2ServiceAccount

正确配置所有内容后,您可以代表此node.js示例中的任何用户调用API:

let keyFile = "../googlekey.json"
    let scopes = [
        "https://www.googleapis.com/auth/gmail.settings.basic"
    ]
    let emailToLoginWith = "theUserYouWantToReadTheMails@for.com"
    let fs = require("fs")
    let google = require('googleapis');
    // Load client secrets from a local file.
    fs.readFile(keyFile, function processClientSecrets(err, content) {
        if (err) {
            console.log('Error loading client secret file: ' + err);
            return;
        }

        authorize(JSON.parse(content));
    });

    var authorize = function(credentials) {
        var googleAuth = require('google-auth-library');
        var auth = new googleAuth();
        var oAuth2Client = new auth.OAuth2();

        var jwt = new google.auth.JWT(
            credentials.client_email,
            null,
            credentials.private_key,
            scopes,
            emailToLoginWith        //this is the user on which behalf the service accounts logs in
        );
        jwt.authorize(function(err, result) {

                    if(err){
                        return console.error(err);
                    }
                    oAuth2Client.setCredentials({
                        access_token: result.access_token
                    });

                    var service = google.gmail('v1');
                    /!* call to google server *!/
                    service.users.settings.sendAs.list({
                        auth: oAuth2Client,
                        userId: emailToLoginWith,
                    }, function(err, response) {
                        if(err){
                            console.error(err);
                        }else{
                            console.error(JSON.stringify(response))
                        }

                    })




                });
    };

答案 1 :(得分:0)