带有服务帐户或Web应用程序ID的Google Calendar API v3 .NET身份验证

时间:2015-03-11 08:05:16

标签: asp.net google-api google-calendar-api google-oauth google-api-dotnet-client

我需要在 .NET 4.5应用程序(VS 2013项目)上连接 Google日历。 我希望从日历中获取所有信息,例如:活动,日期,备注,姓名,来宾等......

我使用Google Developer Console创建了 Web应用程序客户端ID 服务帐户,但是我得到了不同的错误而没有结果。 我已经实现了两种不同的方法,一种是使用Web应用程序客户端ID登录,另一种是使用服务帐户。

这是常见的ASPX页面

public partial class Calendar : System.Web.UI.Page
{
    // client_secrets.json path.
    private readonly string GoogleOAuth2JsonPath = ConfigurationManager.AppSettings["GoogleOAuth2JsonPath"];

    // p12 certificate path.
    private readonly string GoogleOAuth2CertificatePath = ConfigurationManager.AppSettings["GoogleOAuth2CertificatePath"];

    // @developer... e-mail address.
    private readonly string GoogleOAuth2EmailAddress = ConfigurationManager.AppSettings["GoogleOAuth2EmailAddress"];

    // certificate password ("notasecret").
    private readonly string GoogleOAuth2PrivateKey = ConfigurationManager.AppSettings["GoogleOAuth2PrivateKey"];

    // my Google account e-mail address.
    private readonly string GoogleAccount = ConfigurationManager.AppSettings["GoogleAccount"]; 

    protected void Page_Load(object sender, EventArgs e)
    {
        // Enabled one at a time to test
        //GoogleLoginWithServiceAccount();
        GoogleLoginWithWebApplicationClientId();
    }
}

使用Web应用程序客户端ID

我已尝试为JSON配置文件配置重定向URI参数,但似乎没有URI可用。我在开发环境中,所以我在端口44300上使用IIS Express(启用了SSL)。我得到的错误是:

Error: redirect_uri_mismatch
Application: CalendarTest
The redirect URI in the request: http://localhost:56549/authorize/ did not match a registered redirect URI.
Request details
scope=https://www.googleapis.com/auth/calendar
response_type=code
redirect_uri=http://localhost:56549/authorize/
access_type=offline
client_id=....apps.googleusercontent

代码

private void GoogleLoginWithWebApplicationClientId()
{
    UserCredential credential;

    // This example uses the client_secrets.json file for authorization.
    // This file can be downloaded from the Google Developers Console
    // project.
    using (FileStream json = new FileStream(Server.MapPath(GoogleOAuth2JsonPath), FileMode.Open,
        FileAccess.Read))
    {
        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            GoogleClientSecrets.Load(json).Secrets,
            new[] { CalendarService.Scope.Calendar },
            "...@developer.gserviceaccount.com", CancellationToken.None,
            new FileDataStore("Calendar.Auth.Store")).Result;
    }

    // Create the service.
    CalendarService service = new CalendarService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "CalendarTest"
    });

    try
    {
        CalendarListResource.ListRequest listRequest = service.CalendarList.List();
        IList<CalendarListEntry> calendarList = listRequest.Execute().Items;

        foreach (CalendarListEntry entry in calendarList)
        {
            txtCalendarList.Text += "[" + entry.Summary + ". Location: " + entry.Location + ", TimeZone: " +
                                    entry.TimeZone + "] ";
        }
    }
    catch (TokenResponseException tre)
    {
        txtCalendarList.Text = tre.Message;
    }
}

使用服务帐户(首选)

我可以到达CalendarListResource.ListRequest listRequest = service.CalendarList.List();行,所以我猜登录有效,但是当我想要IList<CalendarListEntry> calendarList = listRequest.Execute().Items;上的列表时,我收到以下错误:

Error:"unauthorized_client", Description:"Unauthorized client or scope in request.", Uri:""

代码

private void GoogleLoginWithServiceAccount()
{
    /*
     * From https://developers.google.com/console/help/new/?hl=en_US#generatingoauth2:
     * The name of the downloaded private key is the key's thumbprint. When inspecting the key on your computer, or using the key in your application,
     * you need to provide the password "notasecret".
     * Note that while the password for all Google-issued private keys is the same (notasecret), each key is cryptographically unique.
     * GoogleOAuth2PrivateKey = "notasecret".
     */
    X509Certificate2 certificate = new X509Certificate2(Server.MapPath(GoogleOAuth2CertificatePath),
        GoogleOAuth2PrivateKey, X509KeyStorageFlags.Exportable);

    ServiceAccountCredential credential = new ServiceAccountCredential(
        new ServiceAccountCredential.Initializer(GoogleOAuth2EmailAddress)
        {
            User = GoogleAccount,
            Scopes = new[] { CalendarService.Scope.Calendar }
        }.FromCertificate(certificate));

    // Create the service.
    CalendarService service = new CalendarService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
        ApplicationName = "CalendarTest"
    });

    try
    {
        CalendarListResource.ListRequest listRequest = service.CalendarList.List();
        IList<CalendarListEntry> calendarList = listRequest.Execute().Items;

        foreach (CalendarListEntry entry in calendarList)
        {
            txtCalendarList.Text += "[" + entry.Summary + ". Location: " + entry.Location + ", TimeZone: " +
                                    entry.TimeZone + "] ";
        }
    }
    catch (TokenResponseException tre)
    {
        txtCalendarList.Text = tre.Message;
    }
}

我更喜欢服务帐户登录,因为用户无需使用同意屏幕登录,因为应用程序应在每次需要刷新时自行执行。可以使用带有免费Google帐户的服务帐户,还是需要管理员控制台?我已经阅读了许多相互矛盾的报道...

无论如何,在谷歌和StackOverflow中四处寻找,我都找不到解决方案。我已经看过并尝试过很多问题和解决方案,但没有结果。一些例子:

请帮忙! : - )

更新1 - 使用服务帐户(首选) - 已解决!

我的代码中唯一的问题是:

ServiceAccountCredential credential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(GoogleOAuth2EmailAddress)
    {
        //User = GoogleAccount,
        Scopes = new[] { CalendarService.Scope.Calendar }
    }.FromCertificate(certificate));

无需 User = GoogleAccount

1 个答案:

答案 0 :(得分:2)

您的身份验证肯定存在问题。以下是我的服务帐户身份验证方法的副本。

 /// <summary>
        /// Authenticating to Google using a Service account
        /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
        /// </summary>
        /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
        /// <param name="keyFilePath">Location of the Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
        /// <returns></returns>
        public static CalendarService AuthenticateServiceAccount(string serviceAccountEmail, string keyFilePath)
        {

            // check the file exists
            if (!File.Exists(keyFilePath))
            {
                Console.WriteLine("An Error occurred - Key file does not exist");
                return null;
            }

            string[] scopes = new string[] {
        CalendarService.Scope.Calendar  ,  // Manage your calendars
        CalendarService.Scope.CalendarReadonly    // View your Calendars
            };

            var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
            try
            {
                ServiceAccountCredential credential = new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer(serviceAccountEmail)
                    {
                        Scopes = scopes
                    }.FromCertificate(certificate));

                // Create the service.
                CalendarService service = new CalendarService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Calendar API Sample",
                });
                return service;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.InnerException);
                return null;

            }
        }

我也有一个教程。我的教程Google Calendar API Authentication with C#上面的代码直接从GitHub上的示例项目Google-Dotnet-Samples project中删除

注意/抬头:请记住,服务帐户不是您。它现在有任何日历,当你开始时,你需要创建一个日历并将其插入日历列表,然后才能获得任何结果。此外,您无法通过网络版Google日历查看此日历,因为您无法以服务帐户登录。最好的解决方法是让服务帐户授予您对日历的权限。