I'm working on reading/sending gmail emails in c# with API requests. I have got an access token but it expires after one hour and further actions are not executed anymore. Could, please, someone help me with the procedure on how to get a new valid access token?
Thank you in advance!
EDIT:
This is a code from where I get authorization:
public static GmailService AuthenticateOauthGmail(string clientSecretJson, string userName)
{
try
{
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException("userName");
if (string.IsNullOrEmpty(clientSecretJson))
throw new ArgumentNullException("clientSecretJson");
if (!File.Exists(clientSecretJson))
throw new Exception("clientSecretJson file does not exist.");
// These are the scopes of permissions you need. It is best to request only what you need and not all of them
string[] scopes = new string[] { "https://mail.google.com"};
//UserCredential credential;
using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
// Requesting Authentication or loading previously stored authentication for userName
Variables.Credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
scopes,
userName,
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
var newCredentials = GoogleWebAuthorizationBroker.ReauthorizeAsync(Variables.Credential, CancellationToken.None);
}
// Create Drive API service.
return new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = Variables.Credential,
ApplicationName = "Gmail Oauth2 Authentication Sample"
});
}
catch (Exception ex)
{
Console.WriteLine("Create Oauth2 account GmailService failed" + ex.Message);
throw new Exception("CreateServiceAccountGmailFailed", ex);
}
}
This is how my Credentials.Token looks like credentials.Token
Since access token is expired, when trying to read mails, I get an error:
{
"error": {
"code": 401,
"message": "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.",
"errors": [
{
"message": "Invalid Credentials",
"domain": "global",
"reason": "authError",
"location": "Authorization",
"locationType": "header"
}
],
"status": "UNAUTHENTICATED"
}
}
I have nuget package Google.Apis.Auth. Should I use another one?