diff options
author | Andrew Arnott <andrewarnott@gmail.com> | 2013-02-20 22:28:51 -0800 |
---|---|---|
committer | Andrew Arnott <andrewarnott@gmail.com> | 2013-02-20 22:28:51 -0800 |
commit | 55cba0e1003cde651d0c65c7f7d8270393f65594 (patch) | |
tree | 26bc3a67a3bf608255b531baf4bb369b2a5d0943 | |
parent | 6d037a420c0d304bb2edeee17dce1b11db60b2bf (diff) | |
download | DotNetOpenAuth-55cba0e1003cde651d0c65c7f7d8270393f65594.zip DotNetOpenAuth-55cba0e1003cde651d0c65c7f7d8270393f65594.tar.gz DotNetOpenAuth-55cba0e1003cde651d0c65c7f7d8270393f65594.tar.bz2 |
Removes ConsumerBase.PrepareAuthorizedRequestAsync methods.
HttpClient, full steam ahead.
11 files changed, 126 insertions, 191 deletions
diff --git a/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs b/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs index 631b495..cd3c5fe 100644 --- a/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs +++ b/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs @@ -66,7 +66,7 @@ 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> /// The many specific authorization scopes Google offers. @@ -237,17 +237,16 @@ namespace DotNetOpenAuth.ApplicationBlock throw new ArgumentNullException("consumer"); } - var extraData = new Dictionary<string, string>() { - { "start-index", startIndex.ToString(CultureInfo.InvariantCulture) }, - { "max-results", maxResults.ToString(CultureInfo.InvariantCulture) }, - }; - var request = await consumer.PrepareAuthorizedRequestAsync(GetContactsEndpoint, accessToken, extraData, cancellationToken); - // Enable gzip compression. Google only compresses the response for recognized user agent headers. - Mike Lim var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip }; - 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 httpClient = consumer.Channel.HostFactories.CreateHttpClient(handler)) { + using (var httpClient = consumer.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); @@ -283,11 +282,10 @@ namespace DotNetOpenAuth.ApplicationBlock xw.Flush(); ms.Seek(0, SeekOrigin.Begin); - var request = await consumer.PrepareAuthorizedRequestAsync(new MessageReceivingEndpoint(feedUrl, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), accessToken, cancellationToken); + var request = new HttpRequestMessage(HttpMethod.Post, feedUrl); request.Content = new StreamContent(ms); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/atom+xml"); - request.Method = HttpMethod.Post; - using (var httpClient = consumer.Channel.HostFactories.CreateHttpClient()) { + using (var httpClient = consumer.CreateHttpClient(accessToken)) { using (var response = await httpClient.SendAsync(request, cancellationToken)) { if (response.StatusCode == HttpStatusCode.Created) { // Success diff --git a/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs b/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs index 1ae9f84..e665d96 100644 --- a/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs +++ b/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs @@ -55,18 +55,18 @@ namespace DotNetOpenAuth.ApplicationBlock { /// <summary> /// The URI to get a user's favorites. /// </summary> - private static readonly MessageReceivingEndpoint GetFavoritesEndpoint = new MessageReceivingEndpoint("http://twitter.com/favorites.xml", HttpDeliveryMethods.GetRequest); + private static readonly Uri GetFavoritesEndpoint = new Uri("http://twitter.com/favorites.xml"); /// <summary> /// The URI to get the data on the user's home page. /// </summary> - private static readonly MessageReceivingEndpoint GetFriendTimelineStatusEndpoint = new MessageReceivingEndpoint("https://api.twitter.com/1.1/statuses/home_timeline.json", HttpDeliveryMethods.GetRequest); + private static readonly Uri GetFriendTimelineStatusEndpoint = new Uri("https://api.twitter.com/1.1/statuses/home_timeline.json"); - private static readonly MessageReceivingEndpoint UpdateProfileBackgroundImageEndpoint = new MessageReceivingEndpoint("http://twitter.com/account/update_profile_background_image.xml", HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); + private static readonly Uri UpdateProfileBackgroundImageEndpoint = new Uri("http://twitter.com/account/update_profile_background_image.xml"); - private static readonly MessageReceivingEndpoint UpdateProfileImageEndpoint = new MessageReceivingEndpoint("http://twitter.com/account/update_profile_image.xml", HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); + private static readonly Uri UpdateProfileImageEndpoint = new Uri("http://twitter.com/account/update_profile_image.xml"); - private static readonly MessageReceivingEndpoint VerifyCredentialsEndpoint = new MessageReceivingEndpoint("http://api.twitter.com/1/account/verify_credentials.xml", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); + private static readonly Uri VerifyCredentialsEndpoint = new Uri("http://api.twitter.com/1/account/verify_credentials.xml"); /// <summary> /// The consumer used for the Sign in to Twitter feature. @@ -83,7 +83,7 @@ namespace DotNetOpenAuth.ApplicationBlock { /// </summary> static TwitterConsumer() { // Twitter can't handle the Expect 100 Continue HTTP header. - ServicePointManager.FindServicePoint(GetFavoritesEndpoint.Location).Expect100Continue = false; + ServicePointManager.FindServicePoint(GetFavoritesEndpoint).Expect100Continue = false; } /// <summary> @@ -136,7 +136,7 @@ namespace DotNetOpenAuth.ApplicationBlock { public static async Task<JArray> GetUpdatesAsync( ConsumerBase twitter, string accessToken, CancellationToken cancellationToken = default(CancellationToken)) { using (var httpClient = twitter.CreateHttpClient(accessToken)) { - using (var response = await httpClient.GetAsync(GetFriendTimelineStatusEndpoint.Location, cancellationToken)) { + using (var response = await httpClient.GetAsync(GetFriendTimelineStatusEndpoint, cancellationToken)) { response.EnsureSuccessStatusCode(); string jsonString = await response.Content.ReadAsStringAsync(); var json = JArray.Parse(jsonString); @@ -146,9 +146,9 @@ namespace DotNetOpenAuth.ApplicationBlock { } public static async Task<XDocument> GetFavorites(ConsumerBase twitter, string accessToken, CancellationToken cancellationToken = default(CancellationToken)) { - var request = await twitter.PrepareAuthorizedRequestAsync(GetFavoritesEndpoint, accessToken, cancellationToken); - using (var httpClient = twitter.Channel.HostFactories.CreateHttpClient()) { - using (HttpResponseMessage response = await httpClient.SendAsync(request)) { + using (var httpClient = twitter.CreateHttpClient(accessToken)) { + using (HttpResponseMessage response = await httpClient.GetAsync(GetFavoritesEndpoint, cancellationToken)) { + response.EnsureSuccessStatusCode(); return XDocument.Parse(await response.Content.ReadAsStringAsync()); } } @@ -157,14 +157,15 @@ namespace DotNetOpenAuth.ApplicationBlock { public static async Task<XDocument> UpdateProfileBackgroundImageAsync(ConsumerBase twitter, string accessToken, string image, bool tile, CancellationToken cancellationToken) { var imageAttachment = new StreamContent(File.OpenRead(image)); imageAttachment.Headers.ContentType = new MediaTypeHeaderValue("image/" + Path.GetExtension(image).Substring(1).ToLowerInvariant()); - var parts = new List<MultipartContentMember> { - new MultipartContentMember(imageAttachment, "image"), - new MultipartContentMember(new StringContent(tile.ToString().ToLowerInvariant()), "tile"), - }; - HttpRequestMessage request = await twitter.PrepareAuthorizedRequestAsync(UpdateProfileBackgroundImageEndpoint, accessToken, parts, cancellationToken); + HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, UpdateProfileBackgroundImageEndpoint); + var content = new MultipartFormDataContent(); + content.Add(imageAttachment, "image"); + content.Add(new StringContent(tile.ToString().ToLowerInvariant()), "tile"); + request.Content = content; request.Headers.ExpectContinue = false; - using (var httpClient = twitter.Channel.HostFactories.CreateHttpClient()) { - using (HttpResponseMessage response = await httpClient.SendAsync(request)) { + using (var httpClient = twitter.CreateHttpClient(accessToken)) { + using (HttpResponseMessage response = await httpClient.SendAsync(request, cancellationToken)) { + response.EnsureSuccessStatusCode(); string responseString = await response.Content.ReadAsStringAsync(); return XDocument.Parse(responseString); } @@ -179,13 +180,13 @@ namespace DotNetOpenAuth.ApplicationBlock { public static async Task<XDocument> UpdateProfileImageAsync(ConsumerBase twitter, string accessToken, Stream image, string contentType, CancellationToken cancellationToken = default(CancellationToken)) { var imageAttachment = new StreamContent(image); imageAttachment.Headers.ContentType = new MediaTypeHeaderValue(contentType); - var parts = new List<MultipartContentMember> { - new MultipartContentMember(imageAttachment, "image", "twitterPhoto"), - }; - - HttpRequestMessage request = await twitter.PrepareAuthorizedRequestAsync(UpdateProfileImageEndpoint, accessToken, parts, cancellationToken); - using (var httpClient = twitter.Channel.HostFactories.CreateHttpClient()) { - using (HttpResponseMessage response = await httpClient.SendAsync(request)) { + HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, UpdateProfileImageEndpoint); + var content = new MultipartFormDataContent(); + content.Add(imageAttachment, "image", "twitterPhoto"); + request.Content = content; + using (var httpClient = twitter.CreateHttpClient(accessToken)) { + using (HttpResponseMessage response = await httpClient.SendAsync(request, cancellationToken)) { + response.EnsureSuccessStatusCode(); string responseString = await response.Content.ReadAsStringAsync(); return XDocument.Parse(responseString); } @@ -193,9 +194,9 @@ namespace DotNetOpenAuth.ApplicationBlock { } public static async Task<XDocument> VerifyCredentialsAsync(ConsumerBase twitter, string accessToken, CancellationToken cancellationToken = default(CancellationToken)) { - var request = await twitter.PrepareAuthorizedRequestAsync(VerifyCredentialsEndpoint, accessToken, cancellationToken); - using (var httpClient = twitter.Channel.HostFactories.CreateHttpClient()) { - using (var response = await httpClient.SendAsync(request)) { + using (var httpClient = twitter.CreateHttpClient(accessToken)) { + using (var response = await httpClient.GetAsync(VerifyCredentialsEndpoint, cancellationToken)) { + response.EnsureSuccessStatusCode(); using (var stream = await response.Content.ReadAsStreamAsync()) { return XDocument.Load(XmlReader.Create(stream)); } diff --git a/samples/OAuthConsumer/GoogleApps2Legged.aspx.cs b/samples/OAuthConsumer/GoogleApps2Legged.aspx.cs index 2dfa8a2..af490cf 100644 --- a/samples/OAuthConsumer/GoogleApps2Legged.aspx.cs +++ b/samples/OAuthConsumer/GoogleApps2Legged.aspx.cs @@ -31,11 +31,8 @@ protected async void Page_Load(object sender, EventArgs e) { var google = new WebConsumer(GoogleConsumer.ServiceDescription, this.TokenManager); string accessToken = await google.RequestNewClientAccountAsync(cancellationToken: Response.ClientDisconnectedToken); - ////string tokenSecret = google.TokenManager.GetTokenSecret(accessToken); - MessageReceivingEndpoint ep = null; // set up your authorized call here. - var request = await google.PrepareAuthorizedRequestAsync(ep, accessToken, Response.ClientDisconnectedToken); - using (var httpClient = google.Channel.HostFactories.CreateHttpClient()) { - await httpClient.SendAsync(request); + using (var httpClient = google.CreateHttpClient(accessToken)) { + await httpClient.GetAsync("http://someUri", Response.ClientDisconnectedToken); } } } diff --git a/samples/OAuthConsumer/SampleWcf.aspx.cs b/samples/OAuthConsumer/SampleWcf.aspx.cs index d0f69f8..e01c485 100644 --- a/samples/OAuthConsumer/SampleWcf.aspx.cs +++ b/samples/OAuthConsumer/SampleWcf.aspx.cs @@ -4,6 +4,7 @@ using System.Globalization; using System.Linq; using System.Net; + using System.Net.Http; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Security; @@ -83,8 +84,13 @@ if (accessToken == null) { throw new InvalidOperationException("No access token!"); } - WebConsumer consumer = this.CreateConsumer(); - var httpRequest = await consumer.PrepareAuthorizedRequestAsync(serviceEndpoint, accessToken, Response.ClientDisconnectedToken); + + var httpRequest = new HttpRequestMessage(HttpMethod.Post, client.Endpoint.Address.Uri); + using (WebConsumer consumer = this.CreateConsumer()) { + using (var handler = consumer.CreateMessageHandler(accessToken)) { + handler.ApplyOAuthParameters(httpRequest); + } + } HttpRequestMessageProperty httpDetails = new HttpRequestMessageProperty(); httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers.Authorization.ToString(); diff --git a/samples/OAuthConsumerWpf/MainWindow.xaml.cs b/samples/OAuthConsumerWpf/MainWindow.xaml.cs index 07e127b..69d5dc5 100644 --- a/samples/OAuthConsumerWpf/MainWindow.xaml.cs +++ b/samples/OAuthConsumerWpf/MainWindow.xaml.cs @@ -137,9 +137,15 @@ private async void beginButton_Click(object sender, RoutedEventArgs e) { try { var service = new ServiceProviderDescription { - RequestTokenEndpoint = new MessageReceivingEndpoint(this.requestTokenUrlBox.Text, this.requestTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest), + RequestTokenEndpoint = + new MessageReceivingEndpoint( + this.requestTokenUrlBox.Text, + this.requestTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest), UserAuthorizationEndpoint = new MessageReceivingEndpoint(this.authorizeUrlBox.Text, HttpDeliveryMethods.GetRequest), - AccessTokenEndpoint = new MessageReceivingEndpoint(this.accessTokenUrlBox.Text, this.accessTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest), + AccessTokenEndpoint = + new MessageReceivingEndpoint( + this.accessTokenUrlBox.Text, + this.accessTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest), TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, ProtocolVersion = this.oauthVersion.SelectedIndex == 0 ? ProtocolVersion.V10 : ProtocolVersion.V10a, }; @@ -158,9 +164,7 @@ var authorizationResponse = await consumer.ProcessUserAuthorizationAsync(requestToken, null); accessToken = authorizationResponse.AccessToken; } else { - var authorizePopup = new Authorize( - consumer, - c => c.RequestUserAuthorizationAsync(null, null)); + var authorizePopup = new Authorize(consumer, c => c.RequestUserAuthorizationAsync(null, null)); authorizePopup.Owner = this; bool? result = authorizePopup.ShowDialog(); if (result.HasValue && result.Value) { @@ -169,15 +173,16 @@ return; } } - HttpDeliveryMethods resourceHttpMethod = this.resourceHttpMethodList.SelectedIndex < 2 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest; - if (this.resourceHttpMethodList.SelectedIndex == 1) { - resourceHttpMethod |= HttpDeliveryMethods.AuthorizationHeaderRequest; - } - var resourceEndpoint = new MessageReceivingEndpoint(this.resourceUrlBox.Text, resourceHttpMethod); - var request = await consumer.PrepareAuthorizedRequestAsync(resourceEndpoint, accessToken); - using (var httpClient = new HttpClient()) { - using (var resourceResponse = await httpClient.SendAsync(request)) { - this.resultsBox.Text = await resourceResponse.Content.ReadAsStringAsync(); + HttpMethod resourceHttpMethod = this.resourceHttpMethodList.SelectedIndex < 2 ? HttpMethod.Get : HttpMethod.Post; + using (var handler = consumer.CreateMessageHandler(accessToken)) { + handler.Location = this.resourceHttpMethodList.SelectedIndex == 1 + ? OAuth1HttpMessageHandlerBase.OAuthParametersLocation.AuthorizationHttpHeader + : OAuth1HttpMessageHandlerBase.OAuthParametersLocation.QueryString; + using (var httpClient = consumer.CreateHttpClient(handler)) { + var request = new HttpRequestMessage(resourceHttpMethod, this.resourceUrlBox.Text); + using (var resourceResponse = await httpClient.SendAsync(request)) { + this.resultsBox.Text = await resourceResponse.Content.ReadAsStringAsync(); + } } } } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth/DotNetOpenAuthWebConsumer.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth/DotNetOpenAuthWebConsumer.cs index d2449af..cc35b76 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth/DotNetOpenAuthWebConsumer.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth/DotNetOpenAuthWebConsumer.cs @@ -50,19 +50,23 @@ namespace DotNetOpenAuth.AspNet.Clients { #endregion + /// <summary> + /// Gets the DotNetOpenAuth <see cref="WebConsumer"/> instance that can be used to make OAuth 1.0 authorized HTTP requests. + /// </summary> + public WebConsumer Consumer { + get { return this.webConsumer; } + } + #region Public Methods and Operators /// <summary> - /// The prepare authorized request. + /// Creates an HTTP message handler that authorizes outgoing web requests. /// </summary> - /// <param name="profileEndpoint">The profile endpoint.</param> /// <param name="accessToken">The access token.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns> - /// An HTTP request. - /// </returns> - public Task<HttpRequestMessage> PrepareAuthorizedRequestAsync(MessageReceivingEndpoint profileEndpoint, string accessToken, CancellationToken cancellationToken = default(CancellationToken)) { - return this.webConsumer.PrepareAuthorizedRequestAsync(profileEndpoint, accessToken, cancellationToken); + public HttpMessageHandler CreateMessageHandler(string accessToken) { + Requires.NotNullOrEmpty(accessToken, "accessToken"); + + return this.Consumer.CreateMessageHandler(accessToken); } /// <summary> diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth/IOAuthWebWorker.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth/IOAuthWebWorker.cs index 205d4c0..7763add 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth/IOAuthWebWorker.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth/IOAuthWebWorker.cs @@ -14,21 +14,14 @@ namespace DotNetOpenAuth.AspNet.Clients { using DotNetOpenAuth.OAuth.Messages; /// <summary> - /// The io auth web worker. + /// The interface implemented by all OAuth web authentication modules in this assembly. /// </summary> public interface IOAuthWebWorker { - #region Public Methods and Operators - /// <summary> - /// The prepare authorized request. + /// Creates an HTTP message handler that authorizes outgoing web requests. /// </summary> - /// <param name="profileEndpoint">The profile endpoint.</param> /// <param name="accessToken">The access token.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns> - /// An HTTP request. - /// </returns> - Task<HttpRequestMessage> PrepareAuthorizedRequestAsync(MessageReceivingEndpoint profileEndpoint, string accessToken, CancellationToken cancellationToken = default(CancellationToken)); + HttpMessageHandler CreateMessageHandler(string accessToken); /// <summary> /// The process user authorization. @@ -46,7 +39,5 @@ namespace DotNetOpenAuth.AspNet.Clients { /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The response message</returns> Task<HttpResponseMessage> RequestAuthenticationAsync(Uri callback, CancellationToken cancellationToken = default(CancellationToken)); - - #endregion } } diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth/LinkedInClient.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth/LinkedInClient.cs index 8128cbb..7aa1dd4 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth/LinkedInClient.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth/LinkedInClient.cs @@ -95,12 +95,10 @@ namespace DotNetOpenAuth.AspNet.Clients { string accessToken = response.AccessToken; - var profileEndpoint = new MessageReceivingEndpoint(ProfileRequestUrl, HttpDeliveryMethods.GetRequest); - HttpRequestMessage request = await this.WebWorker.PrepareAuthorizedRequestAsync(profileEndpoint, accessToken, cancellationToken); - + var authorizingHandler = this.WebWorker.CreateMessageHandler(accessToken); try { - using (var httpClient = new HttpClient()) { - using (HttpResponseMessage profileResponse = await httpClient.SendAsync(request, cancellationToken)) { + using (var httpClient = new HttpClient(authorizingHandler)) { + using (HttpResponseMessage profileResponse = await httpClient.GetAsync(ProfileRequestUrl, cancellationToken)) { using (Stream responseStream = await profileResponse.Content.ReadAsStreamAsync()) { XDocument document = LoadXDocumentFromStream(responseStream); string userId = document.Root.Element("id").Value; diff --git a/src/DotNetOpenAuth.AspNet/Clients/OAuth/TwitterClient.cs b/src/DotNetOpenAuth.AspNet/Clients/OAuth/TwitterClient.cs index 3cfa36f..0f5e0db 100644 --- a/src/DotNetOpenAuth.AspNet/Clients/OAuth/TwitterClient.cs +++ b/src/DotNetOpenAuth.AspNet/Clients/OAuth/TwitterClient.cs @@ -96,14 +96,13 @@ namespace DotNetOpenAuth.AspNet.Clients { var profileRequestUrl = new Uri("https://api.twitter.com/1/users/show.xml?user_id=" + MessagingUtilities.EscapeUriDataStringRfc3986(userId)); - var profileEndpoint = new MessageReceivingEndpoint(profileRequestUrl, HttpDeliveryMethods.GetRequest); - HttpRequestMessage request = await this.WebWorker.PrepareAuthorizedRequestAsync(profileEndpoint, accessToken, cancellationToken); + var authorizingHandler = this.WebWorker.CreateMessageHandler(accessToken); var extraData = new Dictionary<string, string>(); extraData.Add("accesstoken", accessToken); try { - using (var httpClient = new HttpClient()) { - using (HttpResponseMessage profileResponse = await httpClient.SendAsync(request)) { + using (var httpClient = new HttpClient(authorizingHandler)) { + using (HttpResponseMessage profileResponse = await httpClient.GetAsync(profileRequestUrl, cancellationToken)) { using (Stream responseStream = await profileResponse.Content.ReadAsStreamAsync()) { XDocument document = LoadXDocumentFromStream(responseStream); extraData.AddDataIfNotEmpty(document, "name"); diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ConsumerBase.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ConsumerBase.cs index d72ad08..1bea2c5 100644 --- a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ConsumerBase.cs +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/ConsumerBase.cs @@ -111,6 +111,18 @@ namespace DotNetOpenAuth.OAuth { } /// <summary> + /// Creates the HTTP client. + /// </summary> + /// <param name="innerHandler">The inner handler that actually sends the HTTP message on the network.</param> + /// <returns>The HttpClient to use.</returns> + public HttpClient CreateHttpClient(OAuth1HttpMessageHandlerBase innerHandler) { + Requires.NotNull(innerHandler, "innerHandler"); + + var client = this.Channel.HostFactories.CreateHttpClient(innerHandler); + return client; + } + + /// <summary> /// Obtains an access token for a new account at the Service Provider via 2-legged OAuth. /// </summary> /// <param name="requestParameters">Any applicable parameters to include in the query string of the token request.</param> @@ -139,84 +151,6 @@ namespace DotNetOpenAuth.OAuth { return grantAccess.AccessToken; } - /// <summary> - /// Creates a web request prepared with OAuth authorization - /// that may be further tailored by adding parameters by the caller. - /// </summary> - /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param> - /// <param name="accessToken">The access token that permits access to the protected resource.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns>The initialized WebRequest object.</returns> - public Task<HttpRequestMessage> PrepareAuthorizedRequestAsync(MessageReceivingEndpoint endpoint, string accessToken, CancellationToken cancellationToken = default(CancellationToken)) { - Requires.NotNull(endpoint, "endpoint"); - Requires.NotNullOrEmpty(accessToken, "accessToken"); - - return this.PrepareAuthorizedRequestAsync(endpoint, accessToken, EmptyDictionary<string, string>.Instance, cancellationToken); - } - - /// <summary> - /// Creates a web request prepared with OAuth authorization - /// that may be further tailored by adding parameters by the caller. - /// </summary> - /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param> - /// <param name="accessToken">The access token that permits access to the protected resource.</param> - /// <param name="extraData">Extra parameters to include in the message. Must not be null, but may be empty.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns>The initialized WebRequest object.</returns> - public Task<HttpRequestMessage> PrepareAuthorizedRequestAsync(MessageReceivingEndpoint endpoint, string accessToken, IDictionary<string, string> extraData, CancellationToken cancellationToken = default(CancellationToken)) { - Requires.NotNull(endpoint, "endpoint"); - Requires.NotNullOrEmpty(accessToken, "accessToken"); - Requires.NotNull(extraData, "extraData"); - - IDirectedProtocolMessage message = this.CreateAuthorizingMessage(endpoint, accessToken); - foreach (var pair in extraData) { - message.ExtraData.Add(pair); - } - - return this.OAuthChannel.InitializeRequestAsync(message, cancellationToken); - } - - /// <summary> - /// Prepares an authorized request that carries an HTTP multi-part POST, allowing for binary data. - /// </summary> - /// <param name="endpoint">The URL and method on the Service Provider to send the request to.</param> - /// <param name="accessToken">The access token that permits access to the protected resource.</param> - /// <param name="binaryData">Extra parameters to include in the message. Must not be null, but may be empty.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns>The initialized WebRequest object.</returns> - public Task<HttpRequestMessage> PrepareAuthorizedRequestAsync(MessageReceivingEndpoint endpoint, string accessToken, IEnumerable<MultipartContentMember> binaryData, CancellationToken cancellationToken = default(CancellationToken)) { - Requires.NotNull(endpoint, "endpoint"); - Requires.NotNullOrEmpty(accessToken, "accessToken"); - Requires.NotNull(binaryData, "binaryData"); - - AccessProtectedResourceRequest message = this.CreateAuthorizingMessage(endpoint, accessToken); - message.BinaryData.AddRange(binaryData); - - return this.OAuthChannel.InitializeRequestAsync(message, cancellationToken); - } - - /// <summary> - /// Prepares an HTTP request that has OAuth authorization already attached to it. - /// </summary> - /// <param name="message">The OAuth authorization message to attach to the HTTP request.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns> - /// The HttpWebRequest that can be used to send the HTTP request to the remote service provider. - /// </returns> - /// <remarks> - /// If <see cref="IDirectedProtocolMessage.HttpMethods"/> property on the - /// <paramref name="message"/> has the - /// <see cref="HttpDeliveryMethods.AuthorizationHeaderRequest"/> flag set and - /// <see cref="ITamperResistantOAuthMessage.HttpMethod"/> is set to an HTTP method - /// that includes an entity body, the request stream is automatically sent - /// if and only if the <see cref="IMessage.ExtraData"/> dictionary is non-empty. - /// </remarks> - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Type of parameter forces the method to apply only to specific scenario.")] - public Task<HttpRequestMessage> PrepareAuthorizedRequestAsync(AccessProtectedResourceRequest message, CancellationToken cancellationToken = default(CancellationToken)) { - Requires.NotNull(message, "message"); - return this.OAuthChannel.InitializeRequestAsync(message, cancellationToken); - } - #region IDisposable Members /// <summary> diff --git a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1HttpMessageHandlerBase.cs b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1HttpMessageHandlerBase.cs index 6029d47..8a79adf 100644 --- a/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1HttpMessageHandlerBase.cs +++ b/src/DotNetOpenAuth.OAuth.Consumer/OAuth/OAuth1HttpMessageHandlerBase.cs @@ -128,6 +128,31 @@ namespace DotNetOpenAuth.OAuth { public int NonceLength { get; set; } /// <summary> + /// Applies OAuth authorization to the specified request. + /// This method is applied automatically to outbound requests that use this message handler instance. + /// However this method may be useful for obtaining the OAuth 1.0 signature without actually sending the request. + /// </summary> + public void ApplyOAuthParameters(HttpRequestMessage request) { + Requires.NotNull(request, "request"); + + var oauthParameters = this.GetOAuthParameters(); + string signature = this.GetSignature(request, oauthParameters); + oauthParameters.Add("oauth_signature", signature); + + // Add parameters and signature to request. + switch (this.Location) { + case OAuthParametersLocation.AuthorizationHttpHeader: + request.Headers.Authorization = new AuthenticationHeaderValue(Protocol.AuthorizationHeaderScheme, MessagingUtilities.AssembleAuthorizationHeader(oauthParameters.AsKeyValuePairs())); + break; + case OAuthParametersLocation.QueryString: + var uriBuilder = new UriBuilder(request.RequestUri); + uriBuilder.AppendQueryArgs(oauthParameters.AsKeyValuePairs()); + request.RequestUri = uriBuilder.Uri; + break; + } + } + + /// <summary> /// Sends an HTTP request to the inner handler to send to the server as an asynchronous operation. /// </summary> /// <param name="request">The HTTP request message to send to the server.</param> @@ -311,29 +336,6 @@ namespace DotNetOpenAuth.OAuth { } /// <summary> - /// Applies OAuth authorization to the specified request. - /// </summary> - private void ApplyOAuthParameters(HttpRequestMessage request) { - Requires.NotNull(request, "request"); - - var oauthParameters = this.GetOAuthParameters(); - string signature = this.GetSignature(request, oauthParameters); - oauthParameters.Add("oauth_signature", signature); - - // Add parameters and signature to request. - switch (this.Location) { - case OAuthParametersLocation.AuthorizationHttpHeader: - request.Headers.Authorization = new AuthenticationHeaderValue(Protocol.AuthorizationHeaderScheme, MessagingUtilities.AssembleAuthorizationHeader(oauthParameters.AsKeyValuePairs())); - break; - case OAuthParametersLocation.QueryString: - var uriBuilder = new UriBuilder(request.RequestUri); - uriBuilder.AppendQueryArgs(oauthParameters.AsKeyValuePairs()); - request.RequestUri = uriBuilder.Uri; - break; - } - } - - /// <summary> /// Gets the OAuth 1.0 signature to apply to the specified request. /// </summary> /// <param name="request">The outbound HTTP request.</param> |