为什么连接Google OAuth2后结果.Credential为空?

问题描述 投票:0回答:1

我使用下面的代码来授权和刷新令牌,以更新我的 ASP.net MVC 项目中 Google 表中的一些数据, 我知道1小时后令牌就会过期,所以我检查了过期时间并刷新了令牌, 下面代码中我的问题是 1 小时后 result.Credential 为 null 并且 result.redirectUri 再次具有连接帐户的值! 我想联系一辈子 笔记: FileDataStore 工作并将数据保存到 C:\Token

private async Task SendToGooggleSheet(List<string> columns, List<List<string>> rows, int formId, int answerId, string userId, string sheetid)
     {
        try
        {
            TempData["FormUserId"] = userId + "_" + formId;
            CancellationToken cancellationToken;
            CancellationTokenSource cts = new CancellationTokenSource();
            cts.CancelAfter(TimeSpan.FromSeconds(50));
            cancellationToken = cts.Token;
    
            var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
               AuthorizeAsync(cancellationToken);
    
            if (result.Credential != null)
            {                   
    
                if (result.Credential.Token.IsExpired(SystemClock.Default))
                {
                    //var accessToekn = await result.Credential.GetAccessTokenForRequestAsync(); // this 2 line works for refresh token
                    var refreshResult = await result.Credential.RefreshTokenAsync(cancellationToken);
                }
    ....
            }
    ...
    }
    /////////////////////
    
        public class AppFlowMetadata : FlowMetadata
        {
            private static readonly IAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = ePoll.Model.GlobalApplicationData.GoogleDriveAuthorizationClientId,
                        ClientSecret = ePoll.Model.GlobalApplicationData.GoogleDriveAuthorizationSecretId
                    },
                    Scopes = new[] { DriveService.Scope.DriveFile,SheetsService.Scope.DriveFile},
                    DataStore = new FileDataStore(ePoll.Model.GlobalApplicationData.GoogleSheetOauthSaveFolder, true), //C:\Token               
                });
    
            public override string GetUserId(Controller controller)
            {            
                var user = controller.TempData["FormUserId"];
                return user?.ToString();
            }
    
            public override IAuthorizationCodeFlow Flow
            {
                get { return flow; }
            }
            
        }
c# asp.net google-oauth google-sheets-api
1个回答
0
投票

与刷新令牌有关, 要强制Google返回新的刷新令牌,您可以将prompt=consent参数添加到您的OAuth请求中。

© www.soinside.com 2019 - 2024. All rights reserved.