Google "GoogleWebAuthorizationBroker" 显示错误重定向 uri 不匹配

Google "GoogleWebAuthorizationBroker" showing error redirect uri mismatch

我正在 MVC (C#) 中执行此操作。我想访问用户 google 日历,所以我用 "Access Calendar" 指定了一个按钮。当用户单击下面的按钮时,将调用代码以获取令牌(并保存)以访问日历数据。

 UserCredential credential;
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    new ClientSecrets
                    {
                        ClientId = "xxxxxx.apps.googleusercontent.com",
                        ClientSecret = "FxxxxxxxxxZ"
                    },
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath)).Result;

当执行此方法时,我们应该被重定向到同意屏幕,相反,我收到错误

但它显示的重定向 URI 我从未在控制台中指定过。这些是我在 google 项目控制台中指定的重定向 uri。 我做错了什么吗?如何正确重定向到权限屏幕?

重定向 uri 问题

您请求中的重定向 uri 是 http://127.0.1:59693/authorize 您没有在授权重定向 Uris 下添加它。

您不能只添加任何重定向 uri。客户端库自己构建这个 url。它总是

host:port/authorize

应用类型

您可以创建多种类型的客户端,这些客户端设计用于不同类型的应用程序。用于连接这些客户端的代码也不同。

  • 已安装的应用程序 - 安装在用户机器上的应用程序
  • Web 应用程序 - 托管在通过 Web 浏览器连接到用户的 Web 服务器中的应用程序。

已安装的应用程序

您正在使用 GoogleWebAuthorizationBroker.AuthorizeAsync 它专为与已安装的应用程序一起使用而设计。浏览器 window 将在机器本身上打开。如果您尝试将其托管在网络服务器上,浏览器将尝试在服务器上打开,但不会显示给用户。

Web 应用程序

您应该关注 Web applications 并使用 GoogleAuthorizationCodeFlow

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