0
votes

i am using c# language the service get me exception

"failed to launch browser with https //accounts.google.com/o/oauth2/v2/auth"

the steps that i followed :

  1. Enable Google drive api service from google console developer
  2. Generate client id, client secret (i tried two type of OAuth Client id type {Web Application and Other} the two type get me the same exception

My code is :

    public File InsertFile(byte[] byteArray)
    {
        // File's metadata
        File body = new File();
        body.Title = "my title";
        body.Description = "my description";
        body.MimeType = "image/jpg";

        // File's content.
        System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

        try
        {

            var credential = Authentication();

            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = string.Format("{0} elfeedback-project", System.Diagnostics.Process.GetCurrentProcess().ProcessName),
            });

            FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "image/jpg");
            request.UploadAsync();

            File file = request.ResponseBody;

            return file;
        }
        catch (Exception ex)
        {
            return null;
        }
    }`

the Authentication get exception :

    `public UserCredential Authentication()
    {
        string[] scopes = { DriveService.Scope.Drive,
                   DriveService.Scope.DriveFile,
        };

        UserCredential credential;
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        new ClientSecrets
        {
            ClientId = "my client id",
            ClientSecret = "my client secret"
        },
        scopes,
        "myGmail Account that authenticated (client id ,client secret)",
        CancellationToken.None,
        new FileDataStore("Drive.Auth.Store")).Result;

        return credential;
    }
1

1 Answers

0
votes

You are using the code for installed applcations. The code is trying to open a new browser window for consent on the server rather than on the users browser.

new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets
                {
                    ClientId = "PUT_CLIENT_ID_HERE",
                    ClientSecret = "PUT_CLIENT_SECRET_HERE"
                },
                Scopes = new[] { DriveService.Scope.Drive },
                DataStore = new FileDataStore("Drive.Api.Auth.Store")
            });

update

If you want to upload to an account that you control then you should look into useing a service account. Service accounts are dummy users they have their own google drive account which you can upload to. You can not use a web view to see what is on this account. You will need to create service account credentials not OAuth credentials.

public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
        {
            try
            {
                if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                    throw new Exception("Path to the service account credentials file is required.");
                if (!File.Exists(serviceAccountCredentialFilePath))
                    throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
                if (string.IsNullOrEmpty(serviceAccountEmail))
                    throw new Exception("ServiceAccountEmail is required.");                

                // For Json file
                if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
                {
                    GoogleCredential credential;
                    using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                    {
                        credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(scopes);
                    }

                    // Create the  Analytics service.
                    return new DriveService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Drive Service account Authentication Sample",
                    });
                }
                else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
                {   // If its a P12 file

                    var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
                    var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
                    {
                        Scopes = scopes
                    }.FromCertificate(certificate));

                    // Create the  Drive service.
                    return new DriveService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Drive Authentication Sample",
                    });
                }
                else
                {
                    throw new Exception("Unsupported Service accounts credentials.");
                }

            }
            catch (Exception ex)
            {                
                throw new Exception("CreateServiceAccountDriveFailed", ex);
            }
        }
    }

code ripped from ServiceAccount.cs