【问题标题】:Get Google token through .NET Web API, error redirect_uri_mismatch通过 .NET Web API 获取 Google 令牌,错误 redirect_uri_mismatch
【发布时间】:2015-05-03 12:37:20
【问题描述】:

我想通过谷歌登录验证用户,我从前端获取授权码,我想用它来换取谷歌的访问令牌。

这是我的代码:

[Route("google")]
public object Google(AuthModel model) {
    IAuthorizationCodeFlow flow =
    new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer {
        ClientSecrets = new ClientSecrets {
            ClientId = model.ClientId,
            ClientSecret = Constants.Constants.GOOGLE_SECRET
        },
        Scopes = new[] { "https://www.googleapis.com/auth/plus.login" }
    });
    var token = flow.ExchangeCodeForTokenAsync("", model.Code, "postmessage",
                    CancellationToken.None).Result;
    return token.AccessToken;
}

调用方法flow.ExchangeCodeForTokenAsync时出现错误

{"Error:\"redirect_uri_mismatch\", Description:\"\", Uri:\"\""}

我不明白,我可以在哪里定义重定向 URL?我花了几个小时在谷歌上搜索这个问题,答案都说我应该在我的谷歌应用程序帐户中定义一些 URL,我现在有:

Redirect URIs   
http://localhost:53906
http://localhost:53906/authcallback

【问题讨论】:

  • ExchangeCodeForTokenAsync的第三个参数应该是重定向URI,我不认为postmessage是你要使用的值。
  • 查看开发者控制台定义重定向 uri

标签: c# asp.net .net google-plus google-api-dotnet-client


【解决方案1】:

对我来说,唯一有效的方法是为 TokenResponse 设置与 Credentials 相同的 url 参数。没有其他工作 - 我尝试将“postmessage”作为 url,然后将 url 指向我网站上的其他一些操作,即使没有 url。没有任何效果。

当我输入与凭据相同的 url 时,它就像一个魅力。

代码:

ClientSecrets secrets = new ClientSecrets
{
ClientId = "***",
ClientSecret = "***"
};
IEnumerable<string> scopes = new[] { PlusService.Scope.UserinfoEmail, PlusService.Scope.UserinfoProfile };

IAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
     ClientSecrets = secrets,
     Scopes = scopes
});                               

TokenResponse token = flow.ExchangeCodeForTokenAsync("", code, 
"https://localhost:44388/TestLogin/Redirect", //This is the same url that I have for credentials
   CancellationToken.None).Result;

【讨论】:

    【解决方案2】:

    客户端库会自行检测您从何处发送请求。所以你不需要应用它。您通过Google Developer console 告诉 Google 您将使用哪些重定向 URI。看来你已经做到了。

    您的问题可能是 Visual Studio 有随机更改端口号的习惯。您可以在项目设置中解决此问题。

    转到 Google 开发者控制台。创建一个Client ID for native application 在本地主机上测试时使用此客户端 ID。一旦你发布到生产网站更改回Client ID for web application

    这个工作的原因是Client ID for native application 允许从所有位置进行连接,因此如果 Visual Studio 更改您的端口并不重要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-29
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      • 2014-12-05
      • 2014-12-04
      相关资源
      最近更新 更多