首页 > 解决方案 > 谷歌“GoogleWebAuthorizationBroker”显示错误重定向 uri 不匹配

问题描述

我在 MVC (C#) 中做这件事。我想访问用户谷歌日历,所以我指定了一个带有“访问日历”的按钮。当用户单击下面的按钮时,将调用代码以获取令牌(并保存)以访问日历数据。

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

当这个方法被执行时,我们应该被重定向到同意屏幕,相反,我得到的错误是如图所示

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

标签: c#oauth-2.0google-calendar-apigoogle-oauthgoogle-developers-console

解决方案


重定向uri问题

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

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

host:port/authorize

申请类型

您可以创建多种类型的客户端,这些客户端旨在与不同类型的应用程序一起使用。用于连接这些客户端的代码也不同。

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

已安装的应用程序

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

网络应用

您应该关注Web 应用程序并使用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; }
        }
    }
}

推荐阅读