简体   繁体   English

使用Asp.Net MVc获取Google文档api刷新令牌和访问令牌

[英]Get the google docs api refresh token and access token using Asp.Net MVc

Can anyone help me to get the google docs api refresh token for the first time in asp .Net MVC. 谁能帮我第一次在ASP .NET MVC中获取google docs api刷新令牌。 I have client Id and Client Secrete, from this how should i get the refresh token and further from refresh token how should i get the access token to access the google api for drive. 我有客户端ID和客户端密钥,从中我应该如何获取刷新令牌,并且从刷新令牌中进一步应该如何获取访问令牌以访问Google api驱动器。

They haven't done a lot of with the sample code for the Drive API V3 yet have they. 他们还没有对Drive API V3的示例代码做很多事情。 I wouldn't use all of these scopes pick which ones you need this code is pre-generated. 我不会使用所有这些范围来选择您需要哪些代码是预先生成的。

NuGet Package NuGet软件包

PM> Install-Package Google.Apis.Drive.v3 PM> 安装包Google.Apis.Drive.v3

    /// <summary>
    /// This method requests Authentication from a user using Oauth2.  
    /// Credentials are stored in System.Environment.SpecialFolder.Personal
    /// Documentation https://developers.google.com/accounts/docs/OAuth2
    /// </summary>
    /// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
    /// <param name="userName">Identifying string for the user who is being authentcated.</param>
    /// <returns>DriveService used to make requests against the Drive API</returns>
    public static DriveService AuthenticateOauth(string clientSecretJson, string userName)
    {
        try
        {
            if (string.IsNullOrEmpty(userName))
                throw new Exception("userName is required.");
            if (!File.Exists(clientSecretJson))
                throw new Exception("clientSecretJson file does not exist.");

            // 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[] { DriveService.Scope.Drive,                   // View and manage the files in your Google Drive
                                             DriveService.Scope.DriveAppdata,            // View and manage its own configuration data in your Google Drive
                                             DriveService.Scope.DriveFile,               // View and manage Google Drive files and folders that you have opened or created with this app
                                             DriveService.Scope.DriveMetadata,           // View and manage metadata of files in your Google Drive
                                             DriveService.Scope.DriveMetadataReadonly,   // View metadata for files in your Google Drive
                                             DriveService.Scope.DrivePhotosReadonly,     // View the photos, videos and albums in your Google Photos
                                             DriveService.Scope.DriveReadonly,           // View the files in your Google Drive
                                             DriveService.Scope.DriveScripts};           // Modify your Google Apps Script scripts' behavior
            UserCredential credential;
            using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/apiName");

                // Requesting Authentication or loading previously stored authentication for userName
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                         scopes,
                                                                         userName,
                                                                         CancellationToken.None,
                                                                         new FileDataStore(credPath, true)).Result;
            }

            // Create Drive API service.
            return new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Drive Authentication Sample",
                });
        }
        catch (Exception ex)
        {
            Console.WriteLine("Create Oauth2 DriveService failed" + ex.Message);
            throw new Exception("CreateOauth2DriveFailed", ex);
        }
    }

Service account Json key file not the p12 服务帐户Json密钥文件不是p12

 /// <summary>
    /// Authenticating to Google using a Service account
    /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
    /// 
    /// Note: Not all APIs support service accounts I cant garentee this will work.   If you find an api that doesnt support service accoutns contact me 
    ///       me at www.daimto.com and I will remove it from auto genration of this APIs sample project.
    /// </summary>
    /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
    /// <param name="serviceAccountCredentialFilePath">Location of the Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
    /// <returns>DriveService used to make requests against the Drive API</returns>
    public static DriveService AuthenticateServiceAccount(string serviceAccountCredentialFilePath)
    {
        try
        {
            if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                throw new Exception("Path to the .JSon service account credentials file is required.");
            if (!File.Exists(serviceAccountCredentialFilePath))
                throw new Exception("The service account credentials .JSon file does not exist at:" + serviceAccountCredentialFilePath);

            // 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[] { DriveService.Scope.Drive,                   // View and manage the files in your Google Drive
                                             DriveService.Scope.DriveAppdata,            // View and manage its own configuration data in your Google Drive
                                             DriveService.Scope.DriveFile,               // View and manage Google Drive files and folders that you have opened or created with this app
                                             DriveService.Scope.DriveMetadata,           // View and manage metadata of files in your Google Drive
                                             DriveService.Scope.DriveMetadataReadonly,   // View metadata for files in your Google Drive
                                             DriveService.Scope.DrivePhotosReadonly,     // View the photos, videos and albums in your Google Photos
                                             DriveService.Scope.DriveReadonly,           // View the files in your Google Drive
                                             DriveService.Scope.DriveScripts};           // Modify your Google Apps Script scripts' behavior
            Stream stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            var credential = GoogleCredential.FromStream(stream).CreateScoped(scopes);

            // Create the  Drive service.
            return new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Drive Authentication Sample",
            });
        }
        catch (Exception ex)
        {
            Console.WriteLine("Create service account DriveService failed" + ex.Message);
            throw new Exception("CreateServiceAccountDriveServiceFailed", ex);
        }
    }

Let me know if you need anything else I have a partial sample project built. 让我知道您是否还有其他需要,我已构建了部分示例项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM