Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Drive API v3 use JSON instead of P12 (Service Account) - Unexpected character

Error: Unexpected character encountered while parsing value: e. Path '', line 0, position 0.

I am using the Google .Net Client library to access the Google drive API v3 specifically the Google.Apis.Drive.v3 package. I am authorizing using "Service Account" with C#.

Authorization with the p12 key is no problem. However, JSON is recommended and p12 format is maintained for backward compatibility.

I downloaded the JSON file from the Google Developers Console and tried to make the authorization with the following code:

    public static Google.Apis.Drive.v3.DriveService AuthenticateServiceAccountJSON(string keyFilePath) {

        // check the file exists
        if (!File.Exists(keyFilePath)) {
            Console.WriteLine("An Error occurred - Key file does not exist");
            return null;
        }

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

        try {
            using (var stream = new FileStream(keyFilePath, FileMode.Open, FileAccess.Read)) {
                var credential = GoogleCredential.FromStream(stream);
                if (credential.IsCreateScopedRequired) {
                    credential.CreateScoped(scopes);
                }
                // Create the service.
                Google.Apis.Drive.v3.DriveService service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer() {
                    HttpClientInitializer = credential,
                    ApplicationName = "MyDrive",
                });
                return service;
            }
        } catch (Exception ex) {
            Console.WriteLine(ex.InnerException);
            return null;

        }
    }

I have looked at the JSON file in notepad and it seems encrypted.

"ewogICJ0eXBlIjogInNlcnZpY2VfYWNjb3VudCIsCiAgInByb2plY3RfaWQiOiAicmFkaWFudC1tZXJjdXJ5LTEyMjkwNyIsCiAgIn.........."

Is it ok to continue using the P12 ?

like image 409
Marcel Avatar asked Mar 02 '16 10:03

Marcel


2 Answers

This works for me using the JSON credentials file from the Google Developers Console. I am using the Analytics Service, but just swap out the appropriate names for the Drive service:

private AnalyticsReportingService service;

public async Task GetAuthorizationByServiceAccount()
    {
        string[] scopes = new string[] { AnalyticsReportingService.Scope.AnalyticsReadonly }; // Put your scopes here
        var keyFilePath = AppContext.BaseDirectory + @"KeyFile.json";

        //Console.WriteLine("Key File: " + keyFilePath);

        var stream = new FileStream(keyFilePath, FileMode.Open, FileAccess.Read);

        var credential = GoogleCredential.FromStream(stream);
        credential = credential.CreateScoped(scopes);

        service = new AnalyticsReportingService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "<Your App Name here>",
        });
    }
like image 156
Sayron5 Avatar answered Nov 04 '22 06:11

Sayron5


Make sure that you are downloading proper file...

GoogleCredential.FromStream(stream)

works with JSON file. Its should look something like this:

{
  "type": "service_account",
  "project_id": "",
  "private_key_id": "",
  "private_key": "-----BEGIN PRIVATE KEY-----
---END PRIVATE KEY-----\n",
  "client_email": "",
  "client_id": "",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": ""
}

You can get this file at https://console.developers.google.com/apis/credentials by clicking Download JSON button on the right side of the grid showing client IDs. Just make sure that Type for selected ID is "Service account client".

like image 1
Igor Avatar answered Nov 04 '22 06:11

Igor