Skip to content

Instantly share code, notes, and snippets.

@Swimburger
Last active June 12, 2020 13:45
Show Gist options
  • Save Swimburger/d2d39276bdeaeaa4d6b6148a0ab02a48 to your computer and use it in GitHub Desktop.
Save Swimburger/d2d39276bdeaeaa4d6b6148a0ab02a48 to your computer and use it in GitHub Desktop.
Use access_type offline with the Google C# SDK to prevent the need to reauthenticate every hour
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Requests;
using Google.Apis.Util.Store;
namespace YourNameSpace.Google
{
//decompiled with dotpeek and adjusted
public class OfflineGoogleWebAuthorizationBroker : GoogleWebAuthorizationBroker
{
public new static async Task<UserCredential> AuthorizeAsync(ClientSecrets clientSecrets, IEnumerable<string> scopes, string user, CancellationToken taskCancellationToken, IDataStore dataStore = null, ICodeReceiver codeReceiver = null)
{
var initializer = new GoogleAuthorizationCodeFlow.Initializer {ClientSecrets = clientSecrets};
return await AuthorizeAsync(initializer, scopes, user, taskCancellationToken, dataStore, codeReceiver).ConfigureAwait(false);
}
public new static async Task<UserCredential> AuthorizeAsync(GoogleAuthorizationCodeFlow.Initializer initializer, IEnumerable<string> scopes, string user, CancellationToken taskCancellationToken, IDataStore dataStore = null, ICodeReceiver codeReceiver = null)
{
initializer.Scopes = scopes;
initializer.DataStore = dataStore ?? new FileDataStore(Folder, false);
GoogleAuthorizationCodeFlow authorizationCodeFlow = new ForceOfflineGoogleAuthorizationCodeFlow(initializer); //own offline implementation
codeReceiver = codeReceiver ?? new LocalServerCodeReceiver();
return await new AuthorizationCodeInstalledApp(authorizationCodeFlow, codeReceiver).AuthorizeAsync(user, taskCancellationToken).ConfigureAwait(false);
}
}
public class ForceOfflineGoogleAuthorizationCodeFlow : GoogleAuthorizationCodeFlow
{
public ForceOfflineGoogleAuthorizationCodeFlow(Initializer initializer) : base(initializer) { }
public override AuthorizationCodeRequestUrl CreateAuthorizationCodeRequest(string redirectUri)
{
var ss = new GoogleAuthorizationCodeRequestUrl(new Uri(AuthorizationServerUrl))
{
AccessType = "offline",
ClientId = ClientSecrets.ClientId,
Scope = string.Join(" ", Scopes),
RedirectUri = redirectUri
};
//ss.ApprovalPrompt = "force";
return ss;
}
};
}
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using YourNameSpace.Google;
namespace YourNameSpace
{
public class GoogleApiConsumer
{
private static readonly string[] Scopes = { GmailService.Scope.GmailReadonly };
private const string ApplicationName = "ApplicationName";
private readonly string _userId;
private readonly string _secretsPath;
private readonly string _tokenFolder;
public GoogleApiConsumer(string userId, string secretsPath, string tokenFolder)
{
_userId = userId;
_secretsPath = secretsPath;
_tokenFolder = tokenFolder;
}
public void GetEmails()
{
UserCredential credential;
using (var stream =
new FileStream(_secretsPath, FileMode.Open, FileAccess.Read))
{
var secrets = GoogleClientSecrets.Load(stream).Secrets;
var store = new FileDataStore(_tokenFolder, true);
//use your own offline implementation instead of Googles default
credential = OfflineGoogleWebAuthorizationBroker.AuthorizeAsync(
secrets,
Scopes,
_userId,
CancellationToken.None,
store).Result;
}
var googleClient = new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName
};
// Create Gmail API service.
var service = new GmailService(googleClient);
var request = service.Users.Messages.List(_userId);
request.IncludeSpamTrash = true;
var response = request.Execute();
var message = response.Messages.First();
// use emails
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment