user1935938
user1935938

Reputation: 113

how use Google OAuth2 using ServiceAccount in .net?

Is there any sample how to access a google service API using service account in .net?

private const string SERVICE_ACCOUNT_EMAIL = "[email protected]";
private const string SERVICE_ACCOUNT_PKCS12_FILE_PATH = @"\path\test-privatekey.p12";

static DriveService BuildService() 
{
    X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret",
    X509KeyStorageFlags.Exportable);

    var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
    {
        ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
        Scope = DriveService.Scopes.Drive.GetStringValue(),
    };
    var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);

    return new DriveService((new BaseClientService.Initializer()
    {
        Authenticator = auth
    });
}

This isn't successful in returning a OAuth connection. How can this be done?

Upvotes: 9

Views: 5891

Answers (2)

  1. Create a Service Account Keys credencial
  2. Create private key for service. (Key json). Example:
    {
      "type": "service_account",
      "project_id": "...",
      "private_key_id": "....",
      "private_key": "....",
      "client_email": "[email protected]",
      "client_id": "....",
      "auth_uri": "...accounts.google.com/o/oauth2/auth",
      "token_uri": "...accounts.google.com/o/oauth2/token",
      "auth_provider_x509_cert_url": "...www.googleapis.com/oauth2/v1/certs",
      "client_x509_cert_url": "...www.googleapis.com/robot/v1/metadata/x509/....-compute%40developer.gserviceaccount.com"
    }
  1. With this json you must generate a c# class. You can using (http://json2csharp.com/). This is faster
  2. Use this code to generate credencial:
       var _pathJson = @"C:\servicekey.json";
       var json = File.ReadAllText(_pathJson);
       var cr = JsonConvert.DeserializeObject<PersonalServiceAccountCred>(json); 
       // "personal" service account credential
       // Create an explicit ServiceAccountCredential credential
       var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.ClientEmail)
                {
                    Scopes = new[] { YouTubeService.Scope.YoutubeUpload /*Here put scope that you want use*/}
                }.FromPrivateKey(cr.PrivateKey));

Upvotes: 4

This case work in my site

var certificate = new X509Certificate2("pathTo***.p12", "notasecret", X509KeyStorageFlags.Exportable);
        var serviceAccountEmail = "********-*********@developer.gserviceaccount.com";
        var userAccountEmail = "******@gmail.com";
        ServiceAccountCredential credential = new ServiceAccountCredential(
                   new ServiceAccountCredential.Initializer(serviceAccountEmail)
                   {
                       Scopes = new[] { DriveService.Scope.Drive },
                       User = userAccountEmail

                   }.FromCertificate(certificate));

        // Create the service.
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "*****",
        });

Upvotes: 2

Related Questions