Reputation: 21
I'm using .Net (and I have installed the NuGet package) to access Google Sheets using a service account. I have a Google API account, created the service account and even have a test sheet to work with. I have included the JSON file which describes the credentials that I downloaded from the service account I created. Everything seems to work except when I use the Execute method call I get the following error:
The caller does not have permission [403] Message[The caller does not have permission] Location[ - ] Reason[forbidden] Domain[global]
at Google.Apis.Requests.ClientServiceRequest`1.<ParseResponse>d__34.MoveNext()
I have turned on global access for the service account as well, but it still doesn't work. I tried to share the service account with the sheet, but there doesn't seem to be any way to do that.
My code looks like this:
string[] Scopes = { SheetsService.Scope.SpreadsheetsReadonly };
string ApplicationName = "My Unit Test";
GoogleCredential sac;
using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
sac = GoogleCredential.FromStream(stream).CreateScoped(Scopes);
}
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = sac,
ApplicationName = ApplicationName,
});
String spreadsheetId = "1_aeTu4YxDKrqDBvCNR1awyo_7WDha0JBVo1jLxsz3pA";
String range = "Export!A2:E";
SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(spreadsheetId, range);
ValueRange response = request.Execute(); // Exception thrown here
I need the Execute to successfully log in and access the Google Sheet I setup. Has anyone seen this or know a way around it?
Upvotes: 1
Views: 478
Reputation: 21
Nobody responded and I found the fix on my own. The gmail account I was using for testing was a specialized work domain. It didn't allow me to share the sheet correctly. So, I setup a new google account, added all the apis and service accounts in. Added the proper role to the service account. Generated the new json private key. Created a sheet with that new account and shared it with the new service account … it works. IMPORTANT, you must share the sheet with the service account or it will not work.
Upvotes: 1