【问题标题】:The access token has expired but we can't refresh it exception访问令牌已过期,但我们无法刷新它异常
【发布时间】:2016-11-23 12:59:55
【问题描述】:

我正在尝试使用 .NET API 从 Google Drive 下载文件。

    private UserCredential _credential;

    protected void Authorize()
    {
        var scopes = new[] {DriveService.Scope.DriveReadonly};

        using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
        {
            var credentialPath = @"App_Data\credential";

            _credential =
                new UserCredential(new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = GoogleClientSecrets.Load(stream).Secrets,
                    Scopes = scopes
                }), Environment.UserName, new TokenResponse());

            // I tried both ways, both result the same exception
            //_credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, scopes, Environment.UserName, CancellationToken.None).Result;
        }
    }

    public Download SaveAsDownload(string fileId)
    {
        if(_credential == null)
            Authorize();

        var service = new DriveService(new BaseClientService.Initializer()
        {
            ApiKey = ApiKey,
            HttpClientInitializer = _credential
        });

        var getRequest = service.Files.Get(fileId);
        var file = getRequest.Execute(); // When I call this I get the exception

        return null;
    }

每次我尝试这样做时,我都会收到“访问令牌已过期但我们无法刷新它”异常。我找到的唯一答案是尝试其他身份验证方式,但我都尝试了,但都导致了相同的异常。 我尝试了 v2 和 v3 版本的 Google SDK。

【问题讨论】:

    标签: c# google-api google-oauth google-api-dotnet-client google-authentication


    【解决方案1】:

    请删除

    ApiKey = ApiKey,

    来自您的 DriveService。当客户端库应该使用您的 OAuth 凭据时,它会尝试使用公共 api 密钥,您对此感到困惑。

    见过几次在图书馆Creating service with credentials and ApiKey发布一个问题

    更新也可能是您的代码的问题

    我的驱动器验证码:

        /// <summary>
        /// This method requests Authentcation 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.DriveReadonly};           // 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);
            }
        }
    

    【讨论】:

    • 没有帮助,还是一样的异常
    猜你喜欢
    • 1970-01-01
    • 2018-06-05
    • 2021-11-16
    • 2017-10-28
    • 2020-06-12
    • 2014-01-01
    • 1970-01-01
    • 2021-12-19
    • 2019-09-28
    相关资源
    最近更新 更多