【发布时间】:2015-09-21 10:35:00
【问题描述】:
我正在尝试在我的非 MVC .NET Web 应用程序中使用Google Calendar API。 (这似乎是一个重要的区别。)
我尝试使用来自 Google 的 this example 和 Daimto 的 this example 的代码,以及一些来自 related posts here 的有用提示。
我写了如下方法:
public void GetUserCredential( String userName )
{
String clientId = ConfigurationManager.AppSettings[ "Google.ClientId" ]; //From Google Developer console https://console.developers.google.com
String clientSecret = ConfigurationManager.AppSettings[ "Google.ClientSecret" ]; //From Google Developer console https://console.developers.google.com
String[] scopes = new string[] {
Google.Apis.Calendar.v3.CalendarService.Scope.Calendar
};
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
}, scopes, userName, CancellationToken.None, new FileDataStore( "c:\\temp" ) ).Result;
// TODO: Replace FileDataStore with DatabaseDataStore
}
问题是,当调用 Google 的 OAuth2 页面时,redirect_uri 一直被设置为 http://localhost:<some-random-port>/authorize。我不知道如何将其设置为其他内容,如AuthorizeAsync 生成的以下示例 URL:
https://accounts.google.com/o/oauth2/auth?access_type=offline
&response_type=code
&client_id=********.apps.googleusercontent.com
&redirect_uri=http:%2F%2Flocalhost:40839%2Fauthorize%2F
&scope=https:%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar
Google 以 redirect_uri_mismatch 错误页面作为响应,其中包含以下消息:
“请求中的重定向 URI:http://localhost:XXXXX/authorize/ 与注册的重定向 URI 不匹配”
我只能在我的 Google Developer's Console Credentials 页面中注册这么多重定向 URI。我不倾向于注册 65535 端口,并且我想在我的网站上使用 /authorize 以外的页面。具体来说,我想在开发过程中使用http://localhost:888/Pages/GoogleApiRedirect,但除了我在开发者控制台中所做的之外,我不知道在哪里设置它。
如何显式设置redirect_uri 的值?我也愿意以“这种方法完全错误”的形式做出回应。
编辑:
在过去一天玩这个之后,我发现通过使用本地应用程序而不是 Web 应用程序的客户端 ID/客户端密钥,我至少可以访问 Google 的网络授权页面而不会抱怨redirect_uri_mismatch。这仍然是不可接受的,因为它仍然返回到http://localhost:<some-random-port>/authorize,这超出了我的 Web 应用程序的控制范围。
【问题讨论】:
-
您是否尝试过将 Visual Studio 配置为为您的 Web 应用项目使用预定义端口?检查此文档,以便您可以定义一个端口并在您的开发人员控制台中使用它。 msdn.microsoft.com/en-us/library/ms178109(v=vs.140).aspx
-
感谢@Gerardo 的建议。是的,它已经为端口 888 进行了预配置。我还尝试过 1024 以上的“非特权”端口。我在一些与我的情况相似的情况下看到了这个建议。如果它确实有效,我想我可以忍受
/authorize作为我的重定向页面。这不是一个理想的解决方案,但我可以接受。 -
您也可以尝试直接在 IIS 中部署项目,从那里您可以对 Web 应用程序的端口进行更多控制。 msdn.microsoft.com/en-us/library/vstudio/…
-
另一个好建议,@Gerardo。事情是,
redirect_uri只是一个 parameter 看在上帝的份上!为什么会被任意、不受控制地设置成原来的样子?我对完全缺乏关于这个问题的文档感到既惊讶又沮丧。这让我想知道,正如我在问题结束时提出的那样,我是否完全错误地处理了这个问题,我根本不应该使用AuthorizeAsync。 -
@Peter - 我已经在我的开发机器 (
localhost:888) 和我的测试机器beta.??????.com上进行了测试,下面的示例在两者上都运行良好。
标签: c# asp.net oauth-2.0 google-calendar-api