1

我想讓一個Web應用程序是ASP.NET MVC 5,通過它我可以使用Google帳戶對用戶進行身份驗證,然後從存儲在Google Drive/Google中的電子表格中讀取數據表。重複使用GData API中的Google API憑證

我正在使用Google API驗證用戶身份。用戶認證成功後,我得到的憑證從谷歌回到了一個對象,它是類型的Google.Apis.Auth.OAuth2.Web AuthResult.UserCredential

然後我就可以成功創建服務使用類似的代碼從驅動器文件列出來

var driveService = new DriveService(new BaseClientService.Initializer { HttpClientInitializer = result.Credential, ApplicationName = "ASP.NET MVC Sample" });

現在,我想使用GData API從Drive中的電子表格中讀取內容。爲此,我需要有一個SpreadsheetsService對象,然後將它的參數RequestFactory設置爲GOAuth2RequestFactory的實例,並且這又需要在類OAuth2Parameters的實例中指定OAuth2參數。

如何重新使用在GData API中使用Google API獲得的憑證?

+0

爲什麼不創建一個SpreadsheetsService?只要創建憑據時使用的範圍允許驅動器和SpreadsheetsService,那麼您就沒有理由不能創建兩者。 – DaImTo 2014-10-27 11:41:40

+0

我已經創建了一個'SpreadsheetsService'。我不想再次啓動認證週期。我正在尋找一種在GData中使用來自API的憑證的方法 – 2014-10-27 11:51:18

+0

不要以爲我明白創建新服務的問題不會再次啓動身份驗證,您已經有了result.credentials,只是在兩者中都使用它。 – DaImTo 2014-10-27 12:04:45

回答

0

這是最終爲我工作

public class AppFlowMetadata : FlowMetadata 
     { 
      private static readonly IAuthorizationCodeFlow flow = 
       new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer 
       { 
        ClientSecrets = new ClientSecrets 
        { 
         ClientId = "randomstring.apps.googleusercontent.com", 
         ClientSecret = "shhhhhh!" 
        }, 
        Scopes = new[] { DriveService.Scope.Drive, "https://spreadsheets.google.com/feeds", "https://docs.google.com/feeds", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" }, 
        DataStore = new FileDataStore("Drive.Api.Auth.Store") 
       }); 

      public override string GetUserId(Controller controller) 
      { 

       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; } } 

     } 

然後代碼,在控制器的OAuth2參數複製到的GData

var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()). 
       AuthorizeAsync(cancellationToken); 
OAuth2Parameters parameters = new OAuth2Parameters(); 
       parameters.ClientId = "somestring.apps.googleusercontent.com"; 
       parameters.ClientSecret = "shhhhhh!"; 
       parameters.Scope = result.Credential.Token.Scope; 
       parameters.AccessToken = result.Credential.Token.AccessToken; 
       parameters.RefreshToken = result.Credential.Token.RefreshToken; 

       GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters); 

       SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1"); 
       service.RequestFactory = requestFactory;