Leave a comment

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

51 thoughts on “Google Drive Authentication C#

  • Venkata Raghu Nadakuditi

    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

    • Linda Lawton
      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
            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
            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.


    • Linda Lawton
      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,

  • GinoPino88

    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
      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

    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.

  • 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
      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
      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
      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

    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)


  • 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
      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);
    ServiceAccountCredential credential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(serviceAccountEmail)
    Scopes = scopes

    DriveService service = new DriveService(new BaseClientService.Initializer()
    HttpClientInitializer = credential,
    ApplicationName = “MyTestApp”,
    return service;
    catch (Exception ex)



    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


    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 assembly ,
    but .net 4.0 having System.Net.Http.Primitives

    • Linda Lawton
      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.