Creating Google Calendar API credentials from stored access/refresh tokens in .NET

I’m working on a web application that needs to add events to users’ Google Calendars. I’ve already completed the OAuth flow and have the access token and refresh token stored in my database.

The issue I’m facing is how to create the proper credentials object for the Google Calendar API using these stored tokens. Most examples I find use GoogleWebAuthorizationBroker.AuthorizeAsync() which is designed for desktop apps where the user authenticates interactively.

Here’s what I’m trying to achieve:

// I have these stored values from previous OAuth flow
string storedAccessToken = "ya29.abc123...";
string storedRefreshToken = "1//def456...";
string myClientId = "client123.googleusercontent.com";
string myClientSecret = "secret789";

// Need to create credentials without user interaction
// This doesn't work for server-side scenarios:
var authBroker = await GoogleWebAuthorizationBroker.AuthorizeAsync(
    new ClientSecrets { ClientId = myClientId, ClientSecret = myClientSecret },
    new[] { CalendarService.Scope.Calendar }, 
    "[email protected]", 
    CancellationToken.None);

var calendarService = new CalendarService(new BaseClientService.Initializer()
{
    HttpClientInitializer = authBroker
});

How can I construct the credentials object directly from my stored tokens instead of going through the authorization broker again?

You need to create a UserCredential object manually with your stored tokens. Here’s what I use in production:

var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
    ClientSecrets = new ClientSecrets
    {
        ClientId = myClientId,
        ClientSecret = myClientSecret
    },
    Scopes = new[] { CalendarService.Scope.Calendar }
});

var token = new TokenResponse
{
    AccessToken = storedAccessToken,
    RefreshToken = storedRefreshToken
};

var credential = new UserCredential(flow, "[email protected]", token);

var calendarService = new CalendarService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential
});

This skips the interactive auth flow entirely. UserCredential automatically refreshes tokens when they expire.

I’ve used this for years in server apps - users auth once through web flow, we store their tokens for background tasks. Works perfectly and handles all token management automatically.