+ Start a Discussion
Kamil MieczakowskiKamil Mieczakowski 

Accessing Google Sheets API via OAuth2 with JWT

I am currently attempting to connect to Google Sheets API via OAuth2 with JWT. I am using Service Account Key, so Salesforce can pull the data from Google Sheets without the requirement for manual authorisation every time it sends out a query.
I am at the point where I set up the Service Account Key and I am successfully sending a request to it to obtain the access_code.

Then I am attempting to query the API, using the following class:
 
/****** API CALLOUT *******/
    public static HttpResponse googleSheetsCallout (){

      string accessCode = getAccessToken();
      string endpoint = 'https://sheets.googleapis.com/v4/spreadsheets/[SPREADSHEET_ID]/values/[VALUE_RANGE]&access_token=';
      httpRequest req = new httpRequest();
      req.setEndpoint(endpoint+accessCode);
      req.setMethod('GET');
      req.setTimeout(120000);
      httpResponse res = new http().send(req);
      System.debug ('res is ' +res);
      return res;

    }
When I run the function this is what the log returns:
​|CALLOUT_RESPONSE|[71]|System.HttpResponse[Status=Forbidden, StatusCode=403] 
|USER_DEBUG|[72]|DEBUG|res is System.HttpResponse[Status=Forbidden, StatusCode=403]

 
Best Answer chosen by Kamil Mieczakowski
Kamil MieczakowskiKamil Mieczakowski
I solved it, and the issue was not the code itself.

The problem was sharing my sheet. To allow read/edit access to your sheet from the service account it must be shared with the Service Account ID email address, the same way it's shared with any other user. If this isn't done the script will produce 403 error.
 

All Answers

NagendraNagendra (Salesforce Developers) 
Hi Kamil,

May I request you please confirm the response body what you are seeing so that it results in better understanding of the issue.

Sample response body can be like
{ "access_token" : "1/8xbJqaOZXSUZbHLl5EOtu1pxz3fmmetKx9W8CV4t79M", "token_type" : "Bearer", "expires_in" : 3600 }
Please let us know if you have any queries.

Thanks,
Nagendra
 
Kamil MieczakowskiKamil Mieczakowski
I confirm that this is what I am getting as a response.
 
Response ={ "access_token" : "TOKEN WAS HERE", "expires_in" : 3600, "token_type" : "Bearer" } 200

 
Kamil MieczakowskiKamil Mieczakowski
I solved it, and the issue was not the code itself.

The problem was sharing my sheet. To allow read/edit access to your sheet from the service account it must be shared with the Service Account ID email address, the same way it's shared with any other user. If this isn't done the script will produce 403 error.
 
This was selected as the best answer