I have been working on a project where I have had to implement OAuth across 7 different platforms, but for some reason Google's OAuth process has tripped me up.
The project has been developed in .NET MVC, and I am using RestSharp to make outgoing Http requests.
I am retrieving an OAuth request to access the GoogleAnalytics API, and on the first attempt I am obtaining a valid access token which I am able to use to successfully retrieve data from the user's GA account. However, although I specified access_type=offline in the auth request URL, when attempting to refresh the token after it expires, I am seeing the following error:
400 - Bad Request - { "error": "invalid_grant", "error_description": "Bad Request" }
My request URL looks like this:
https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https://www.googleapis.com/auth/analytics.readonly&include_granted_scopes=true&response_type=code&state=8f692f0f-b177-4b0b-aa89-a757da9432e3&redirect_uri=https://localhost:44338/GoogleAnalytics&client_id=xxxx
My token request function called when the user is redirected back along with the code:
public OAuth2Token GetToken(string code)
{
var client = new RestClient(_tokenUri);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("undefined", $"client_id={_clientId}&client_secret={_secret}&code={code}&redirect_uri={_redirectUri}&grant_type=authorization_code", ParameterType.RequestBody);
var response = client.Execute<OAuth2Token>(request);
return response.Data;
}
Access & refresh tokens are returned, and stored in the database then used later in my refresh function, where the tokenUri here is https://www.googleapis.com/oauth2/v4/token:
public OAuth2Token RefreshToken()
{
var client = new RestClient(_tokenUri);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("undefined", $"client_id={_clientId}&client_secret={_secret}&refresh_token={_refreshToken}&grant_type=refresh_token", ParameterType.RequestBody);
var response = client.Execute<OAuth2Token>(request);
if (!response.IsSuccessful)
if (response.ErrorException == null)
throw new Exception(response.Content);
else
throw response.ErrorException;
return response.Data;
}
Another point to note is that my Google App here is in testing mode, and I have added users to the list of test users. Any suggestions as to what I'm doing wrong here?
Cheers