how use Google OAuth2 using ServiceAccount in .net?

前端 未结 2 1233
谎友^
谎友^ 2020-12-11 17:02

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

private const string SERVICE_ACCOUNT_EMAIL = \"xxxxxxxxxxx@developer.gs         


        
相关标签:
2条回答
  • 2020-12-11 17:42

    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 = "*****",
            });
    
    0 讨论(0)
  • 2020-12-11 17:44
    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": ".....@developer.gserviceaccount.com",
          "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));
    
    0 讨论(0)
提交回复
热议问题