【问题标题】:ASP.NET MVC C# Google Drive API Redirect mismatch URIASP.NET MVC C# Google Drive API 重定向不匹配 URI
【发布时间】:2021-11-26 00:30:16
【问题描述】:

作为参考,我关注了这个网站https://qawithexperts.com/article/asp-net/upload-file-to-google-drive-using-google-drive-api-in-aspnet/236,了解如何在 Web 应用程序中将文件上传到 Google 云端硬盘。

这是我获取 DriveService 的代码


public static string[] Scopes = { Google.Apis.Drive.v3.DriveService.Scope.Drive };

public static DriveService GetService()
{
    //get Credentials from client_secret.json file 
    UserCredential credential;
    DriveService service = null;

    //Root Folder of project
    var CSPath = System.Web.Hosting.HostingEnvironment.MapPath("~/");
    try
    {
        using (var stream = new FileStream(Path.Combine(CSPath, "client_secret.json"), FileMode.Open, FileAccess.Read))
        {
            String FolderPath = System.Web.Hosting.HostingEnvironment.MapPath("~/");
            String FilePath = Path.Combine(FolderPath, "DriveServiceCredentials.json");
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(FilePath, true)).Result;
        }
        //create Drive API service.
        service = new Google.Apis.Drive.v3.DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "GoogleDriveMVCUpload",
        });
    }
    catch (Exception e)
    {
        System.Diagnostics.Debug.WriteLine(e.StackTrace);
        System.Diagnostics.Debug.WriteLine(e.Message);
        System.Diagnostics.Debug.WriteLine(e.InnerException);

    }
    return service;
            
}

从 GoogleWebAuthorizationBroker.AuthorizeAsync 获取凭据时会出现问题。当该行运行时,我将被重定向到 this link(每次运行此代码时,重定向 URI http://127.0.0.1:52829/authorize/ 的端口都会更改)。

我查看了 Google 的错误文档和其他堆栈溢出,解释说我必须在我执行 shown here 的控制台上添加重定向 URI,但它仍然存在 redirect_uri_mismatch 错误。当我只打开错误中给出的重定向 URI(例如:http://127.0.0.1:52829/authorize/)时,我得到以下信息

。但是会抛出异常

Exception thrown: 'System.AggregateException' in mscorlib.dll
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at System.Threading.Tasks.Task`1.get_Result()
   at .........
One or more errors occurred.
Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"", Description:"", Uri:""
   at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.<AuthorizeAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__1.MoveNext()
**service** was null.

我找不到太多关于这个特定异常错误的信息:

Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"", Description:"", Uri:"" 但我相信这是因为重定向不匹配 URI 问题。

有关更多信息:Web 应用程序的当前链接是 http://localhost:61506,而我运行上述代码时的链接是 http://localhost:61506/AutoFileTransfer/Index

所以我真的不知道为什么会收到此重定向不匹配 URI 错误,也不知道如何解决 Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"", Description:"", Uri:"" 也有问题。

【问题讨论】:

    标签: c# asp.net google-drive-api google-api-dotnet-client


    【解决方案1】:

    您遇到的第一个问题是您使用的是GoogleWebAuthorizationBroker.AuthorizeAsync,它旨在与已安装的应用程序一起使用,但它不适用于 Asp .net

    对于 asp .net MVC,您应该执行以下操作

    using System;
    using System.Web.Mvc;
    
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Auth.OAuth2.Flows;
    using Google.Apis.Auth.OAuth2.Mvc;
    using Google.Apis.Drive.v2;
    using Google.Apis.Util.Store;
    
    namespace Google.Apis.Sample.MVC4
    {
        public class AppFlowMetadata : FlowMetadata
        {
            private static readonly IAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                    {
                        ClientSecrets = new ClientSecrets
                        {
                            ClientId = "PUT_CLIENT_ID_HERE",
                            ClientSecret = "PUT_CLIENT_SECRET_HERE"
                        },
                        Scopes = new[] { DriveService.Scope.Drive },
                        DataStore = new FileDataStore("Drive.Api.Auth.Store")
                    });
    
            public override string GetUserId(Controller controller)
            {
                // In this sample we use the session to store the user identifiers.
                // That's not the best practice, because you should have a logic to identify
                // a user. You might want to use "OpenID Connect".
                // You can read more about the protocol in the following link:
                // https://developers.google.com/accounts/docs/OAuth2Login.
                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; }
            }
        }
    }
          
    

    官方样品可以在web-applications-asp.net-mvc找到

    您遇到的第二个问题是您的 IDE 正在更改您的端口。您需要对其进行修复,使其使用静态端口,然后您才能正确添加重定向 uri。 How to create Google Oauth2 web application credentials in 2021.Google OAuth2: How the fix redirect_uri_mismatch error. Part 2 server sided web applications.

    至于你正在关注的那个例子,作者可能已经让它在本地主机上工作,但它永远不会作为网站托管,因为 GoogleWebAuthorizationBroker.AuthorizeAsync 将在运行它的机器上打开浏览器窗口。这是一个网络服务器永远不会工作。

    【讨论】:

    • 非常感谢您详细而迅速的回复。我能够让它工作!
    • @WilliamTjandra 你是如何让它工作的?我也按照该教程进行操作,但无法让我的上传器正常工作。我本应该在几个小时内完成这个项目,并错误地认为教程很简单。 ://
    • @Jamie 用你的代码打开一个新问题,我很乐意看看
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    相关资源
    最近更新 更多