Reputation: 23
I have generated Access Token through OAuth by authenticating with admin account then trying to fetch all the labels with use of Gmail API (https://developers.google.com/apis-explorer/#p/gmail/v1/gmail.users.labels.list) for other user in same domain. But facing issue with an error : Delegation denied for [email protected].
Below is the code:
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", "[email protected]"));
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/[email protected]/labels");
var httpRequest = new HttpRequestMessage()
{
RequestUri = requestUri,
Method = HttpMethod.Get,
};
httpRequest.Headers.TryAddWithoutValidation("Authorization", string.Format("Bearer {0}", newToken));
//httpRequest.Headers.TryAddWithoutValidation("sub", "[email protected]");
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();
But getting the below error response :
{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Delegation denied for [email protected]"
}
],
"code": 403,
"message": "Delegation denied for [email protected]"
}
}
Please help me out somebody.
Upvotes: 0
Views: 1585
Reputation: 457
The impersonation with an authorization_code
still works for Google Directory API:
Upvotes: 0
Reputation: 130
It wont be possible to login with one user and get control of other users gmail account, even when you are admin.
You have to use server2server communication like it is described here: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
When everything is configured right you can call the APIs on behalf of any user like in this node.js example:
let keyFile = "../googlekey.json"
let scopes = [
"https://www.googleapis.com/auth/gmail.settings.basic"
]
let emailToLoginWith = "[email protected]"
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))
}
})
});
};
Upvotes: 1