通过 .NET Web API 获取 Google 令牌,错误 redirect_uri_mismatch

Get Google token through .NET Web API, error redirect_uri_mismatch

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

这是我的代码:

[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?我花了好几个小时 google 解决这个问题,所有的答案都说我应该在我的 google 应用程序帐户中定义一些 URLs,我现在有:

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

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

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

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

这样做的原因是 Client ID for native application 允许来自所有位置的连接,因此即使 Visual studio 更改您的端口也没有关系。

对我来说,唯一有效的方法是为 TokenResponse 设置与 Credentials 相同的 url 参数。其他都没有用 - 我试过 'postmessage' 作为 url,然后 urls 对我网站上的一些其他操作,即使没有 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;