hasnayn
hasnayn

Reputation: 356

Get UserCredential of Google Drive API using Refresh token, ClientId and ClientSecret in ASP.net/C#

I was able to get a RefreshToken by following the instruction given in this link : How do I authorise a background web app without user intervention? (canonical ?).

Now I need user credential for getting driveservice object. I have searched a lot but cant find a exact solution.

I can get access token using refresh token, ClientId and ClientSecret following this link :Using OAuth 2.0 for Web Server Applications - offline.

But after that how can I get user credential using that AccessToken? Or any direct way for getting credential using refresh token. Any example or suggestion.

Thanks!

Upvotes: 0

Views: 2886

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 116958

You might want to try using the Client Lib for this instead of that. All you need to do is run the following code once. The refresh token will be created by FileDataStore and stored in your %appData% directory. The next time it runs it wont prompt you for authentication because it will have it already. You could also create your own implementation of iDataStore to store the refresh token where ever you like. I like current directory LocalFileDatastore.cs.

//Scopes for use with the Google Drive API
string[] scopes = new string[] { DriveService.Scope.Drive,
                                 DriveService.Scope.DriveFile};
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = 
            GoogleWebAuthorizationBroker
                          .AuthorizeAsync(new ClientSecrets { ClientId = CLIENT_ID
                                                            , ClientSecret = CLIENT_SECRET }
                                          ,scopes
                                          ,"SingleUser"
                                          ,CancellationToken.None
                                          ,new FileDataStore("Daimto.GoogleDrive.Auth.Store")
                                          ).Result;

Code ripped from Google Drive API C# tutorial.

Upvotes: 1

Related Questions