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

Google Drive Api for installed application c#


Can someone please show a working example code of how to use google drive api for installed application? ( access_type=offline) I found a few explanations, but can't get to a working flow.

Thanks


Solution

  • Ok, What I used at least was not 'installed application', but 'web application'. These are the steps to do:

    1. Go to Google Developers Console and create a project.

    2. Go to APIs & Auth

    3. On APIs enable Drive API & Drive SDK.

    4.On Credentials Create new Client ID for Web Application (Create your Consent screen, evev though we won't use it.)

    In the Create Client ID window, add the url "https://developers.google.com/oauthplayground" to the AUTHORIZED REDIRECT URIS.

    5.Go to the url you added on number 4

    6.Click the gear on the right and configure:

    OAuth flow: Server-side
    
    Access type: Offline
    
    Use your own OAuth credentials: Tick
    
    Then copy your Client ID & Secret from the console.
    

    7.On the left, choose Drive API -> https://www.googleapis.com/auth/drive, click Authorize APIs

    8.A new window will open, asking you to accept Google OAuth... click Accept.

    9.Click Exchange authorizaion code for tokens.

    10.Copy & Save the Acess & Refresh tokens.

    The code:

    private static DriveService CreateServie(string applicationName)
    {
      var tokenResponse = new TokenResponse
      {
        AccessToken = yourAccessToken,
        RefreshToken = yourRefreshToken,
      };
    
      var apiCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
      {
        ClientSecrets = new ClientSecrets
        {
          ClientId = yourClientID,
          ClientSecret = yourClientSecret
        },
        Scopes = new[] { DriveService.Scope.Drive },
        DataStore = new FileDataStore(applicationName)
      });
    
      var credential = new UserCredential(apiCodeFlow, yourEMail, tokenResponse);
    
      var service = new DriveService(new BaseClientService.Initializer
      {
        HttpClientInitializer = credential,
        ApplicationName = applicationName
      });
    
      return service;
    }