2013-08-16 102 views
4

我有以下代碼可以使用使用OAuth2的Google日曆API(https://developers.google.com/google-apps/calendar/)獲取日曆條目。 它運作良好。如何通過Oauth2身份驗證使用Google Contacts API

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,但我不完全知道如何正確地做到這一點(我無法在Google網站上看到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); 
     } 
} 
+0

在正確方向的'點'評論:http://stackoverflow.com/questions/8897072/google-contacts-api-after-getting-the-access-token-oauth –

回答

4

我結束了通過由具有瀏覽器控制讀取存取碼這樣讀取的原稿標題值當用戶選擇Google帳戶並授予訪問權限。

如:

來生成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; 
} 

然後在GoogleLoginForm: 我們有一個瀏覽器控件並註冊browserControl_Navigated事件和做好以下。 DocumentTitle包含用於生成令牌的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; 
    } 
} 

這樣它可以在同一段代碼來完成,而無需編寫了某種複雜的回調服務讀取訪問令牌返回到我們的系統中。

不完全確定爲什麼日曆api有內置的,而聯繫人API沒有。

2

首先,快速解答您的問題。我相信IAuthorizationState與OAuth2Parameters具有相似的屬性。因此,你應該能夠做到這一點(它與你有壓延代碼合併):

OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); 

//This will call your GetAuthorization method 
auth.LoadAccessToken() 
RequestSettings settings = new RequestSettings("appName", auth.State.AccessToken); 
ContactsRequest cRequest = new ContactsRequest(settings); 

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

這應該作爲RequestSettings允許你指定一個訪問令牌。話雖這麼說,我本人更喜歡使用:

var parameters = new OAuth2Parameters() 
{ 
    //Client 
    ClientId = CLIENT_ID, 
    ClientSecret = CLIENT_SECRET, 
    RedirectUri = redirectUri, 
    Scope = "https://www.google.com/m8/feeds", 
    ResponseType = "code" 
}; 

//User clicks this auth url and will then be sent to your redirect url with a code parameter 
var authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters); 
. 
. 
. 
//using the code parameter 
parameters.AccessCode = code; 
OAuthUtil.GetAccessToken(parameters); 
var settings = new RequestSettings(applicationName, parameters); 
var cr = new ContactsRequest(settings); 
//Now you can use contacts as you would have before 

雖然,香港專業教育學院只用Web服務器應用程序測試了這個,所以也許需要適合自己情況的認證?我發現方便的這些源代碼:

OAuth2Demo

IAuthorizationState

OAuth2Authenticator

+1

這是正確的,但這不does not獲取訪問代碼。我想知道是否有方法可以輕鬆地在同一段代碼中獲取訪問代碼。 – Marty

相關問題