【问题标题】:ASP.NET MVC website application to upload files with Google Drive API URI mismatchASP.NET MVC 网站应用程序上传与 Google Drive API URI 不匹配的文件
【发布时间】:2022-02-04 19:53:09
【问题描述】:

我正在尝试使用 Google Drive API 上传文件,并在单击我页面上的上传按钮时收到来自 Google 的 URI 不匹配错误。 Google 显示的 URI 甚至不是网站的一部分,我提供给 Google 的 URI 也不是,所以我不知道它来自哪里。

这是我基于 this tutorial 创建的 APIHelper 类(这表明代码应该可以在网站上运行)

public class GoogleDriveAPIHelper
{
    //add scope
    public static string[] Scopes = { DriveService.Scope.Drive };

    //create Drive API service.
    public static DriveService GetService()
    {
        //get Credentials from client_secret.json file 
        UserCredential credential;
        //Root Folder of project
        var CSPath = System.Web.Hosting.HostingEnvironment.MapPath("~/");
        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.
        DriveService service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Documents Uploader",
        });
        return service;
    }


    //file Upload to the Google Drive.
    public static void UploadFile(string folderID, HttpPostedFileBase file)
    {
        if (file != null && file.ContentLength > 0)
        {
            //create service
            DriveService service = GetService();
            string path = Path.Combine(HttpContext.Current.Server.MapPath("~/GoogleDriveFiles"),
            Path.GetFileName(file.FileName));
            file.SaveAs(path);
            var FileMetaData = new Google.Apis.Drive.v3.Data.File
            {
                Name = Path.GetFileName(file.FileName),
                MimeType = MimeMapping.GetMimeMapping(path),
                //id of parent folder 
                Parents = new List<string>
                {
                    folderID
                }
            };
            FilesResource.CreateMediaUpload request;
            using (var stream = new FileStream(path, FileMode.Open))
            {
                request = service.Files.Create(FileMetaData, stream, FileMetaData.MimeType);
                request.Fields = "id";
                request.Upload();
            }
        }
    }
}

还有帖子

[HttpPost]
    public ActionResult Index(HttpPostedFileBase file)
    {
        string folderID = "1L9QUUgmtg8KUdNvutQ1yncIwN_uLz4xs";
        if (TempData["Success"] == null)
        {
            // show all fields
            ViewBag.ShowForm = true;
            ViewBag.ShowButtons = false;
        }
        else
        {
            // hide all elements on the page for success message
            ViewBag.ShowForm = false;
            ViewBag.ShowButtons = true;
        }
        GoogleDriveAPIHelper.UploadFile(folderID, file);
        TempData["Success"] = "File successfully uploaded";
        return View();
    }

我听说教程引用的代码仅适用于独立应用程序而不适用于 Web 应用程序,因此教程中的屏幕截图来自网站很奇怪。 耸耸肩 我会继续寻找技巧和窍门,但与此同时,我发布此内容是为了查看是否有其他人编写了一个网站以通过 Google 驱动器上传到特定文件夹,而不是根。蒂亚!

编辑:以下是我在 Google Cloud Console 中设置的重定向 URI 的屏幕截图。产品和本地主机

编辑:Startup.Auth.cs - 用于通过 ADFS 身份验证,与 Google Drive API 无关

 private void ConfigureAuth(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        app.UseCookieAuthentication(
            new CookieAuthenticationOptions
            {
                // TempData and Owin don't get along, use this workaround to force a custom cookie manager
                // https://stackoverflow.com/questions/28559237/intermittent-redirection-loops-during-adfs-authentication
                CookieManager = new SystemWebCookieManager()
            });
        app.UseWsFederationAuthentication(
            new WsFederationAuthenticationOptions
            {
                Wtrealm = ConfigurationManager.AppSettings["ida:Wtrealm"],
                MetadataAddress = ConfigurationManager.AppSettings["ida:ADFSMetadata"]
            });
    }

领域与 Google 控制台中的 URI 相匹配,元数据与我在所有使用 ADFS 的 Web 应用程序中使用的 xml 链接相同,通过身份验证,它可以完美运行。我的 web.config 文件中也没有提到 Google 所说的 IP 地址是我的重定向 URI。

【问题讨论】:

  • 首先您的应用是否在谷歌云控制台中投入生产?其次,您可以发布您设置的重定向 uri 的图片吗?
  • 是的,它在 GCC 中设置为生产,我将添加我设置的重定向 URI 的屏幕截图。
  • 您也可以发布您的身份验证代码吗?如果您使用 Javascript,则只需添加 Javascript 源。
  • 我添加了我的 Startup.Auth 类,感谢您的关注
  • 我用代码走了一条不同的路线,但仍然有一个 URI 不匹配,只是这次有点不同。我会发布这个问题,因为我现在被这个问题困住了。

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


【解决方案1】:

Google 显示的 URI 甚至不是网站的一部分,我提供给 Google 的 URI 也不是,所以我不知道它来自哪里。

重定向 uri 是在购买您正在使用的客户端库时构建的。您的应用程序设置为运行 http 而不是 https 它正在运行的 localhost 并且未托管,因此它的 127.0.0.1 端口也是由您的应用程序随机生成的,或者是您静态设置的。 /authorize 由客户端库再次附加。

重定向 uri 是您的代码准备接受来自授权服务器的响应的位置。此 URI 需要在 Google Cloud Console 中配置。最简单的解决方案是完全复制它并将其作为重定向 uri 添加到 Google 云控制台中。只要确保您的应用程序设置为使用静态端口,如果端口更改将无法正常工作。

此视频将向您展示如何添加它。 Google OAuth2: How the fix redirect_uri_mismatch error. Part 2 server sided web applications.

Web applications

public void ConfigureServices(IServiceCollection services)
{
    ...

    // This configures Google.Apis.Auth.AspNetCore3 for use in this app.
    services
        .AddAuthentication(o =>
        {
            // This forces challenge results to be handled by Google OpenID Handler, so there's no
            // need to add an AccountController that emits challenges for Login.
            o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
            // This forces forbid results to be handled by Google OpenID Handler, which checks if
            // extra scopes are required and does automatic incremental auth.
            o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
            // Default scheme that will handle everything else.
            // Once a user is authenticated, the OAuth2 token info is stored in cookies.
            o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie()
        .AddGoogleOpenIdConnect(options =>
        {
            options.ClientId = {YOUR_CLIENT_ID};
            options.ClientSecret = {YOUR_CLIENT_SECRET};
        });
}

【讨论】:

  • 我的网络应用程序设置为使用 https。我必须对所有 Web 应用程序使用 SSL,因为我首先通过 ADFS 服务器进行身份验证。我为 live 和 localhost 添加的依赖方信任也没有提到该 IP 地址,所以我仍然不确定不匹配的来源。 :(
  • 它不是您的应用程序在127.0.0.1:port/authorize 上运行该库从您的应用程序中获取设置。只需获取它设置的确切重定向 uri 并将其用作谷歌云控制台中的重定向 uri。
  • 我无法将 Google 中的重定向设置为 IP 地址,它不允许我这样做。 Invalid Redirect: must end with a public top-level domain (such as .com or .org).Invalid Redirect: must use a domain that is a valid top private domain.
  • 这可能是因为您的项目设置为生产。您需要让您的应用程序在 Web 服务器上运行并使用该域。此时您将获得 http://yourdomain/authorize | localhost 仅在您在本地开发时才有效。我认为这一切都取决于您的应用程序中的设置。你确定你正确设置了 ASPNETCORE_URLS。
  • 在生产中出现访问被拒绝错误。很抱歉我应该提到这一点。我认为在提到它在服务器上也不起作用之前先让 localhost 运行会更容易。它一直引用该 IP 地址。不过我不使用 Core,我使用 MVC,所以我不确定 ASPNETCORE_URLS 是什么。
猜你喜欢
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
相关资源
最近更新 更多