2017-05-08 1 views
2

Azure 함수를 사용하여 Google Apis에 액세스하려고합니다. 목표는 연결하여 여러 개의 Google 스프레드 시트의 내용을 Azure SQL 데이터베이스에로드하는 것입니다. 나는 샘플 코드 here을보고 있었지만 Azure 함수를 사용하여 작동하게 만드는 방법을 알 수 없다.Azure 함수에서 Google Apis 사용하기

오류 CS0234 : 나는 '#LOAD "AppFlowMetadata.csx"를'사용 AppFlowMetadata.csx 파일을 만들어 내 run.csx에 참조 사용하는 경우

, 나는 여러 컴파일 에러가 발생 유형 또는 'System.Web'네임 스페이스에 'Mvc'네임 스페이스 이름이 없습니다 (어셈블리 참조가 누락 되었습니까?)

오류 CS0234 : 형식 또는 네임 스페이스 이름 'Mvc'이 (가) 네임 스페이스 'Google.Apis .Auth.OAuth2 '(어셈블리 참조가 누락 되었습니까?)

오류 CS0246 : 형식 또는 이름 페이스 이름 'FlowMetadata'를 찾을 수 없습니다 (사용 지시문이나 어셈블리 참조가 누락 되었습니까?)

오류 CS0246 : 형식 또는 네임 스페이스 이름 'Controller'를 찾을 수 없습니다. 사용 지시문이나 어셈블리 참조)

오류 CS0115 : 'AppFlowMetadata.GetUserId (컨트롤러)'

오류 CS0115을 무시할 찾지 적합한 방법 'AppFlowMetadata.Flow'무시할 찾지 적합한 방법

AppFlwMetadata.csx :

using System; 
using System.Web.Mvc; 

using Google.Apis.Auth.OAuth2; 
using Google.Apis.Auth.OAuth2.Flows; 
using Google.Apis.Auth.OAuth2.Mvc; 
using Google.Apis.Drive.v3; 
using Google.Apis.Util.Store; 

public class AppFlowMetadata : FlowMetadata 
{ 
private static readonly IAuthorizationCodeFlow flow = 
    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") 
     }); 

public override string GetUserId(Controller controller) 
{ 
    // In this sample we use the session to store the user identifiers. 
    // That's not the best practice, because you should have a logic to identify 
    // a user. You might want to use "OpenID Connect". 
    // You can read more about the protocol in the following link: 
    // https://developers.google.com/accounts/docs/OAuth2Login. 
    var user = controller.Session["user"]; 
    if (user == null) 
    { 
     user = Guid.NewGuid(); 
     controller.Session["user"] = user; 
    } 
    return user.ToString(); 

} 

public override IAuthorizationCodeFlow Flow 
{ 
    get { return flow; } 
} 
} 

project.json :

{ 
"frameworks": { 
"net46":{ 
    "dependencies": { 
    "Google.Apis.Drive.v3": "1.25.0.834", 
    "Google.Apis.Sheets.v4": "1.25.0.841", 
    "Google.Apis.Auth":"1.25.0" 
    } 
} 
} 
} 

사람이 성공적으로 구글 API를 사용하여 인증하는 푸른 기능을 사용 했습니까? Azure에 Google 예제를 적용하는 방법에 대한 지침이 있습니까?

+0

Oauth2를 사용하여 인증하는 것이 어떻게 가능할지 모르겠습니다. webhook은 액세스 권한을 요청한 다음 승인되지 않은 서버에서 반환을 수락해야합니다. 이걸 어떻게 해고하겠습니까? – DaImTo

+0

일정에 따라 Google 드라이브의 파일 메타 데이터를 가져와 마지막 풀 이후 시트가 업데이트되었는지 확인한 다음 Azure sql DB에 내용을로드하십시오. –

+0

누가 운전 계정인가 – DaImTo

답변

1

정확하게 시도하지 않았습니다. IMO는 Oauth2를 사용할 수 없도록 서비스 계정으로 시도하는 것이 좋습니다.

서비스 계정 키 파일을 업로드하는 방법을 알아야합니다.

/// <summary> 
    /// Authenticating to Google using a Service account 
    /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount 
    /// </summary> 
    /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param> 
    /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param> 
    /// <returns>AnalyticsService used to make requests against the Analytics API</returns> 
    public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath) 
    { 
     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."); 

      // These are the scopes of permissions you need. It is best to request only what you need and not all of them 
      string[] scopes = new string[] { AnalyticsReportingService.Scope.Analytics };    // View your Google Analytics data 

      // 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) 
     { 
      Console.WriteLine("Create service account DriveService failed" + ex.Message); 
      throw new Exception("CreateServiceAccountDriveFailed", ex); 
     } 
    } 
} 

Google 드라이브 용 My GitHub 샘플 프로젝트에서 코드가 추출되었습니다. Serviceaccount.cs 나는 또한 튜토리얼에 대해 Drive API with service accounts

만약 내가 할 수 없다면 나에게 재미있는 생각처럼 들린다.

+0

내 개인 Google 드라이브의 파일을이 새로운 서비스 계정으로 공유하여 액세스 할 수있는 방법을 알고 계십니까? 서비스 계정을 나타 내기 위해 어떤 전자 메일 주소를 입력합니까? –

+1

감사합니다.이 예제를 Google 스프레드 시트의 다른 유사한 사용 사례에 사용할 수있었습니다. –

관련 문제