如何通过OAuth2验证程序使用谷歌联系人API [英] How to use Google Contacts API via Oauth2 authentication

查看:476
本文介绍了如何通过OAuth2验证程序使用谷歌联系人API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样下面的代码来获得使用谷歌日历API( HTTPS日历条目:// developers.google.com/google-apps/calendar/ <​​/A>)它采用了OAuth2。
它运作良好。

 私人的IList<串GT;范围=新的List<串GT;(); 
私人CalendarService calendarService;

私人无效InitializeCalendarService()
{
//日历具体范围添加到列表范围
scopes.Add(CalendarService.Scopes.Calendar.GetStringValue() );

//显示头和初始化样本
CommandLine.EnableExceptionHandling();
CommandLine.DisplayGoogleSampleHeader(样品Google.Api.Calendar.v3」);

//创建认证
// FullClientCredentials凭证= PromptingClientCredentials.EnsureFullClientCredentials();
VAR提供商=新NativeApplicationClient(GoogleAuthenticationServer.Description);

FullClientCredentials证书=新FullClientCredentials();
credentials.ClientId =XYZ.apps.googleusercontent.com;
credentials.ClientSecret =XYZ;
credentials.ApiKey =XYZ;

provider.ClientIdentifier = credentials.ClientId;
provider.ClientSecret = credentials.ClientSecret;
OAuth2Authenticator< NativeApplicationClient> AUTH =新OAuth2Authenticator< NativeApplicationClient>(供应商,GetAuthorization);

//使用一个初始化实例
BaseClientService.Initializer初始化=新BaseClientService.Initializer()的日历服务;
initializer.Authenticator =权威性;
calendarService =新CalendarService(初始化);

CalendarList列表= calendarService.CalendarList.List()执行();
//做的名单东西..名单都好

}

公共IAuthorizationState GetAuthorization(NativeApplicationClient客户端)
{
//您应该使用这里存储密钥为
// .NET应用程序可以使用反射工具进行拆卸更安全的方式。
常量字符串存储=google.samples.dotnet.calendar;
常量字符串KEY =s0mekey; //检查

是否有可用缓存刷新令牌。
IAuthorizationState状态= AuthorizationMgr.GetCachedRefreshToken(存储,KEY);
如果((州= NULL)!)
{

{
client.RefreshToken(州);
返回状态;
//我们完成
}
赶上(DotNetOpenAuth.Messaging.ProtocolException前)
{
CommandLine.WriteError(使用不合格现有的刷新令牌:+ ex.Message);
CommandLine.WriteLine();
}
}

//从用户
串授权[]数组=新的字符串[scopes.Count]
scopes.CopyTo(数组,0);
=状态AuthorizationMgr.RequestNativeAuthorization(客户端,数组);
AuthorizationMgr.SetCachedRefreshToken(存储,KEY,状态);
返回状态;
}



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



我能够获取使用下面的代码联系,但它不是无密码,我需要得到它使用Oath2工作。下面的示例使用做为Gdata联系人API V2。我可以看到,我可以通过OAuth2Authenticator但林不完全知道如何做是正确的(我看不到在C#在谷歌网站上的任何有效的例子),并获取基于用户正在选择接入代码。
我不能看到如何使用OAuth2Authenticator与联系人API V3(
的https:/ /developers.google.com/google-apps/contacts/v3/

  RequestSettings rsLoginInfo =新RequestSettings( ,电子邮件,PWD); 
rsLoginInfo.AutoPaging = TRUE;
ContactsRequest cRequest =新ContactsRequest(rsLoginInfo);

//获取联系人列表
饲料和LT;联系与GT; feedContacts = cRequest.GetContacts();
的foreach(联系gmailAddresses在feedContacts.Entries)
{
//循环读取电子邮件地址
的foreach(电子邮件EMAILID在gmailAddresses.Emails)
{
lstContacts.Add(emailId.Address);
}
}


解决方案



如>

要生成网址

  RedirectURI =金塔:IETF:WG:OAuth的: 2.0:OOB

OAuth2Parameters参数=新OAuth2Parameters()
{
客户端Id =客户端ID,
clientSecret = clientSecret,
redirectUri = redirectUri,
SCOPE = requiredScope
};


//请求从用户授权(通过打开浏览器窗口):
字符串URL = OAuthUtil.CreateOAuth2AuthorizationUrl(参数);
变种loginUri =新的URI(URL);

//这种形式的浏览器控件
GoogleLoginForm形式=新GoogleLoginForm(loginUri,redirectUri);
无功博士= form.ShowDialog();

如果(DR == System.Windows.Forms.DialogResult.OK)
{
parameters.AccessCode = form.OAuthVerifierToken;
}



然后GoogleLoginForm:
我们有一个浏览器控件和注册browserControl_Navigated事件和做好以下。该DOCUMENTTITLE包含一个用于生成令牌AccessCode。

 私人无效GoogleLoginForm_Load(对象发件人,EventArgs五)
{
wbGoogleLogin.Url = _loginUri;
}

私人无效wbGoogleLogin_Navigated(对象发件人,WebBrowserNavigatedEventArgs E)
{
串=完整路径e.Url.ToString();
WebBrowser控件=发件人作为web浏览器;
如果(控制=空&安培;!&安培;!string.IsNullOrEmpty(control.DocumentTitle)及和放大器; control.DocumentTitle.Contains(成功密码))
{
_OAuthVerifierToken = control.DocumentTitle.Replace(成功密码=,);
的DialogResult = DialogResult.OK;
}
}

此方式,可在同一块进行代码,而无需编写某种复杂的回调服务读取访问令牌返回到我们的系统中。



不知道是什么原因日历API具有这种内置,和联系人API不。


I have this below code to get calendar entries using the google Calendar API (https://developers.google.com/google-apps/calendar/) which uses OAuth2. It works well.

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;
} 

How can I use the similar OAuth2Authenticator to fetch Contacts?

I am able to fetch contacts using the below code, but its not password-less, I need to get it working using Oath2. The example below uses Gdata contacts api v2. I can see that i can pass through OAuth2Authenticator but im not exactly sure how to do it correctly (i cant see any valid examples in C# on the google site) and fetch the access code based on what the user is selecting. I cant see how to use OAuth2Authenticator with the contacts 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);
        }
}

解决方案

I ended up doing this by fetching the access code by having a browser control read the Document title value when the user selects the google account and grants access.

eg:

To Generate URL

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;
}

Then In GoogleLoginForm : We have a browser control and registered browserControl_Navigated event and the do the below. The DocumentTitle contains the AccessCode which is used to generate the token.

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;
    }
}

This way it can be done in the same piece of code, without having to write a complicated callback service of some sort to read the access token back into our system.

Not exactly sure why the calendar api has this built in, and the contacts API doesn't.

这篇关于如何通过OAuth2验证程序使用谷歌联系人API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆