c# - 如何通过 Oauth2 身份验证使用 Google Contacts API

标签 c# .net google-api oauth-2.0

我有下面的代码,可以使用使用 OAuth2 的 google Calendar API ( https://developers.google.com/google-apps/calendar/ ) 获取日历条目。 它运作良好。

private IList<string> scopes = new List<string>();
private CalendarService calendarService;

private void InitializeCalendarService()
{
        // Add the calendar specific scope to the scopes list
        scopes.Add(CalendarService.Scopes.Calendar.GetStringValue());

        // Display the header and initialize the sample
        CommandLine.EnableExceptionHandling();
        CommandLine.DisplayGoogleSampleHeader("Google.Api.Calendar.v3 Sample");

        // Create the authenticator
        //FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials();
        var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);

        FullClientCredentials credentials = new FullClientCredentials();
        credentials.ClientId = "XYZ.apps.googleusercontent.com";
        credentials.ClientSecret = "XYZ";
        credentials.ApiKey = "XYZ";

        provider.ClientIdentifier = credentials.ClientId;
        provider.ClientSecret = credentials.ClientSecret;
        OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);

        // Create the calendar service using an initializer instance
        BaseClientService.Initializer initializer = new BaseClientService.Initializer();
        initializer.Authenticator = auth;
        calendarService = new CalendarService(initializer);

        CalendarList list = calendarService.CalendarList.List().Execute();
        // do something with the list .. the list is all good

} 

public IAuthorizationState GetAuthorization(NativeApplicationClient client)
{
        // You should use a more secure way of storing the key here as
        // .NET applications can be disassembled using a reflection tool.
        const string STORAGE = "google.samples.dotnet.calendar";
        const string KEY = "s0mekey";

        // Check if there is a cached refresh token available.
        IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY);
        if ((state != null))
        {
            try
            {
                client.RefreshToken(state);
                return state;
                // we are done
            }
            catch (DotNetOpenAuth.Messaging.ProtocolException ex)
            {
                CommandLine.WriteError("Using an existing refresh token failed: " + ex.Message);
                CommandLine.WriteLine();
            }
        }

        // Retrieve the authorization from the user
        string[] array = new string[scopes.Count];
        scopes.CopyTo(array,0);
        state = AuthorizationMgr.RequestNativeAuthorization(client, array);
        AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state);
        return state;
} 

如何使用类似的 OAuth2Authenticator 来获取联系人?

我可以使用下面的代码获取联系人,但它不是无密码的,我需要使用 Oath2 让它工作。下面的示例使用 Gdata contacts api v2。我可以看到我可以通过 OAuth2Authenticator,但我不确定如何正确地执行它(我在谷歌网站上看不到任何有效的 C# 示例)并根据用户选择的内容获取访问代码。 我看不到如何将 OAuth2Authenticator 与联系人 api v3 ( https://developers.google.com/google-apps/contacts/v3/ ) 一起使用

RequestSettings rsLoginInfo = new RequestSettings("", email,pwd);
rsLoginInfo.AutoPaging = true;
ContactsRequest cRequest = new ContactsRequest(rsLoginInfo);

// fetch contacts list
Feed<Contact> feedContacts = cRequest.GetContacts();
foreach (Contact gmailAddresses in feedContacts.Entries)
{
        // Looping to read  email addresses
        foreach (EMail emailId in gmailAddresses.Emails)
        {
           lstContacts.Add(emailId.Address);
        }
}

最佳答案

我最终通过在用户选择 Google 帐户并授予访问权限时让浏览器控件读取文档标题值来获取访问代码来完成此操作。

例如:

生成网址

RedirectURI = "urn:ietf:wg:oauth:2.0:oob"

OAuth2Parameters parameters = new OAuth2Parameters()
{
    ClientId = clientId,
    ClientSecret = clientSecret,
    RedirectUri = redirectUri,
    Scope = requiredScope
};


// Request authorization from the user (by opening a browser window):
string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
var loginUri = new Uri(url);

// This form has browser control
GoogleLoginForm form = new GoogleLoginForm(loginUri, redirectUri);
var dr = form.ShowDialog();

if (dr == System.Windows.Forms.DialogResult.OK)
{
    parameters.AccessCode = form.OAuthVerifierToken;
}

然后在 GoogleLoginForm 中: 我们有一个浏览器控件和注册的 browserControl_Navigated 事件,然后执行以下操作。 DocumentTitle 包含用于生成 token 的 AccessCode。

private void GoogleLoginForm_Load(object sender, EventArgs e)
{
   wbGoogleLogin.Url = _loginUri;
}

private void wbGoogleLogin_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
    string fullPath = e.Url.ToString();
    WebBrowser control = sender as WebBrowser;
    if (control != null &&  !string.IsNullOrEmpty(control.DocumentTitle) && control.DocumentTitle.Contains("Success code"))
    {
       _OAuthVerifierToken = control.DocumentTitle.Replace("Success code=","");
       DialogResult = DialogResult.OK;
    }
}

这样就可以在同一段代码中完成,而无需编写某种复杂的回调服务来将访问 token 读回我们的系统。

不确定为什么日历 API 内置了这个,而联系人 API 没有。

关于c# - 如何通过 Oauth2 身份验证使用 Google Contacts API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18264286/

相关文章:

c# - 更新包时如何防止nuget恢复到旧版本的依赖包

c# - 子串深度扫描

c# - 将隐含为派生程度较低的类型的对象放入派生程度较高的类型的列表中

c# - Linq to entities 无法识别我的实体类型

c# - 让 FluentValidation 调用具有多个参数的函数

javascript - 从 Google Fusion 表获取请求时遇到问题

javascript - 将 Google 可视化图表的多个实例放入一页、单独的 div 中

c# - Dispatcher.CurrentDispatcher.BeginInvoke 未调用

c# - 如何读取 ASP.NET NullReferenceException 消息中的堆栈跟踪

javascript - 在 Node js中获取谷歌日历事件ID