c# - 谷歌“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。我做错了什么吗?如何正确重定向到权限屏幕?
解决方案
重定向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; }
}
}
}
推荐阅读
- java - maven错误:在包中找不到符号类
- java - 如果我使用单独的 utils 类的静态方法添加 Firebase 事件侦听器,如何删除它们?
- python - Pandas DataFrame - 选择和索引
- python-3.x - RuntimeError: 请在创建新的 QApplication 实例之前销毁 QApplication 单例
- multithreading - 复制工作线程的字符串
- html - 构建 React/Spring Boot/MongoDB 应用程序
- typo3 - 将表单处理程序字段数据添加到主题
- flutter - 模拟器:错误:调整分区 e2fsck 的大小失败,退出代码为 1
- angular - 如何处理递归函数包含 observable?
- vba - 在 Excel 中使用动态范围而不使用命名范围