Google.GData.Client.GDataRequestException - Authentication suddenly fails in old code

前端 未结 4 2078
逝去的感伤
逝去的感伤 2020-12-03 14:52

I\'m suddenly starting to get the following exception when attempting to authenticate and access a spreadsheet on Google drive:

Unhandled Exception: G

4条回答
  •  执笔经年
    2020-12-03 15:20

    I've managed to solve this by using this solution with Service Account with oAuth2.0 Accessing older GData APIs (Spreadsheet API) using OAuth 2 and a service account

    The solution: 1. Create Project and Google Service Account in https://console.developers.google.com/project

    1. Generate your p12 key.
    2. Allow APIs in Developer console you want to use (basically we are going to use old API, so you can skip this step, but just in case)
    3. Use the code below (.NET Framework 4.5!)
    4. Also don't forget to grant "youraccount@developer.gserviceaccount.com" access to your spreadsheet document as you grant permissions for usual users by pressing Share.

    Code:

    using System.Security.Cryptography.X509Certificates;
    using Google.GData.Client;
    using Google.GData.Extensions;
    using Google.GData.Spreadsheets;
    using Google.Apis.Auth.OAuth2;
    
    string keyFilePath = @"C:\key.p12";    // found in developer console
    string serviceAccountEmail = "youraccount@developer.gserviceaccount.com";   // found in developer console
    var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
    
    ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) //create credential using certificate
            {
                Scopes = new[] { "https://spreadsheets.google.com/feeds/" } //this scopr is for spreadsheets, check google scope FAQ for others
            }.FromCertificate(certificate));
    
    credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Wait(); //request token
    
    var requestFactory = new GDataRequestFactory("Some Name"); 
    requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", credential.Token.AccessToken));
    
    SpreadsheetsService myService = new SpreadsheetsService("You App Name"); //create your old service
    myService.RequestFactory = requestFactory; //add new request factory to your old service
    
    SpreadsheetQuery query = new SpreadsheetQuery(); //do the job as you done it before
    SpreadsheetFeed feed = myService.Query(query);
    

提交回复
热议问题