2016-12-21 4 views
0

Google 스프레드 시트를 사용하여 개발 한 애플리케이션이 있습니다. C# .NET에서 개인 계정 대신 서비스 계정으로 Google 스프레드 시트를 사용하도록 인증합니다.

는 나는 다음 코드를 사용하여 Google 시트 API에 액세스 할 수 있도록하는 방법을 알아 내기 할 수 있었다 :

UserCredential credential; 
    using (var stream = 
        new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) 
    { 
     string credPath = System.Environment.GetFolderPath(
      System.Environment.SpecialFolder.Personal); 


     credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
      GoogleClientSecrets.Load(stream).Secrets, 
      Scopes, 
      "user", 
      CancellationToken.None, 
      new FileDataStore(credPath, true)).Result; 
     Console.WriteLine("Credential file saved to: " + credPath); 
    } 
    // Create Google Sheets API service. 
    var service = new SheetsService(new BaseClientService.Initializer() 
    { 
     HttpClientInitializer = credential, 
     ApplicationName = ApplicationName, 
    }); 

이 응용 프로그램은 몇 가지 다른 사람들에 의해 사용됩니다 -하지만 처음 그들이 애플리케이션을 실행하여 Google에 로그인하라는 요청을하지만, 해당 계정이 적절한 액세스 권한을 부여하지는 않습니다.

서비스 계정을 사용하면 내 문제가 해결되고 더 이상 사용자에게 '로그인'하라는 메시지가 표시되지 않지만 내 응용 프로그램은 스프레드 시트를 적절히 읽고 업데이트 할 수 있습니다.

기존 코드를 수정하고 서비스 계정을 사용하도록 수정하고 싶지만 그 방법에 대한 좋은 설명서를 찾을 수 없습니다. 서비스 계정을 만들고 현재 'client_secret.json'파일과 동일한 위치에 ServiceAccount.json 파일을 가지고 있지만 훨씬 더 진행하는 방법을 모르겠습니다.

나는에 코드를 변경 시도 :

ServiceAccountCredential credential; 
    //UserCredential credential; 
    using (var stream = 
     new FileStream("HelperServiceAccount.json", FileMode.Open, FileAccess.Read)) 
    { 
     string credPath = System.Environment.GetFolderPath(
      System.Environment.SpecialFolder.Personal); 


     credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
      GoogleClientSecrets.Load(stream).Secrets, 
      Scopes, 
      "user", 
      CancellationToken.None, 
      new FileDataStore(credPath, true)).Result; 
      ) 
     Console.WriteLine("Credential file saved to: " + credPath); 
    } 
    // Create Google Sheets API service. 
    var service = new SheetsService(new BaseClientService.Initializer() 
    { 
     HttpClientInitializer = credential, 
     ApplicationName = ApplicationName, 
    }); 

그러나 실패 - 자격 증명 변수에 오류가 있습니다.

아이디어가 있으십니까?

+1

당신은 [대한의 OAuth 2.0을 사용하는 방법에 대한 문서를 확인 할 수 있습니다를 Server to Server Applications] (https://developers.google.com/identity/protocols/OAuth2ServiceAccount)에서 Google 시트 API에 액세스하기위한 서비스 계정을 올바르게 인증하는 방법에 대해 설명합니다. 서비스 계정을 사용하여 스프레드 시트 API에 액세스 할 수있는 nodejs의 [샘플] (https://www.npmjs.com/package/google-spreadsheet)이 있습니다. –

+1

마지막으로 [.NET, OAuth 2.0 및 서비스 계정을 사용하여 Google의 스프레드 시트 API 사용하기] (https://markembling.info/2012/12/google-spreadsheet-dotnet-oauth2-service-account)를 읽으면 도움이 될 것입니다. 당신은 C# 코드 구현을 이해합니다. 이것이 도움이됩니다. –

+1

감사합니다. 나는 웹 사이트를 여행하면서 그 사이트를 우연히 발견했다. 비록 p12 파일을 다루었지만 .json 파일로 작업하고있다. 나는 거의 내가 거기에 있다고 생각한다 - 나는 당신의 도움에 감사한다! – Hanny

답변

-2

저는이 프로젝트를 통해 사용자가 json 또는 p12 자격 증명 파일을 사용하여 서비스 계정 자격 증명을 만들 수 있도록했습니다. 도메인의 사용자 데이터에 액세스하려면 이전에 와이드 도메인 위임 옵션을 사용하도록 설정해야합니다.

GoogleApiServiceFactory

+1

솔루션에 대한 링크는 환영합니다. 그러나 링크가없는 상황에서 유용한 답변을 제공하십시오. (// meta.stackexchange.com/a/8259) 동료 사용자는 그것이 무엇인지 알 수 있습니다. 그리고 왜 그곳에 있는지, 그리고 목표 페이지를 사용할 수 없을 때 당신이 링크하고있는 페이지의 가장 중요한 부분을 인용하십시오. [링크 이상인 답변은 삭제 될 수 있습니다.] (// stackoverflow.com/help/deleted-answers) –

+0

이 링크가 질문에 대답 할 수 있지만 여기에 답변의 핵심 부분을 포함시키고 참조 용 링크. 링크 된 페이지가 변경되면 링크 전용 답변이 유효하지 않게 될 수 있습니다. - [From Review] (리뷰/저품절 게시물/18741679) –

0

당신은 서비스 계정을 생성하고, JSON 자격 증명 파일을 저장해야 :

그런 다음이 시도 :

 ServiceAccountCredential credential; 
     string[] Scopes = { SheetsService.Scope.Spreadsheets }; 
     string serviceAccountEmail = "[email protected]"; 
     string jsonfile = "xxxxxxxx-xxxxxxx.json"; 
     using (Stream stream = new FileStream(@jsonfile, FileMode.Open, FileAccess.Read, FileShare.Read)) 
     { 
      credential = (ServiceAccountCredential) 
       GoogleCredential.FromStream(stream).UnderlyingCredential; 

      var initializer = new ServiceAccountCredential.Initializer(credential.Id) 
      { 
       User = serviceAccountEmail, 
       Key = credential.Key, 
       Scopes = Scopes 
      }; 
      credential = new ServiceAccountCredential(initializer); 
     }