错误:redirect_uri_mismatch Google API,如何解决? [英] Error: redirect_uri_mismatch Google API, how to fix?

查看:175
本文介绍了错误:redirect_uri_mismatch Google API,如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了这个HTTP触发azure函数,该函数包含(以下)用于自动将视频上传到YouTube的代码.来源:( https://developers.google.com/youtube/v3/docs/videos/insert ).

I have created this HTTP trigger azure function, which contains the code(below) to upload a video to YouTube automatically. Source: (https://developers.google.com/youtube/v3/docs/videos/insert).

我还使用Google Console API创建了Client_Id和Client_secret,并将这些数据存储在client_secrets.json文件中. (例如 https://github.com/youtube/api-样本/blob/master/dotnet/client_secrets.json )

I also created the Client_Id and Client_secret using Google Console API and stored that data in the client_secrets.json file. (E.g https://github.com/youtube/api-samples/blob/master/dotnet/client_secrets.json)

我尝试在本地运行该函数,并将其粘贴: http://localhost:7071/api/Function1 在浏览器中,出现以下错误:

I try to run the function locally, pasting this: http://localhost:7071/api/Function1 in a browser, I am getting the following error:

400,这是一个错误.错误:redirect_rui_mismatch中的重定向URI 请求 http://localhost58085/authorize/与请求不匹配 授权给OAuth客户端.更新授权的重定向 URI,请访问. http://consolse.Developers.google.com/apis/credentials .. >

400, That's an error. Error: redirect_rui_mismatch The redirect URI in the request, http://localhost58085/authorize/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit. http://consolse.Developers.google.com/apis/credentials.

我不确定自己在做什么错,并且我不知道应该为授权重定向URI"输入什么URL

I am not sure what I am doing wrong, and I don't know what the URL I should put in for "Authorized redirect URIs"

代码:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Upload;
using Google.Apis.YouTube.v3.Data;
using System.Reflection;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using System.Threading;

namespace UploadVideo
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            log.LogInformation("YouTube Data API: Upload Video");
            log.LogInformation("==============================");

            try
            {
                await Run();
            }
            catch (AggregateException ex)
            {
                foreach (var e in ex.InnerExceptions)
                {
                    log.LogInformation("Error: " + e.Message);
                }
            }

            return new OkObjectResult($"Video Processed..");

        }

        private static async Task Run()
        {
            UserCredential credential;
            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows an application to upload files to the
                    // authenticated user's YouTube channel, but doesn't allow other types of access.
                    new[] { YouTubeService.Scope.YoutubeUpload },
                    "user",
                    CancellationToken.None
                );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
            });

            var video = new Video();
            video.Snippet = new VideoSnippet();
            video.Snippet.Title = "Default Video Title";
            video.Snippet.Description = "Default Video Description";
            video.Snippet.Tags = new string[] { "tag1", "tag2" };
            video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
            video.Status = new VideoStatus();
            video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
            var filePath = @"C:\Users\Peter\Desktop\audio\Test.mp4"; // Replace with path to actual movie file.

            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
                videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                await videosInsertRequest.UploadAsync();
            }
        }

        private static void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
        {
            switch (progress.Status)
            {
                case UploadStatus.Uploading:
                    Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                    break;

                case UploadStatus.Failed:
                    Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                    break;
            }
        }

        private static void videosInsertRequest_ResponseReceived(Video video)
        {
            Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
        }
    }
}

推荐答案

Oauth2的工作方式是向用户显示同意屏幕

The way Oauth2 works is that a user is presented with a consent screen

您是否要授予Peters出色的应用程序访问您的YouTube帐户的权限.

Do you want to grant Peters awesome application access to your YouTube account.

如果用户接受此请求,则在重定向uri时,授权代码将返回到您的应用程序

If the user accepts this then an Authorization code is returned to your application at the point of the redirect uri

http://localhost:7071/api/Function1

这是您应用程序中能够处理授权握手的文件.此重定向uri必须在Google开发者控制台中注册,这有助于确保没有人试图劫持您的授权呼叫并将其发送到他们的站点,然后他们将可以访问用户数据.

This is the file in your application that is able to handle the authorization handshake. This redirect uri must be registered in the Google developer console it helps to ensure that no one trys to hijack your authorization call and send it over to their site and then they will have access to the users data.

在凭据下找到您要寻找的

Under credentials find the one you are looking for

点击铅笔图标

请记住,GoogleWebAuthorizationBroker.AuthorizeAsync用于已安装的应用程序,如果您尝试将其设置为功能,它将在服务器上打开浏览器同意窗口.您需要为网络应用程序做更多类似的事情

Please remember that GoogleWebAuthorizationBroker.AuthorizeAsync is used for installed applications its going to open the browser consent window on the server if you try to put this up as a function. you need to do something more like this for a web application Asp.net mvc I cant claim to know a lot about azure functions but if there anything like cloud functions i dont think they have the ability to display a web browser page to your user. I dont think you can authenticate a user with Oauth2 from an azure function.

这篇关于错误:redirect_uri_mismatch Google API,如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆