ASP.NET MVC 网站应用程序上传文件 Google Drive API URI 不匹配

ASP.NET MVC website application to upload files with Google Drive API URI mismatch

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

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

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();
            }
        }
    }
}

和 post

[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();
    }

我听说教程引用的代码仅适用于独立应用程序而不适用于网络应用程序,因此教程中的屏幕截图来自网站很奇怪。 耸耸肩 我会继续寻找提示和技巧,但与此同时,我正在 post 查看是否有其他人编写了一个网站以通过 Google 驱动器到特定文件夹,而不是根目录。 TIA!

编辑:这是我在 Google 云控制台中设置的重定向 URI 的屏幕截图。产品和本地主机

编辑:Startup.Auth.cs - 这用于通过 ADFS 身份验证,与 Google 驱动器 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
                // 
                CookieManager = new SystemWebCookieManager()
            });
        app.UseWsFederationAuthentication(
            new WsFederationAuthenticationOptions
            {
                Wtrealm = ConfigurationManager.AppSettings["ida:Wtrealm"],
                MetadataAddress = ConfigurationManager.AppSettings["ida:ADFSMetadata"]
            });
    }

领域与 Google 控制台中的 URI 匹配并且元数据相同 xml link 我在所有使用 ADFS 传递身份验证的 Web 应用程序中使用,它具有完美地工作。我的 web.config 文件中没有提到 Google 所说的 IP 地址也是我的重定向 URI。

The URI that Google shows isn't even a part of the website, nor is a URI that I supplied to Google, so I have no idea where it's coming from.

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

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

此视频将向您展示如何添加它。 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};
        });
}