GoogleWebAuthorizationBroker 无法从 IIS 主机工作

1 c# asp.net iis google-contacts-api google-oauth

我使用以下代码通过 Google .Net 客户端库向 Google 进行身份验证。

public static void auth()
{

string clientId = "xxxxxx.apps.googleusercontent.com";
string clientSecret = "xxxxx";


string[] scopes = new string[] { "https://www.googleapis.com/auth/contacts.readonly" };     // view your basic profile info.
try
{
    // Use the current Google .net client library to get the Oauth2 stuff.
    UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                 , scopes
                                                                                 , "test"
                                                                                 , CancellationToken.None
                                                                                 , new FileDataStore("test")).Result;

    // Translate the Oauth permissions to something the old client libray can read
    OAuth2Parameters parameters = new OAuth2Parameters();
    parameters.AccessToken = credential.Token.AccessToken;
    parameters.RefreshToken = credential.Token.RefreshToken;
    RunContactsSample(parameters);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Run Code Online (Sandbox Code Playgroud)

我正在使用我自己的客户端 ID 和客户端密钥。当我从 Visual Studio 运行时,此代码完美运行,但在 IIS 中托管后无法运行。

我在 google api 控制台中提到重定向的 URI 是 http://localhost/authorize/

我的 IIS 主机 URL 是 http://localhost/googleintegration.aspx

我在上个月面临这个问题,任何人都可以为此提供解决方案..

DaI*_*mTo 6

有几种不同类型的应用程序。您可以拥有 Web 应用程序、本地安装的应用程序或移动应用程序。用于验证这些的方法略有不同。

GoogleWebAuthorizationBroker.AuthorizeAsync 方法用于本地安装的应用程序。它将在运行代码的机器上打开浏览器窗口。在您在 Visual Studio 中运行它的实例中,它工作正常,但是一旦您尝试托管它,它就会尝试在无法工作的 Web 服务器上打开浏览器窗口。

您需要使用专为 Web 应用程序设计的 GoogleAuthorizationCodeFlow。您可以在此处找到示例。

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")
            });
Run Code Online (Sandbox Code Playgroud)