'Google.Apis.Requests.RequestError - Expected OAuth 2 access token
We are getting the following error in c# when executing Google.Apis.Gmail.v1.StopRequest.Stop. **NOTE: this is code that has ran for 2+ years and suddenly stopped working around 3/23/2022. I am also including a screenshot of the Nuget versions we are using. Any advice or direction on this is appreciated!
THE CODE:
var credential = GetCredential(serviceAccountEmail, certFileName, email);
if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
{
var accessToken = credential.Token.AccessToken;
GmailService gmailService = new GmailService(
new BaseClientService.Initializer()
{
HttpClientInitializer = credential
}
);
var stopRequest = gmailService.Users.Stop(email);
stopRequestStatus = stopRequest.Execute();
}
This is the code for GetCredentials:
ServiceAccountCredential GetCredential(string serviceAccountEmail, string certFileName, string userId)
{
try
{
log.Debug("svcAacntEmail=" + serviceAccountEmail);
log.Debug("Userid=" + userId);
log.Debug("certfilename" + certFileName);
X509Certificate2 certificate = new X509Certificate2(certFileName, SvcResource.CERT_PASSWORD, X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
User = userId,
Scopes = new[]
{
"https://mail.google.com/",
}
}.FromCertificate(certificate));
return credential;
}
catch (Exception ex)
{
log.Error("Error in setting creds for gmail svc auth", ex);
return null;
}
}
THE ERROR:
The service gmail has thrown an exception:
Google.GoogleApiException: Google.Apis.Requests.RequestError Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project. [401] Errors [ Message[Invalid Credentials] Location[Authorization - header] Reason[authError] Domain[global] ]
at Google.Apis.Requests.ClientServiceRequest
1.<ParseResponse>d__31.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Google.Apis.Requests.ClientServiceRequest1.Execute()
Solution 1:[1]
I ran into this issue as well in our C# application.
I've now figured out the problem - and it's nothing to do with what the 401 error message suggests.
Our application is written in C# and is attempting to use TLS 1.0 by default. When we force it to use TLS 1.2, it works absolutely fine.
So the real problem is the cryptography ciphers used in the HTTPS connection and is nothing to do with the Authorization header, etc.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chris Wood |

