如何创建具有访问权限和Google Drive API令牌的凭证对象

Sha*_*han 1 c# asp.net-mvc oauth google-drive-api google-api-dotnet-client

我想对工作表和Google驱动器api使用相同的OAuth代码和令牌,而无需将工作表和驱动器重定向到第2页。

以下是使用oauth 2生成访问代码和令牌的代码

                string SCOPE = "https://spreadsheets.google.com/feeds https://docs.google.com/feeds";
                OAuth2Parameters parameters = new OAuth2Parameters();
                parameters.ClientId = CLIENT_ID;
                parameters.ClientSecret = CLIENT_SECRET;
                parameters.RedirectUri = REDIRECT_URI;
                parameters.Scope = SCOPE;
                string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters); 
                OAuthUtil.GetAccessToken(parameters);
                string accessToken = parameters.AccessToken;
Run Code Online (Sandbox Code Playgroud)

就像在asp.net mvc中一样,它是通过重定向Google表格API生成的。

我也想使用Google Drive API来获得相同的令牌。

我如何才能为Google Drive API 创建凭据对象,以便与其一起使用。遵循代码打开另一个窗口并将代码发送到该窗口。

var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
      {
         ClientId = clientId,
         ClientSecret = clientSecret
      }, scopes, "skhan", CancellationToken.None, new FileDataStore("Drive.Auth.Store")).Result;
Run Code Online (Sandbox Code Playgroud)

Sag*_*tay 5

您可以使用下面的代码,假设您已经具有访问/刷新令牌:

var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
    {
        ClientSecrets = new ClientSecrets
            {
                ClientId = ClientId,
                ClientSecret = ClientSecret
            },
            Scopes = new[] { DriveService.Scope.Drive }
    });

var credential = new UserCredential(_flow, UserIdentifier, new TokenResponse
    {
        AccessToken = AccessToken,
        RefreshToken = RefreshToken
    });
var service = new DriveService(new BaseClientService.Initializer
    {
        ApplicationName = "MyApp",
        HttpClientInitializer = credential,
        DefaultExponentialBackOffPolicy = ExponentialBackOffPolicy.Exception | ExponentialBackOffPolicy.UnsuccessfulResponse503
    });
Run Code Online (Sandbox Code Playgroud)