I’m struggling with authentication when trying to use a service account to connect to the Google Documents API. The error I keep getting is a 401 Unauthorized response saying the request is missing authentication credentials.
I have configured the service account in Google Workspace admin console and set up the proper scopes. The credentials file is in place but I think I’m missing something in how I pass the authentication token to the actual API request. Any help would be great!
You’re setting up the Google Client correctly but then completely ignoring it when you make the API call. Using Guzzle directly means it doesn’t know about your auth setup at all. I hit this same issue six months ago and wasted hours debugging it. Two ways to fix this: either use the Google Client’s HTTP client, or grab the access token manually and stick it in the Authorization header. If you want to keep using Guzzle, call $googleClient->authorize() to get an authenticated client, or pull the token yourself and add it to your headers. The Google Client handles all the OAuth stuff, but you’ve got to actually use it for requests.
It seems you’re missing the crucial step of adding the authentication token to your Guzzle request. After configuring your Google Client, you should fetch an access token using $googleClient->fetchAccessTokenWithAssertion();. Then, retrieve the token with $accessToken = $googleClient->getAccessToken();. In your Guzzle request, remember to set the ‘Authorization’ header like this: 'headers' => ['Authorization' => 'Bearer ' . $accessToken['access_token']]. Alternatively, consider using the Google Client’s service methods which manage authentication for you.
youre not using the google client for the api call – you created it but then made a separate guzzle request without auth headers. try $service = new Google_Service_Docs($googleClient); then use that service object instead of raw guzzle calls.