summaryrefslogtreecommitdiffstats
path: root/samples/DotNetOpenAuth.ApplicationBlock/OAuth1/GoogleConsumer.cs
diff options
context:
space:
mode:
Diffstat (limited to 'samples/DotNetOpenAuth.ApplicationBlock/OAuth1/GoogleConsumer.cs')
-rw-r--r--samples/DotNetOpenAuth.ApplicationBlock/OAuth1/GoogleConsumer.cs162
1 files changed, 69 insertions, 93 deletions
diff --git a/samples/DotNetOpenAuth.ApplicationBlock/OAuth1/GoogleConsumer.cs b/samples/DotNetOpenAuth.ApplicationBlock/OAuth1/GoogleConsumer.cs
index 1bdb04d..a7c062e 100644
--- a/samples/DotNetOpenAuth.ApplicationBlock/OAuth1/GoogleConsumer.cs
+++ b/samples/DotNetOpenAuth.ApplicationBlock/OAuth1/GoogleConsumer.cs
@@ -7,14 +7,20 @@
namespace DotNetOpenAuth.ApplicationBlock {
using System;
using System.Collections.Generic;
+ using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
+ using System.Net.Http;
+ using System.Net.Http.Headers;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
+ using System.Threading;
+ using System.Threading.Tasks;
+ using System.Web;
using System.Xml;
using System.Xml.Linq;
using DotNetOpenAuth.Messaging;
@@ -24,16 +30,15 @@ namespace DotNetOpenAuth.ApplicationBlock {
/// <summary>
/// A consumer capable of communicating with Google Data APIs.
/// </summary>
- public static class GoogleConsumer {
+ public class GoogleConsumer : Consumer {
/// <summary>
/// The Consumer to use for accessing Google data APIs.
/// </summary>
- public static readonly ServiceProviderDescription ServiceDescription = new ServiceProviderDescription {
- RequestTokenEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest),
- UserAuthorizationEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthAuthorizeToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest),
- AccessTokenEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetAccessToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest),
- TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
- };
+ public static readonly ServiceProviderDescription ServiceDescription =
+ new ServiceProviderDescription(
+ "https://www.google.com/accounts/OAuthGetRequestToken",
+ "https://www.google.com/accounts/OAuthAuthorizeToken",
+ "https://www.google.com/accounts/OAuthGetAccessToken");
/// <summary>
/// A mapping between Google's applications and their URI scope values.
@@ -60,7 +65,19 @@ namespace DotNetOpenAuth.ApplicationBlock {
/// <summary>
/// The URI to get contacts once authorization is granted.
/// </summary>
- private static readonly MessageReceivingEndpoint GetContactsEndpoint = new MessageReceivingEndpoint("http://www.google.com/m8/feeds/contacts/default/full/", HttpDeliveryMethods.GetRequest);
+ private static readonly Uri GetContactsEndpoint = new Uri("http://www.google.com/m8/feeds/contacts/default/full/");
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GoogleConsumer"/> class.
+ /// </summary>
+ public GoogleConsumer() {
+ this.ServiceProvider = ServiceDescription;
+ this.ConsumerKey = ConfigurationManager.AppSettings["googleConsumerKey"];
+ this.ConsumerSecret = ConfigurationManager.AppSettings["googleConsumerSecret"];
+ this.TemporaryCredentialStorage = HttpContext.Current != null
+ ? (ITemporaryCredentialStorage)new CookieTemporaryCredentialStorage()
+ : new MemoryTemporaryCredentialStorage();
+ }
/// <summary>
/// The many specific authorization scopes Google offers.
@@ -149,91 +166,60 @@ namespace DotNetOpenAuth.ApplicationBlock {
}
/// <summary>
- /// The service description to use for accessing Google data APIs using an X509 certificate.
+ /// Gets the scope URI in Google's format.
/// </summary>
- /// <param name="signingCertificate">The signing certificate.</param>
- /// <returns>A service description that can be used to create an instance of
- /// <see cref="DesktopConsumer"/> or <see cref="WebConsumer"/>. </returns>
- public static ServiceProviderDescription CreateRsaSha1ServiceDescription(X509Certificate2 signingCertificate) {
- if (signingCertificate == null) {
- throw new ArgumentNullException("signingCertificate");
- }
-
- return new ServiceProviderDescription {
- RequestTokenEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest),
- UserAuthorizationEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthAuthorizeToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest),
- AccessTokenEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetAccessToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest),
- TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new RsaSha1ConsumerSigningBindingElement(signingCertificate) },
- };
+ /// <param name="scope">The scope, which may include one or several Google applications.</param>
+ /// <returns>A space-delimited list of URIs for the requested Google applications.</returns>
+ public static string GetScopeUri(Applications scope) {
+ return string.Join(" ", Util.GetIndividualFlags(scope).Select(app => DataScopeUris[(Applications)app]).ToArray());
}
/// <summary>
/// Requests authorization from Google to access data from a set of Google applications.
/// </summary>
- /// <param name="consumer">The Google consumer previously constructed using <see cref="CreateWebConsumer"/> or <see cref="CreateDesktopConsumer"/>.</param>
/// <param name="requestedAccessScope">The requested access scope.</param>
- public static void RequestAuthorization(WebConsumer consumer, Applications requestedAccessScope) {
- if (consumer == null) {
- throw new ArgumentNullException("consumer");
- }
-
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>
+ /// A task that completes with the asynchronous operation.
+ /// </returns>
+ public Task<Uri> RequestUserAuthorizationAsync(Applications requestedAccessScope, CancellationToken cancellationToken = default(CancellationToken)) {
var extraParameters = new Dictionary<string, string> {
{ "scope", GetScopeUri(requestedAccessScope) },
};
Uri callback = Util.GetCallbackUrlFromContext();
- var request = consumer.PrepareRequestUserAuthorization(callback, extraParameters, null);
- consumer.Channel.Send(request);
- }
-
- /// <summary>
- /// Requests authorization from Google to access data from a set of Google applications.
- /// </summary>
- /// <param name="consumer">The Google consumer previously constructed using <see cref="CreateWebConsumer"/> or <see cref="CreateDesktopConsumer"/>.</param>
- /// <param name="requestedAccessScope">The requested access scope.</param>
- /// <param name="requestToken">The unauthorized request token assigned by Google.</param>
- /// <returns>The request token</returns>
- public static Uri RequestAuthorization(DesktopConsumer consumer, Applications requestedAccessScope, out string requestToken) {
- if (consumer == null) {
- throw new ArgumentNullException("consumer");
- }
-
- var extraParameters = new Dictionary<string, string> {
- { "scope", GetScopeUri(requestedAccessScope) },
- };
-
- return consumer.RequestUserAuthorization(extraParameters, null, out requestToken);
+ return this.RequestUserAuthorizationAsync(callback, extraParameters, cancellationToken);
}
/// <summary>
/// Gets the Gmail address book's contents.
/// </summary>
- /// <param name="consumer">The Google consumer.</param>
/// <param name="accessToken">The access token previously retrieved.</param>
/// <param name="maxResults">The maximum number of entries to return. If you want to receive all of the contacts, rather than only the default maximum, you can specify a very large number here.</param>
/// <param name="startIndex">The 1-based index of the first result to be retrieved (for paging).</param>
- /// <returns>An XML document returned by Google.</returns>
- public static XDocument GetContacts(ConsumerBase consumer, string accessToken, int maxResults/* = 25*/, int startIndex/* = 1*/) {
- if (consumer == null) {
- throw new ArgumentNullException("consumer");
- }
-
- var extraData = new Dictionary<string, string>() {
- { "start-index", startIndex.ToString(CultureInfo.InvariantCulture) },
- { "max-results", maxResults.ToString(CultureInfo.InvariantCulture) },
- };
- var request = consumer.PrepareAuthorizedRequest(GetContactsEndpoint, accessToken, extraData);
-
+ /// <param name="cancellationToken">The cancellation token.</param>
+ /// <returns>
+ /// An XML document returned by Google.
+ /// </returns>
+ public async Task<XDocument> GetContactsAsync(AccessToken accessToken, int maxResults = 25, int startIndex = 1, CancellationToken cancellationToken = default(CancellationToken)) {
// Enable gzip compression. Google only compresses the response for recognized user agent headers. - Mike Lim
- request.AutomaticDecompression = DecompressionMethods.GZip;
- request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.151 Safari/534.16";
-
- var response = consumer.Channel.WebRequestHandler.GetResponse(request);
- string body = response.GetResponseReader().ReadToEnd();
- XDocument result = XDocument.Parse(body);
- return result;
+ var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip };
+ using (var httpClient = this.CreateHttpClient(accessToken, handler)) {
+ var request = new HttpRequestMessage(HttpMethod.Get, GetContactsEndpoint);
+ request.Content = new FormUrlEncodedContent(
+ new Dictionary<string, string>() {
+ { "start-index", startIndex.ToString(CultureInfo.InvariantCulture) },
+ { "max-results", maxResults.ToString(CultureInfo.InvariantCulture) },
+ });
+ request.Headers.UserAgent.Add(ProductInfoHeaderValue.Parse("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.151 Safari/534.16"));
+ using (var response = await httpClient.SendAsync(request, cancellationToken)) {
+ string body = await response.Content.ReadAsStringAsync();
+ XDocument result = XDocument.Parse(body);
+ return result;
+ }
+ }
}
- public static void PostBlogEntry(ConsumerBase consumer, string accessToken, string blogUrl, string title, XElement body) {
+ public async Task PostBlogEntryAsync(AccessToken accessToken, string blogUrl, string title, XElement body, CancellationToken cancellationToken = default(CancellationToken)) {
string feedUrl;
var getBlogHome = WebRequest.Create(blogUrl);
using (var blogHomeResponse = getBlogHome.GetResponse()) {
@@ -258,31 +244,21 @@ namespace DotNetOpenAuth.ApplicationBlock {
XmlWriter xw = XmlWriter.Create(ms, xws);
entry.WriteTo(xw);
xw.Flush();
-
- WebRequest request = consumer.PrepareAuthorizedRequest(new MessageReceivingEndpoint(feedUrl, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), accessToken);
- request.ContentType = "application/atom+xml";
- request.Method = "POST";
- request.ContentLength = ms.Length;
ms.Seek(0, SeekOrigin.Begin);
- using (Stream requestStream = request.GetRequestStream()) {
- ms.CopyTo(requestStream);
- }
- using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
- if (response.StatusCode == HttpStatusCode.Created) {
- // Success
- } else {
- // Error!
+
+ var request = new HttpRequestMessage(HttpMethod.Post, feedUrl);
+ request.Content = new StreamContent(ms);
+ request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/atom+xml");
+ using (var httpClient = this.CreateHttpClient(accessToken)) {
+ using (var response = await httpClient.SendAsync(request, cancellationToken)) {
+ if (response.StatusCode == HttpStatusCode.Created) {
+ // Success
+ } else {
+ // Error!
+ response.EnsureSuccessStatusCode(); // throw some meaningful exception.
+ }
}
}
}
-
- /// <summary>
- /// Gets the scope URI in Google's format.
- /// </summary>
- /// <param name="scope">The scope, which may include one or several Google applications.</param>
- /// <returns>A space-delimited list of URIs for the requested Google applications.</returns>
- public static string GetScopeUri(Applications scope) {
- return string.Join(" ", Util.GetIndividualFlags(scope).Select(app => DataScopeUris[(Applications)app]).ToArray());
- }
}
}