Search code examples
c#google-apigoogle-oauthgoogle-api-dotnet-client

C# set access_type = offline for AuthorizeAsync?


I am attempting to change our old rest calls for the .net client libs and I have two-ish questions/issues which are related...

The sample app on this page https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth

uses AuthorizeAsync to get the user to approve the authorization, then you save the credentials somewhere....

At a later point - you want to do some offline stuff, for that., it has the following

UserCredential and AuthorizationCodeFlow take care of automatically "refreshing" the token, which simply means getting a new access token. This is done using a long-lived refresh token, which you receive along with the access token if you use the access_type=offline parameter during the authorization code flow.

I've marked the two statement in bold that are in question.

  1. How do you set this parameter using the c# client lib? AuthorizeAsync does not take in a accessType flag.
  2. Do you even need to set this (AccessType)? I noticed that after approving the oauth screen - I received both the accessToken and the RefreshToken
  3. Once you have the refresh token - and you need to build the credentials from the saved accesstoken and refreshtoken - do you need manually refresh the access token? or will AuthorizationCodeFlow really take care of this and do I need to remember the refreshed accessToken?

Solution

  • using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
                {
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        new[] { BooksService.Scope.Books },
                        "user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary"));
                }
    

    The first thing that you should look at above is "user" this is where you denote different users. FileDataStore stores the credentials by default in %appData% folder on your machine each user will have their own credentials file. I have a full write up on filedatastore.

    You don't need to worry about setting it to offline access or requesting a new access token when yours expires the client library will handle all of that for you.