Google Sheets API. The request is missing a valid API key. [403] - c#

I'm using .net package Google.Apis.Sheets.v4 Client Library. Everything was fine, but last time (about a week ago) there is an error: The request is missing a valid API key. [403] when I'm trying to batchGet with 150+ ranges in a query. If I split my query to 25 ranges in a single query, it could be ok, also it could return the same error at one of them. Sometimes it works without any splitting, but usually I get an error.
I'm absolutely sure that my API key is valid and I've tried another keys, another spreadsheets, but nothing has changed.

Some of the answers in this SO post have point to handle this 403 error.
First thing, make sure that you have permission to call the specific spreadsheet and enable the Sheets API in your developer console. Another thing, try to change the privacy settings of this spreadsheet to public and checked if you can access it now. You will usually get 403 error when you have missed or incorrect configuration in Authorizing Requests. Make sure to use proper scope if you are authorizing requests with OAuth 2.0

Check this conversation.
Instead of google.sheets({version: 'v4', oAuth2Client})
use google.sheets({version: 'v4', auth: oAuth2Client})

Related

Google Drive v3 API file - 403 when specifying alt=media

This C# code, with a proper access token (for scope drive.readonly) in the Authorization header, will work fine and return the file metadata in json format
_httpClient.GetAsync($"https://content.googleapis.com/drive/v3/files/{someDriveFileId}")
However this code (still with the same access token) will return a 403 :
_httpClient.GetAsync($"https://content.googleapis.com/drive/v3/files/{someDriveFileId}?alt=media")
And the following response html (exactly as returned) :
<html><title>Error 403 (Forbidden)!!1</title><a
href=//www.google.com/><span id=logo
aria-label=Google></span></a><p><b>403 Forbidden</b><p>Your client
does not have permission.\n
I've been using this code in production for years and it worked fine, so i suppose it's related to the recent changes at Google regarding the OAuth screens ?
I'm not sure what i should change here, or what i'm doing (now) wrong. Also the message seems a little sketchy for something made at Google, makes me think there is maybe an issue on their side ?
UPDATE:
Thanks to #Iamblichus for fixing the layout of my original answer. I'm newer to stackoverflow posting.
Even though the change in the original answer appears to be at the root of the problem, I found it difficult to use the troubleshooting steps to come to a working solution. I also was already passing the Authorization Bearer token solution, and that was not fixing my problem. After some trial and error the change I had to make was:
Broken GET URL:
https://content.googleapis.com/drive/v2/files/MY_FILE_ID?key=MY_KEY&alt=media&source=downloadUrl
Working GET URL:
https://www.googleapis.com/drive/v2/files/MY_FILE_ID?alt=media&source=downloadUrl
NOTE:
I am using v2 of the API, so you would need to update to url to v3 if using that.
In the file object I get from the google filepicker v2 API, I don't get back a single URL that supports the change made in authentication. I had to concat the file.selfLink string to make the new URL work
var url = file.selfLink + "?alt=media&source=downloadUrl";
ORIGINAL ANSWER:
Is it possible that https://cloud.google.com/blog/products/application-development/upcoming-changes-to-the-google-drive-api-and-google-picker-api is your problem?:
download calls to files.get, revisions.get and files.export endpoints which authenticate using the access token in the query parameter will no longer be supported.
Only requests that download media content (alt=media) are affected by this change.
The access token should be provided in the HTTP header, like Authorization: Bearer oauth2-token or, if that's not possible, follow the workarounds provided in the referenced documentation:
For file downloads, redirect to the webContentLink which will instruct the browser to download the content. If the application wants to display the file to the user, they can simply redirect to the alternateLink in v2 or webViewLink in v3.
For file exports, redirect to the export link in exportLinks with the desired mime type which will instruct the browser to download the content.
Reference:
Changes in authorization to Google Drive API
Authorization via HTTP header
v2 files get documentation
v3 files get documentation

ASP NET Web API google authentication issue HTTP 404

I am trying to setup a social login for my site.
Here is what I did:
I created credentials on google and have both ClientID and Secret
In default MVC app, in App_Start Startup.Auth.cs I uncommented
app.UseGoogleAuthentication()* method, so it looks like this:
Build solution!
Made sure authorized JavaScript origins and Redirect url are correct. And other things that are needed on console.cloud.google.com are done. Including activation of Google+ API
Eventually Google authentication button should appear in _ExternalLoginsListPartial partial view. But as I can see I have 0 login providers still. And not sure why, and what can I do about it?
var loginProviders = Context.GetOwinContext().Authentication.GetExternalAuthenticationTypes();
//loginProviders.Count() here returns 0
Tried researching, but most are saying that you forgot to build, or restart the server. Tried that but nothing changed.
As last resort, I tried following a tutorial https://youtu.be/WsRyvWvo4EI?t=9m47s
I did everything as shown there, I should be able to reach api/Account/ExternalLogins?returnUrl=%2F&generateState=true url, and receive callback URL from Google.
But I got stuck with same HTTP404 error at 9:50
To answer my question, everything turns out to be fine.
All I had to do was just to give it some time.
After couple of hours, Google provider appeared on the page.
For future readers - if met with 404 in this case, another possibility is an active filtering rule against query strings in IIS. One of the commonly copy-pasted rules aiming to block SQL injection requests scans the query string for open (to catch OPEN cursor). Your OAuth request probably contains this word in the scopes section (data you want to pull from the Google profile)
IIS -> Request Filtering
Switch to the tab "Rules"
Inspect and remove any suspicious active filters there

C# GoogleSheets - Getting a 403 (FORBIDDEN)

I have tried to test code to read the content of a google sheet from C#
For now, I have copied the code from: http://mscodingblog.blogspot.com.mt/2016/11/how-to-read-google-spreadsheet-using.html
Everything is verbatim, but my keyfile.
When running, I get a 403.
The account is admin, the spreadsheet is even posted publicly on the web (id: 1wAkLe8GRpsL_FrBjEi4aMTeR1wGWWllwqBdY2Z8zVms) and I request read-only access, and yet, I can't access it.
If I run it with the wrong spreadsheet Id, I get a 404, so at least I know it finds the spreadsheet in the first call.
I am using a service account.
I found this: Getting a 403 - Forbidden for Google Service Account but it doesn't really help me as there doesn't seem to be a valid solution there.
What could I be missing?
Try deleting your .credential directory. On Windows, you would open a file explorer and navigate to .credentials.

Accessing OneDrive from Desktop App

I'm trying to get to grips with OneDrive, using this tutorial:
https://msdn.microsoft.com/en-us/library/hh826529.aspx
When I run in code, it gets as far as the makeAccessTokenRequest function, sending the following requestURL:
"https: //login.live.com/oauth20_token.srf?client_id=[myclientID] &client_secret=[myclientsecret]&redirect_uri=https:// login.live.com/oauth20_desktop.srf&grant_type=authorization_code&code=[authcode]"
(please ignore the spaces after "https:", I had to add them here to allow the question)
[myclientid], [myclientsecret], and [authcode] all appear to be populated correctly. It seems to get a response, as it runs the function "accessToken_DownloadStringCompleted", but throws a "TargetInvocationException" error, The inner message of the error is ""The remote server returned an error: (400) Bad Request.".
Could anyone throw any light on this? I'm completely new to this, so apologies if my question makes no sense, or is irritatingly vague..
Requests to the oauth20_token.srf end point need to be a POST with the parameters in the body of the post, instead of the query string. Since you didn't mention what code you're using to build the HTTP request it's hard to provide an example, but take a look at RedeemAuthorizationCodeAsync in my sample OAuth 2 project for an idea.
The outgoing request should look like this:
POST https://login.live.com/oauth20_token.srf
Content-Type: application/x-www-form-urlencoded
client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}&code={code}&grant_type=authorization_code
You may also find this tutorial easier to follow than the one you linked with: https://dev.onedrive.com/auth/msa_oauth.htm.
If you are doing something with OneDrive (you tagged the post OneDrive) then you may want to consider using the OneDrive SDK instead. It includes authentication for several types of .NET projects so you don't need to figure out how to do auth yourself.

OneDrive get access token request case-sensitivity

I have a WinForms C# app using the OneDrive API. All was working up until last week when new token requests after authorizing the user started failing telling me that the 'code' parameter was invalid.
After reviewing my code, I noticed that routine that was extracting the authorization code from the authorize call back was using .ToLowerInvariant which resulted in the authorization code starting with a lower-case 'm'. When I removed the .ToLowerInvariant, the code started with an upper-case 'M' and the token request worked correctly.
Obviously I'm happy that my code is now working, but I'd like to try and understand why it suddenly started having problems.
Many thanks
James

Categories