Google Drive Authentication C# 74


Google Drive API V3
Google Drive API V3

Have you been trying to connect your website or application to Google Drive?  Would you like to see a list of files or a list of Directories stored on Google Drive?   Would you like to Upload a file to Google Drive or download a file from Google drive using C# .Net using Visual Studio.   In this tutorial series, we will be looking into the Google Drive API, using the Google .net Client library which makes accessing Google APIs much simpler.    There are a lot of things you can do with the Google Drive API, List files and folders,  Download files, Upload files, Change Files,  Copy files,  Delete Files, Trash Files,  Create directory’s, delete directory’s.  There is even a version of %appdata% on Google Drive where you can store your application specific files for each user.
[wp_ad_camp_3]
I think you get the idea there are a lot of possibilities for us with Google drive.  My plans are to show you how to most of these work.

Five part Tutorial Series

  1. Google Drive API with C# .net – Authentication
  2. Google Drive API with C# .net – Files –  Files, directories, search
  3. Google Drive API with C# .net – Upload, update, patch, delete, trash
  4. Google Drive API with C# .net – Download
  5. Google Drive API with C# .net – File Permissions
  6. Google Drive API with C# .net – Sample project

Restringing your application.

Like with most of the Google APIs you need to be authenticated in order to connect to them. To do that you must first register your application on Google Developer console.   Under APIs be sure to enable the Google Drive API and Google Drive SDK, as always don’t forget to add a product name and email address on the  consent screen form.

Project Setup

Make sure your project is at least set to .net 4.0.

Add the following NuGet Package

PM> Install-Package Google.Apis.Drive.v2

Types of Authentication

Authentication is the key to everything when you want to access Google Drive API. If you want to be able to access data, you will need to be authenticated. There are two types of Authentication OAuth2 which will allow you to access another users data, and a service account which can be set up to access your own data.   The code for them is slightly different.

OAuth2 Authentication

[wp_ad_camp_1]If you want to be able to access Google Drive though the API owned by someone else you will need to be authenticated. The code for authentication simply displays a webpage for your user asking them to give you permission to access there data. If the user gives you permission a file is then stored on the machine in the %AppData% directory containing all the information you will need in the future to access there data. For my testing purpose I use Environment. Environment.UserName as the name of the user, but if you are doing this web based you could use it as a session var of some kind.

That’s just fine but how does Google know what kind of permission you want to ask the user for? That’s where scopes come in, with scopes you define what permissions you need.

The code below will basically ask for everything, you should only include the scopes you NEED.

Assuming the user clicks Accept and gives you permission you will then have a valid user credential you can build upon. The main problem you may have with this is that it is using FileDataStore which stores the data in the users %AppData% directory while this is probably fine for an installed application this is probably not the optimal solution for a web application. If you want to store the data in the database you need to create your own implementation of IDataStore. You are in luck I have a working version of that on GitHub.

Service Account

If you are only accessing your own Google Drive Account you own this data already, so there is no reason to ask a user for permission to access it. In this instance you should use a Service account. A service account is just like any other user who has been granted access to your Google drive data with one exception, its automatic. There will be no prompt for access. You can also grant the service account direct access to a folder you already have on your google drive account it can then upload to that folder, but again it will have to give you permissions to access the files as well. Just add the service account email to the folder like you would any other user you want to give access.

A service account also has its own drive account, so you could use a service account and upload data to it. The problem with uploading data to a service account directly is that you cant see it on the website. In this instance you can create a directory on the service account then grant your personal google account full access to the directory. Then you will be able to see the files on your web site version of google drive. This can be very tricky when the service account uploads the files it owns the files it will have to give you permission to access them as well.

Service

In order to send requests to Google Drive you need a “BaseClientService” to preform those request though, notice how we are passing it our credentials

Public access

If the file is set to public then you don’t need to be authenticated. You can access it using a public API key.

Now we have a drive service that we can preform perform though.

Conclusion

You should now understand how to access the Google Drive API with an authenticated user. Join me for the next tutorial where we will look at how to list Files, directories, search using an authenticated Google drive service.

If you had any problems with this tutorial you can check the a sample project for working with Google Drive API on GitHub as part of the Google-Dotnet-Samples project. With in that project you will find a helper class for Authentication with Google Drive.


About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a Reply to Arman Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

74 thoughts on “Google Drive Authentication C#

  • Venkata Raghu Nadakuditi

    Hi,
    The information provided by you in the blog is quite useful. I am trying to write a Portable Class library to encapsulate these functionalities so that I can use them across all the platforms (Mobile and WPF) , I am finding some of the classes missing like x509certificate2 . Is there an alternative ?

  • Yassine

    Hi Linda,

    I want to google drive in my application and i want to know what type of authentication to use if i want to access my own google drive storage, is there a way to save my credentials into the application so that i can access the drive without asking me for authorization or displaying the consent screen.

    Best regards
    Yassine

    • Linda Lawton Post author

      If you authenticate your application once you can use Oauth2 and save the refresh token to be able to access it again at a later date.

      A better way of doing it though would be to use a service account, give the service account accss to a folder on your Google drive it will be able to access it. Just remember if the service account uploads a file to your google drive account to do a permissions.insert after the file is uploaded to give yourself permissions to the file. Who ever uploads the file is the owner other users need to be added after. This might help Drive file permissions

      • Yassine

        Hi Linda,

        Thanks for your quick respond, i did use the service account and i was able to access a shared folder on my drive the problem now is when i retrieve the list of all files i was getting a file called “Getting started” that was automatically get created on the service account drive, so the question is there a way to delete that file or at least getting files that exists only on my shared folder ?

      • Darryl Dalton

        Do you have an example of how to extract the access token when using a service account with the Google API Client Library for .Net?

        • Yassine

          Hi Darryl,

          According to my knowledge you cant use access token with service account, access token are used when using Oauth2 protocol instead to authenticate a service account you have to use a PKCS #12 file which store the private key and the x509 Certificate protected by a password the default is “notasecret” but you can change it by saving it to your operating system and exporting it with a different password.

          • Linda Lawton Post author

            Hi Yassine,

            I spoke with Darryl in an email. Hes not talking about using an access token to get access with a service account. He wants to find the access token that was granted by the service account so he can pass it to another call. To the Google Analytics Embedded API which doesn’t support service accounts out of the box.

            there’s Token property that gets populated once you get the token, also the credential explicitly implements ITokenAccess interface that allows you to grab the access token.

            Unfortunately I don’t have an example of this I am going to see if i can find one over the weekend.

          • Yassine

            Oh Sorry, Thank you for clearing that up Linda that was a misunderstanding on my behalf, i didnt know that a service account uses an access token, i don’t know what the types of authentication that Google Analytics API uses but if google uses the same authentication mechanisms on all google services i think storing the access token that was granted by the service account and using it with the Google Analytics API will be a great Idea.

          • Linda Lawton Post author

            Service accounts don’t use access tokens but they still return an access token, because all of the APIs need access tokens to work.

            The Google Analytics Embedded API is special its a JavaScript, which is a no go for service accounts. If we get it working this will turn into a nice blog post. so stay tuned 🙂

          • Yassine Khadouch

            Sorry for my English i mean by saying “service account uses an access token” that it retrieves an access token, anyway thanks again and i will be waiting for that blog post

  • Manish

    Hi Linda,

    All of your blogs are very helpful. Thanks!!

    Trying to implement a scenario.
    Scenario: A winform (c#) application giving option to users to synch with Google Drive. These users would not be client id or client secret details. Following are steps app is providing to users to synch google drive (Pretty much like using normal Google Drive through web) :

    (1) Login to google account

    Question : Is it possible to get any information (given, user is not aware/having client id and secret) after login which would help to synch files to Google Drive?

    (2) Present consent screen to user

    (3) Sync to Google Drive

    Please suggest if it is possible using c# and how this could be achieved without client id and secret.

    Regards,
    Manish

    • Linda Lawton Post author

      Of course its possible to do that there are several applications around that do just that.

      • 1. You need not worry about the login to Google users are logged in to there browsers that’s all that’s needed.
      • 2. If you follow this tutorial and the others in the series you will see how to present the consent screen to the user in there browser
      • 3. Sync to Google drive would be done by checking what files are currently on drive and then compairing them to what are on the machine again its doable.

      I suggest you read though this series from start to finish and you should understand how the Google Drive API works when you are done. You might also want to read my Google Developers for beginners series which walks you though all you need to know about how to access Google APIs and how to set up your account in Google Developers console.

      If you need help on the project I offer a consulting service. I try to keep my fees reasonable but only have time for so many projects. I can normally save people a lot of time in the beginning of the project just by keeping you on the correct path. Consulting service

  • Sandeep Jain

    Hi Linda,

    Thanks for sharing such a useful information. I am trying to build a ASP.NET web application. In the application where users will configure their Google Drive account through consent screen.

    The issue I am facing is that when I run the application in debugging mode through Visual Studio everything works great but when deployed the application in IIS it doesn’t prompt the consent screen.

    I have tried all three options to store token
    1. Default FileDataStore where data stores in %AppData% directory
    2. Custom implementation of IDataStore for file system and
    3. Custom implementation of IDataStore for database

    Can you please help me to figure out the issue.

    Thanks & Regards,
    Sandeep

  • GinoPino88

    Hi,
    I don’t completly understand! If I have a public file in a public folder, and I want that users using my app, can write on this file updating it.
    From my app (windows platform), Users can update this file in the pubblic folder. I must use an OAuth2 Authentication or can I set in my project the API Key? Or… my Users must the first time running my app sign in with a google account, or it’s possible using API Key to skip authentication? This because if some Users dont’ have an google account, can use app the same.
    Thanks so much

    • Linda Lawton Post author

      If you want to use Oauth2 then you can give all the users permission to access the file. Or you could just go with a service account and let the service account handle the authentication and accessing of the file.

  • GinoPino88

    Hi,
    If I want to share a pubblic file in a pubblic folder, and all my app’s users can write (update) and read it trough my app (windows platform), I must set the OAuth2 Authentication? Or it is possible to do that setting my project with (pubblic) API Key? I must understand if it possibile that all of my users can use my app also without a Google account.
    Thanks

  • Boris

    Hi Linda

    I have an ASP.NET MVC application and when I use this code first of all the google login page aprears in my default browser not the one that I ma using to run my application and then the return_uri in the request is something generic and google is reporting an error because of it. I have set the return uri in my configuration page for my project on google and I have even tried using client_secret.json where I have a return uri specified. I just cannot seem to override the setting that the GoogleWebAuthorizationBroker.AuthorizeAsync is setting in the request. Can you help please?
    Thank you

    • Linda Lawton Post author

      The client library by default opens it in the default web browser that’s not something you can change. Redirect_uri is detected by where you are sending from not from where you set it. Again this isn’t something you can override.

      You need to set the redirect_uri in the Google Developer console to that of your website or in the case of localhost something like http://localhost/authorize/ normally works. The invalid redirect uri error message normally tells you what you should set it to.

      • Boris

        Thank you Linda for a fast reply. Hope I’ll figure it out. My application port is set to 5000 but the one set to google always changes. Perhaps I need to use IIS rather then IIS Express…? Will experiment a bit with it. But it might be something to mention in your posts because I haven’t seen examples of Google drive integration with ASP.NET applications. Thnx again

  • Scott Cherkauer

    Hi Linda,
    This is a really wonderful tutorial, but I have a specific question regarding authentication for you. First, some background. Basically, what I’m attempting to do is read images from a google drive location to display on a website – a drive location that is mine. I’ve determined that I would like to use the Service Account for authentication, but my problem is the storage of the certification file. Since I really don’t have a hard path that I would reference (c:\temp\key.p12) I’m not sure how to read it in.
    Even currently, I’m attempting to locally read in a json (instead of a p12) and when I perform the execute the process just hangs.
    These may not be related issues, but they are both quite hair pulling to me. Any assistance you could provide would be greatly appreciated.

    • Linda Lawton Post author

      If you get it to read the json file instead of the p12 file i would love to chat with you. I have been trying to get that to work for weeks.

      You can put the p12 file in the same directory as the application is running from other wise you are going to have to give it a path.

  • Jarvis

    Hi Linda

    I have an error that I don’t understand. My Url in Visual Studio Project is http://localhost:56265/default.aspx. Authorized JavaScript origins in Google Console is Authorized JavaScript origins, Authorized redirect URIs is http://localhost:56265/default.aspx. But when I run your code I have an error(Error: redirect_uri_mismatch, The redirect URI in the request: http://localhost:56585/authorize/ did not match a registered redirect URI.). http://localhost:xxxxx change automaticaly. Why so?

    • Linda Lawton Post author

      Redirect URI must exactly match the url you are sending from. Testing on localhost can be a pain because visual studio likes to add the default port.

      This is what i have done in the past to deal with this issue.

      • * Fix Visual stuido so it doesnt add the default port
      • * In Google Developer console add http://localhost or http://localhost/authorize (what ever it says in the error message – the port number)
      • * Test on localhost with native credentials not browser credentials. Don’t release it with native credentials when you put it up on the server switch back to the browser credentials
      • Jarvis

        Thanks you so much for your answer. I got it. The reason is that the name in my Google Console is not match with Application Name in DriveService. That’s awesome

  • Arman

    Hi,
    I want my users can read “my own google drive” (where is public (anyone with the link can view – no sign in required)).
    I was doing it with page source and succeed but it’s not good idea! I deiced to use google drive API.
    Can i do it without using “https://console.developers.google.com” at all ?! (just using “ID” of files or something like that) If not, what is the best solution for it? (read and download files in a public folder on google drive)

    Regards
    Arman

  • puneeth

    Hi linda,
    iam fresher iam new to .net and c#.plz tell me how to interact with google drive with username and password using c# console application. And also how to create folder in google drive and upload and download files from that folder ingoogle drive using c# web services .

    • Linda Lawton Post author

      Loging in with user name and password to an api is called client login. Client login was shut down in May 2015 by Google. You cant authenticate the apis using that anymore you must use Oauth2.

  • Sesha Sreenivas Gunturu

    private DriveService GetDriveService()
    {

    //Google Drive scopes Documentation: https://developers.google.com/drive/web/scopes
    string[] scopes = new string[] { DriveService.Scope.Drive, // view and manage your files and documents
    DriveService.Scope.DriveAppdata, // view and manage its own configuration data
    DriveService.Scope.DriveAppsReadonly, // view your drive apps
    DriveService.Scope.DriveFile, // view and manage files created by this app
    DriveService.Scope.DriveMetadataReadonly, // view metadata for files
    DriveService.Scope.DriveReadonly, // view files and documents on your drive
    DriveService.Scope.DriveScripts }; // modify your app scripts

    var certificate = new X509Certificate2(keyFilePath, “notasecret”, X509KeyStorageFlags.Exportable);
    try
    {
    ServiceAccountCredential credential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(serviceAccountEmail)
    {
    Scopes = scopes
    }.FromCertificate(certificate));

    DriveService service = new DriveService(new BaseClientService.Initializer()
    {
    HttpClientInitializer = credential,
    ApplicationName = “MyTestApp”,
    });
    return service;
    }
    catch (Exception ex)
    {
    //Console.WriteLine(ex.InnerException);
    throw;

    }

    }

    I am using the above function to instantiate a DriveService using service account credentials. I am able to upload files through web application running in VS2012 IDE. However, it seems like its failing in hosted environment. I have encapsulated Google ServiceDrive functionality in an .ashx file and this gets invoked by an ajax request as given below.

    Does sending request from an external domain cause any problem?

  • david butali

    Hi Linda,
    amazing post!!
    Very clear.
    I would like to ask help.
    I’m trying to use your code behind a web service.

    Someone call my webservice and my code connect to google drive and upload a file.

    The class implementing your code works launching with a main method.

    If I try to execute the class after a calling to my web service it work only if before this call i have executed my class with a main method.

    It looks like the first time (with a main method) it were created something useful per the following web service callings.

    If I close and reopen Visual studio and call the web service first it doesn’t work.

    Hope to be clear.

    Thanks in advance

  • Alexandra

    Do you have any good resource recommendations for google drive v3 api.
    I have been looking online but ones offered by google aren’t as good.
    For example, they have “create” method but in V2 they are example codes but v3 kinda lacks.

  • James

    Hi,

    Thanks for the information shared in your blog, it’s really helpful to me.

    I’m a newbie in Google API, and I want to use my Google Drive as a central storage to keep the data of a c# application, so that I can access and update the data without hosting a server in internet.

    I just try to follow your tutorial to build my first testing application, however, being a newbie in using Google API, I was stuck in the first step to authenticate the Google API.

    I have created a new project in Google Developer console, I can find the “Google Apps APIs” in the Library page, but I cannot find the Google Drive SDK mentioned above, and also I cannot find the consent screen form for adding the product name and email address.

    I guess these may be the basic for using Google API, but I’m sorry that I have no idea where I can find them out.

    Would you please give me some details step in starting to use Google Drive API, or could you show me any reference on it.

    Thanks in advance.

  • Riyaz

    These APis are not compatible with .net framework4.0,
    these apis dependent on System.Net.Http.Primitives 1.5.0.0 assembly ,
    but .net 4.0 having System.Net.Http.Primitives 2.2.29.0

    • Linda Lawton Post author

      Google APIs are rest APIs and can be used by any language or framework that supports HTTP Post or HTTP get. You appear to be referring to the Google .Net client library which only officially supports .Net Framework 4.5+, some of the packages are still available for 4.0 but I don’t think anything is being updated.

      If you wish to use the Client library you will need to change your project to use a higher .Net Framework. You could also code the calls yourself using .net 4.0 without the library I have done something like this for my project which must support .Net 3.5.

      I just made a quick console project using .Net 4.0 and it worked for me. Which Nuget Package did you import. Nuget Packages prior to version 11 had .Net 4.0 support.

  • AntonK

    Thanks for the article!
    What is the proper approach dealing with “Access denied” when authenticating via GoogleWebAuthorizationBroker without Administrative priviledges?
    On a Windows PC ordinary users aren’t allowed to invoke HttpListener at arbitrary ports (like http://127.0.0.1:53010/authorize/).
    I’ve managed to run my code (C# and Google.Apis.Drive.v3) via service account and old-fashioned GoogleAuthorizationCodeFlow, but I need authentication the way how it is provided by GoogleWebAuthorizationBroker (it works fine only for an Administrator).
    Any hints?

    • Callam

      Can I please second this comment. I have been struggling for a fortnight to try and get the google drive api to work for a .net desktop application and I have found no way around the “access denied” exception with the httplistener, without running as administrator.

      I use other apps on my PC regularly that have some level of google drive integration, without prompting me for administrative privileges before i log in.

      Even the official .NET quickstart guide in the official documentation creates an app that requires administrative privileges to work correctly, although it doesn’t mention this anywhere in the tutorial so it makes me wonder if i am doing something wrong? especially since i cannot find any mention of a similar error through google!

  • Alessandro Spina

    Hi Linda,
    sorry for my silly questions.
    I’m in trouble with the authentication on Google Drive. When the user want to authenticate on her/his Google account through my windows form application, it prompt to her/him a webpage for the authentication on Google (naturally).
    If the user try to close the browser or don’t continue with the request from the webpage my application hangs, and she/he have to force to close the application.
    Is there a solution for this problem? Am I wrong with the approch? Have I to use the API in a different manner? I’m looking for on the web, but – as you can imagine – without results.

    This below is the code for the authentication.

    Dim fds As FileDataStore = New FileDataStore(“aaa”)
    credential = Await GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With {.ClientId = “xxx”, .ClientSecret = “yyy”}, {DriveService.Scope.Drive}, “zzz”, CancellationToken.None, fds)
    service = New DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = credential, .ApplicationName = “test”})

    Thanks in advance for your attenction (and time)
    Hoping in your help,
    best regards.
    Alessandro

    • Alessandro Spina

      Sorry Linda, I’ve solved the issue. I need some Awaitable mark on the authentication functions.
      But I’ve another boring question (I know I’m going to the hell for that!), because I don’t like that the browser prompt the request. Is there something for leave “in app” the authentication process? I’m looking for some project that helps this operation, like Oauth2 or Nemiro, but I’m a bit confused. Can you indicate me a way?

      Thanks a lot,
      best regards.
      Alessandro

  • Karan

    Hi Linda,

    Very informative tutorial/article and I am also following your answers on this topic on stackoverflow as well. I am using Xamarin Android to create an app which access users google drive files and folders. Do you have any other article/tutorial regarding the same using Xamarin Android?

    The problem is that when you create credential in google developer console and select Application Type “Android” then it does not give you client secret. So the above stated method won’t work. Another method stated here (https://stackoverflow.com/questions/28745818/google-api-to-upload-files-using-the-authentication-service-account) is for service accounts.

    Google introduced revised API V3.0 for Drive in which lots of V2 methods and field have been deprecated.

    • Linda Lawton Post author

      Your problem is that the client library doesnt support xamarin they are still trying to decide if this is something they want to support in the future. That code isnt going to work your going to have to do this on your own.

  • Thomas Heeb

    Hi Linda,
    I have a Google Drive MVC web application controlled by a scheduled task. My problem is that when I do the authentication via mvc, always a prompt Windows comes the Scheduled Task can not confirm. if i do it with the GoogleWebAuthorizationBroker.AuthorizeAsyn the IIS has problem with that (permission). Can you help me with that?

    best regards
    Thomas

    • Linda Lawton Post author

      If you are only accessing a single account you should look into using a service account. If you cant then you should just authenticate your code once the refresh token will be saved and the scheduled task should be able to use that to request a new access token for accessing the api.

  • Steve

    Hi. Great info in this series – thanks, it has helped a lot.
    In now have it set up so I can access my Drive from c# with OAuth2 (both read and write). My question – how to expand this to other accounts? Google says “access Google Drive though the API owned by someone else” – but all the examples show me how to access my own Drive. If I have a second Drive account, can I access that (read and write) from the first Drive account – without redoing all the things in Google Developers (project creation, API enabling, secret.json etc) for the second account? Thanks.

  • Wajeeh

    Hi, Linda.
    Im having trouble regarding google drive api v3, using oauth2 flow i got the access token of the specific account. But now im blank as i dont know how to make api calls for files and folders or downloading and uploading files using access token. Im currently using asp.net mvc on visual studio 2017.
    Also access token is of short lifetime, how do i generate and access refresh token in mvc ?

    • Linda Lawton Post author

      You have a drive service

      var service = new DriveService(new BaseClientService.Initializer() {HttpClientInitializer = credential,
      ApplicationName = “Drive API Sample”,});

      If you check that all the calls go though that.

      The Client library will handle refreshing the access token when it expires. Assuming you requested offline access.

  • Gladson

    Hi Linda,

    I am doing file search operation in Google drive using ASP.Net Core 2.0. In my application, first i am authenticating using Google+(with the scope of DriveService.Scope.DriveReadonly) by providing Client Id and Client Secret key. It got authenticated successfully. After that, i am performing google drive search operation. I referred this Url(https://developers.google.com/drive/api/v3/quickstart/dotnet). While performing this, Consent screen is shown to select the google account. I know that access tokens are not available in my FileDataStore. so to provide the access token, it is asking me to select the required google account.
    My problem is, I am already logged in with Google, why it is asking for consent screen. How to get the access token without prompting. I cannot use service account because i want to access the end user data.

    Please help.

  • Bram

    Hello Linda,

    i’m using your tutorial to download and delete files from my google drive in a c# desktop solution.
    The authentication works but when i try to get my files i always get 0 files.
    Any idea’s what could be wrong?

    string[] scopes = { DriveService.Scope.Drive, DriveService.Scope.DriveFile };
    var keyFilePath =
    @”D:\ResizeImages\Photos 54392-9ad0fc2df4cf.p12″; // Downloaded from https://console.developers.google.com
    var serviceAccountEmail =
    “….@photos-54392.iam.gserviceaccount.com”; // found https://console.developers.google.com

    //loading the Key file
    var certificate = new X509Certificate2(keyFilePath, “notasecret”, X509KeyStorageFlags.Exportable);
    var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
    {
    Scopes = scopes
    }.FromCertificate(certificate));

    var service = new DriveService(new BaseClientService.Initializer
    {
    HttpClientInitializer = credential,
    ApplicationName = “photos-54392”
    });

    var files = GetFiles(service, “trashed = false”);

  • Blas González

    Thank you so much for so clear explanation about the process. I implemented in a VB.NET application that upload files to GDrive the OAuth2 Authentication as you describe in your code sample and it works fine. When I execute the windows program for the first time, the consent prompt is shown, I agree with the permission and the file is upload to GDrive. After I while, lets say a couple of hours, I execute the application again an the file is uploaded without the prompt consent. So far, so good…

    However, I scheduled the application in Windows and it works for an hour, then the batch program stops to work, unsucessfullly asking for consent and the the json file where the access information is store goes missing.

    Private Sub CreateService()
    Dim Scopes() = {DriveService.Scope.Drive, DriveService.Scope.DriveFile}

    Dim oClientSecrets As New ClientSecrets
    oClientSecrets.ClientId = _ClientID
    oClientSecrets.ClientSecret = _ClientSecret

    Dim MyUserCredential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(oClientSecrets,
    Scopes,
    Environment.UserName,
    CancellationToken.None,
    New FileDataStore(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), True)
    ).Result

    service = New DriveService(New BaseClientService.Initializer() With {.HttpClientInitializer = MyUserCredential, .ApplicationName = _ApplicationName})
    service.HttpClient.Timeout = TimeSpan.FromMinutes(100)

    End Sub

  • Carlos arango

    Good afternoon Linda Lawton,
    how much would you charge me for helping me and explaining how to fix the following error:

    in local:
    google drive 3

    Error 400: redirect_uri_mismatch

    redirect_uri=http://127.0.0.1:51714/authorize/

    thank you for your time.

    Best regards.

  • Daniel Doromal

    Hi,

    is it possible to access the google drive of specific user in asp.net? for example i want to upload a file to a google drive of my customer.