Skip to content
This repository was archived by the owner on Mar 20, 2019. It is now read-only.

Commit 55cba0e

Browse files
committed
Removes ConsumerBase.PrepareAuthorizedRequestAsync methods.
HttpClient, full steam ahead.
1 parent 6d037a4 commit 55cba0e

11 files changed

Lines changed: 126 additions & 191 deletions

File tree

samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ public static class GoogleConsumer
6666
/// <summary>
6767
/// The URI to get contacts once authorization is granted.
6868
/// </summary>
69-
private static readonly MessageReceivingEndpoint GetContactsEndpoint = new MessageReceivingEndpoint("http://www.google.com/m8/feeds/contacts/default/full/", HttpDeliveryMethods.GetRequest);
69+
private static readonly Uri GetContactsEndpoint = new Uri("http://www.google.com/m8/feeds/contacts/default/full/");
7070

7171
/// <summary>
7272
/// The many specific authorization scopes Google offers.
@@ -237,17 +237,16 @@ public static ServiceProviderDescription CreateRsaSha1ServiceDescription(X509Cer
237237
throw new ArgumentNullException("consumer");
238238
}
239239

240-
var extraData = new Dictionary<string, string>() {
241-
{ "start-index", startIndex.ToString(CultureInfo.InvariantCulture) },
242-
{ "max-results", maxResults.ToString(CultureInfo.InvariantCulture) },
243-
};
244-
var request = await consumer.PrepareAuthorizedRequestAsync(GetContactsEndpoint, accessToken, extraData, cancellationToken);
245-
246240
// Enable gzip compression. Google only compresses the response for recognized user agent headers. - Mike Lim
247241
var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip };
248-
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"));
249-
250-
using (var httpClient = consumer.Channel.HostFactories.CreateHttpClient(handler)) {
242+
using (var httpClient = consumer.CreateHttpClient(accessToken, handler)) {
243+
var request = new HttpRequestMessage(HttpMethod.Get, GetContactsEndpoint);
244+
request.Content = new FormUrlEncodedContent(
245+
new Dictionary<string, string>() {
246+
{ "start-index", startIndex.ToString(CultureInfo.InvariantCulture) },
247+
{ "max-results", maxResults.ToString(CultureInfo.InvariantCulture) },
248+
});
249+
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"));
251250
using (var response = await httpClient.SendAsync(request, cancellationToken)) {
252251
string body = await response.Content.ReadAsStringAsync();
253252
XDocument result = XDocument.Parse(body);
@@ -283,11 +282,10 @@ public static async Task PostBlogEntryAsync(ConsumerBase consumer, string access
283282
xw.Flush();
284283
ms.Seek(0, SeekOrigin.Begin);
285284

286-
var request = await consumer.PrepareAuthorizedRequestAsync(new MessageReceivingEndpoint(feedUrl, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), accessToken, cancellationToken);
285+
var request = new HttpRequestMessage(HttpMethod.Post, feedUrl);
287286
request.Content = new StreamContent(ms);
288287
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/atom+xml");
289-
request.Method = HttpMethod.Post;
290-
using (var httpClient = consumer.Channel.HostFactories.CreateHttpClient()) {
288+
using (var httpClient = consumer.CreateHttpClient(accessToken)) {
291289
using (var response = await httpClient.SendAsync(request, cancellationToken)) {
292290
if (response.StatusCode == HttpStatusCode.Created) {
293291
// Success

samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs

Lines changed: 28 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -55,18 +55,18 @@ public static class TwitterConsumer {
5555
/// <summary>
5656
/// The URI to get a user's favorites.
5757
/// </summary>
58-
private static readonly MessageReceivingEndpoint GetFavoritesEndpoint = new MessageReceivingEndpoint("http://twitter.com/favorites.xml", HttpDeliveryMethods.GetRequest);
58+
private static readonly Uri GetFavoritesEndpoint = new Uri("http://twitter.com/favorites.xml");
5959

6060
/// <summary>
6161
/// The URI to get the data on the user's home page.
6262
/// </summary>
63-
private static readonly MessageReceivingEndpoint GetFriendTimelineStatusEndpoint = new MessageReceivingEndpoint("https://api.twitter.com/1.1/statuses/home_timeline.json", HttpDeliveryMethods.GetRequest);
63+
private static readonly Uri GetFriendTimelineStatusEndpoint = new Uri("https://api.twitter.com/1.1/statuses/home_timeline.json");
6464

65-
private static readonly MessageReceivingEndpoint UpdateProfileBackgroundImageEndpoint = new MessageReceivingEndpoint("http://twitter.com/account/update_profile_background_image.xml", HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
65+
private static readonly Uri UpdateProfileBackgroundImageEndpoint = new Uri("http://twitter.com/account/update_profile_background_image.xml");
6666

67-
private static readonly MessageReceivingEndpoint UpdateProfileImageEndpoint = new MessageReceivingEndpoint("http://twitter.com/account/update_profile_image.xml", HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
67+
private static readonly Uri UpdateProfileImageEndpoint = new Uri("http://twitter.com/account/update_profile_image.xml");
6868

69-
private static readonly MessageReceivingEndpoint VerifyCredentialsEndpoint = new MessageReceivingEndpoint("http://api.twitter.com/1/account/verify_credentials.xml", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
69+
private static readonly Uri VerifyCredentialsEndpoint = new Uri("http://api.twitter.com/1/account/verify_credentials.xml");
7070

7171
/// <summary>
7272
/// The consumer used for the Sign in to Twitter feature.
@@ -83,7 +83,7 @@ public static class TwitterConsumer {
8383
/// </summary>
8484
static TwitterConsumer() {
8585
// Twitter can't handle the Expect 100 Continue HTTP header.
86-
ServicePointManager.FindServicePoint(GetFavoritesEndpoint.Location).Expect100Continue = false;
86+
ServicePointManager.FindServicePoint(GetFavoritesEndpoint).Expect100Continue = false;
8787
}
8888

8989
/// <summary>
@@ -136,7 +136,7 @@ private static InMemoryTokenManager ShortTermUserSessionTokenManager {
136136
public static async Task<JArray> GetUpdatesAsync(
137137
ConsumerBase twitter, string accessToken, CancellationToken cancellationToken = default(CancellationToken)) {
138138
using (var httpClient = twitter.CreateHttpClient(accessToken)) {
139-
using (var response = await httpClient.GetAsync(GetFriendTimelineStatusEndpoint.Location, cancellationToken)) {
139+
using (var response = await httpClient.GetAsync(GetFriendTimelineStatusEndpoint, cancellationToken)) {
140140
response.EnsureSuccessStatusCode();
141141
string jsonString = await response.Content.ReadAsStringAsync();
142142
var json = JArray.Parse(jsonString);
@@ -146,9 +146,9 @@ public static async Task<JArray> GetUpdatesAsync(
146146
}
147147

148148
public static async Task<XDocument> GetFavorites(ConsumerBase twitter, string accessToken, CancellationToken cancellationToken = default(CancellationToken)) {
149-
var request = await twitter.PrepareAuthorizedRequestAsync(GetFavoritesEndpoint, accessToken, cancellationToken);
150-
using (var httpClient = twitter.Channel.HostFactories.CreateHttpClient()) {
151-
using (HttpResponseMessage response = await httpClient.SendAsync(request)) {
149+
using (var httpClient = twitter.CreateHttpClient(accessToken)) {
150+
using (HttpResponseMessage response = await httpClient.GetAsync(GetFavoritesEndpoint, cancellationToken)) {
151+
response.EnsureSuccessStatusCode();
152152
return XDocument.Parse(await response.Content.ReadAsStringAsync());
153153
}
154154
}
@@ -157,14 +157,15 @@ public static async Task<JArray> GetUpdatesAsync(
157157
public static async Task<XDocument> UpdateProfileBackgroundImageAsync(ConsumerBase twitter, string accessToken, string image, bool tile, CancellationToken cancellationToken) {
158158
var imageAttachment = new StreamContent(File.OpenRead(image));
159159
imageAttachment.Headers.ContentType = new MediaTypeHeaderValue("image/" + Path.GetExtension(image).Substring(1).ToLowerInvariant());
160-
var parts = new List<MultipartContentMember> {
161-
new MultipartContentMember(imageAttachment, "image"),
162-
new MultipartContentMember(new StringContent(tile.ToString().ToLowerInvariant()), "tile"),
163-
};
164-
HttpRequestMessage request = await twitter.PrepareAuthorizedRequestAsync(UpdateProfileBackgroundImageEndpoint, accessToken, parts, cancellationToken);
160+
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, UpdateProfileBackgroundImageEndpoint);
161+
var content = new MultipartFormDataContent();
162+
content.Add(imageAttachment, "image");
163+
content.Add(new StringContent(tile.ToString().ToLowerInvariant()), "tile");
164+
request.Content = content;
165165
request.Headers.ExpectContinue = false;
166-
using (var httpClient = twitter.Channel.HostFactories.CreateHttpClient()) {
167-
using (HttpResponseMessage response = await httpClient.SendAsync(request)) {
166+
using (var httpClient = twitter.CreateHttpClient(accessToken)) {
167+
using (HttpResponseMessage response = await httpClient.SendAsync(request, cancellationToken)) {
168+
response.EnsureSuccessStatusCode();
168169
string responseString = await response.Content.ReadAsStringAsync();
169170
return XDocument.Parse(responseString);
170171
}
@@ -179,23 +180,23 @@ public static async Task<XDocument> UpdateProfileBackgroundImageAsync(ConsumerBa
179180
public static async Task<XDocument> UpdateProfileImageAsync(ConsumerBase twitter, string accessToken, Stream image, string contentType, CancellationToken cancellationToken = default(CancellationToken)) {
180181
var imageAttachment = new StreamContent(image);
181182
imageAttachment.Headers.ContentType = new MediaTypeHeaderValue(contentType);
182-
var parts = new List<MultipartContentMember> {
183-
new MultipartContentMember(imageAttachment, "image", "twitterPhoto"),
184-
};
185-
186-
HttpRequestMessage request = await twitter.PrepareAuthorizedRequestAsync(UpdateProfileImageEndpoint, accessToken, parts, cancellationToken);
187-
using (var httpClient = twitter.Channel.HostFactories.CreateHttpClient()) {
188-
using (HttpResponseMessage response = await httpClient.SendAsync(request)) {
183+
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, UpdateProfileImageEndpoint);
184+
var content = new MultipartFormDataContent();
185+
content.Add(imageAttachment, "image", "twitterPhoto");
186+
request.Content = content;
187+
using (var httpClient = twitter.CreateHttpClient(accessToken)) {
188+
using (HttpResponseMessage response = await httpClient.SendAsync(request, cancellationToken)) {
189+
response.EnsureSuccessStatusCode();
189190
string responseString = await response.Content.ReadAsStringAsync();
190191
return XDocument.Parse(responseString);
191192
}
192193
}
193194
}
194195

195196
public static async Task<XDocument> VerifyCredentialsAsync(ConsumerBase twitter, string accessToken, CancellationToken cancellationToken = default(CancellationToken)) {
196-
var request = await twitter.PrepareAuthorizedRequestAsync(VerifyCredentialsEndpoint, accessToken, cancellationToken);
197-
using (var httpClient = twitter.Channel.HostFactories.CreateHttpClient()) {
198-
using (var response = await httpClient.SendAsync(request)) {
197+
using (var httpClient = twitter.CreateHttpClient(accessToken)) {
198+
using (var response = await httpClient.GetAsync(VerifyCredentialsEndpoint, cancellationToken)) {
199+
response.EnsureSuccessStatusCode();
199200
using (var stream = await response.Content.ReadAsStreamAsync()) {
200201
return XDocument.Load(XmlReader.Create(stream));
201202
}

samples/OAuthConsumer/GoogleApps2Legged.aspx.cs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,8 @@ private InMemoryTokenManager TokenManager {
3131
protected async void Page_Load(object sender, EventArgs e) {
3232
var google = new WebConsumer(GoogleConsumer.ServiceDescription, this.TokenManager);
3333
string accessToken = await google.RequestNewClientAccountAsync(cancellationToken: Response.ClientDisconnectedToken);
34-
////string tokenSecret = google.TokenManager.GetTokenSecret(accessToken);
35-
MessageReceivingEndpoint ep = null; // set up your authorized call here.
36-
var request = await google.PrepareAuthorizedRequestAsync(ep, accessToken, Response.ClientDisconnectedToken);
37-
using (var httpClient = google.Channel.HostFactories.CreateHttpClient()) {
38-
await httpClient.SendAsync(request);
34+
using (var httpClient = google.CreateHttpClient(accessToken)) {
35+
await httpClient.GetAsync("http://someUri", Response.ClientDisconnectedToken);
3936
}
4037
}
4138
}

samples/OAuthConsumer/SampleWcf.aspx.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
using System.Globalization;
55
using System.Linq;
66
using System.Net;
7+
using System.Net.Http;
78
using System.ServiceModel;
89
using System.ServiceModel.Channels;
910
using System.ServiceModel.Security;
@@ -83,8 +84,13 @@ private async Task<T> CallServiceAsync<T>(Func<DataApiClient, T> predicate) {
8384
if (accessToken == null) {
8485
throw new InvalidOperationException("No access token!");
8586
}
86-
WebConsumer consumer = this.CreateConsumer();
87-
var httpRequest = await consumer.PrepareAuthorizedRequestAsync(serviceEndpoint, accessToken, Response.ClientDisconnectedToken);
87+
88+
var httpRequest = new HttpRequestMessage(HttpMethod.Post, client.Endpoint.Address.Uri);
89+
using (WebConsumer consumer = this.CreateConsumer()) {
90+
using (var handler = consumer.CreateMessageHandler(accessToken)) {
91+
handler.ApplyOAuthParameters(httpRequest);
92+
}
93+
}
8894

8995
HttpRequestMessageProperty httpDetails = new HttpRequestMessageProperty();
9096
httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers.Authorization.ToString();

samples/OAuthConsumerWpf/MainWindow.xaml.cs

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -137,9 +137,15 @@ private async Task<T> CallServiceAsync<T>(Func<DataApiClient, T> predicate) {
137137
private async void beginButton_Click(object sender, RoutedEventArgs e) {
138138
try {
139139
var service = new ServiceProviderDescription {
140-
RequestTokenEndpoint = new MessageReceivingEndpoint(this.requestTokenUrlBox.Text, this.requestTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest),
140+
RequestTokenEndpoint =
141+
new MessageReceivingEndpoint(
142+
this.requestTokenUrlBox.Text,
143+
this.requestTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest),
141144
UserAuthorizationEndpoint = new MessageReceivingEndpoint(this.authorizeUrlBox.Text, HttpDeliveryMethods.GetRequest),
142-
AccessTokenEndpoint = new MessageReceivingEndpoint(this.accessTokenUrlBox.Text, this.accessTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest),
145+
AccessTokenEndpoint =
146+
new MessageReceivingEndpoint(
147+
this.accessTokenUrlBox.Text,
148+
this.accessTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest),
143149
TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
144150
ProtocolVersion = this.oauthVersion.SelectedIndex == 0 ? ProtocolVersion.V10 : ProtocolVersion.V10a,
145151
};
@@ -158,9 +164,7 @@ private async void beginButton_Click(object sender, RoutedEventArgs e) {
158164
var authorizationResponse = await consumer.ProcessUserAuthorizationAsync(requestToken, null);
159165
accessToken = authorizationResponse.AccessToken;
160166
} else {
161-
var authorizePopup = new Authorize(
162-
consumer,
163-
c => c.RequestUserAuthorizationAsync(null, null));
167+
var authorizePopup = new Authorize(consumer, c => c.RequestUserAuthorizationAsync(null, null));
164168
authorizePopup.Owner = this;
165169
bool? result = authorizePopup.ShowDialog();
166170
if (result.HasValue && result.Value) {
@@ -169,15 +173,16 @@ private async void beginButton_Click(object sender, RoutedEventArgs e) {
169173
return;
170174
}
171175
}
172-
HttpDeliveryMethods resourceHttpMethod = this.resourceHttpMethodList.SelectedIndex < 2 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest;
173-
if (this.resourceHttpMethodList.SelectedIndex == 1) {
174-
resourceHttpMethod |= HttpDeliveryMethods.AuthorizationHeaderRequest;
175-
}
176-
var resourceEndpoint = new MessageReceivingEndpoint(this.resourceUrlBox.Text, resourceHttpMethod);
177-
var request = await consumer.PrepareAuthorizedRequestAsync(resourceEndpoint, accessToken);
178-
using (var httpClient = new HttpClient()) {
179-
using (var resourceResponse = await httpClient.SendAsync(request)) {
180-
this.resultsBox.Text = await resourceResponse.Content.ReadAsStringAsync();
176+
HttpMethod resourceHttpMethod = this.resourceHttpMethodList.SelectedIndex < 2 ? HttpMethod.Get : HttpMethod.Post;
177+
using (var handler = consumer.CreateMessageHandler(accessToken)) {
178+
handler.Location = this.resourceHttpMethodList.SelectedIndex == 1
179+
? OAuth1HttpMessageHandlerBase.OAuthParametersLocation.AuthorizationHttpHeader
180+
: OAuth1HttpMessageHandlerBase.OAuthParametersLocation.QueryString;
181+
using (var httpClient = consumer.CreateHttpClient(handler)) {
182+
var request = new HttpRequestMessage(resourceHttpMethod, this.resourceUrlBox.Text);
183+
using (var resourceResponse = await httpClient.SendAsync(request)) {
184+
this.resultsBox.Text = await resourceResponse.Content.ReadAsStringAsync();
185+
}
181186
}
182187
}
183188
} catch (DotNetOpenAuth.Messaging.ProtocolException ex) {

src/DotNetOpenAuth.AspNet/Clients/OAuth/DotNetOpenAuthWebConsumer.cs

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,19 +50,23 @@ public DotNetOpenAuthWebConsumer(ServiceProviderDescription serviceDescription,
5050

5151
#endregion
5252

53+
/// <summary>
54+
/// Gets the DotNetOpenAuth <see cref="WebConsumer"/> instance that can be used to make OAuth 1.0 authorized HTTP requests.
55+
/// </summary>
56+
public WebConsumer Consumer {
57+
get { return this.webConsumer; }
58+
}
59+
5360
#region Public Methods and Operators
5461

5562
/// <summary>
56-
/// The prepare authorized request.
63+
/// Creates an HTTP message handler that authorizes outgoing web requests.
5764
/// </summary>
58-
/// <param name="profileEndpoint">The profile endpoint.</param>
5965
/// <param name="accessToken">The access token.</param>
60-
/// <param name="cancellationToken">The cancellation token.</param>
61-
/// <returns>
62-
/// An HTTP request.
63-
/// </returns>
64-
public Task<HttpRequestMessage> PrepareAuthorizedRequestAsync(MessageReceivingEndpoint profileEndpoint, string accessToken, CancellationToken cancellationToken = default(CancellationToken)) {
65-
return this.webConsumer.PrepareAuthorizedRequestAsync(profileEndpoint, accessToken, cancellationToken);
66+
public HttpMessageHandler CreateMessageHandler(string accessToken) {
67+
Requires.NotNullOrEmpty(accessToken, "accessToken");
68+
69+
return this.Consumer.CreateMessageHandler(accessToken);
6670
}
6771

6872
/// <summary>

src/DotNetOpenAuth.AspNet/Clients/OAuth/IOAuthWebWorker.cs

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,21 +14,14 @@ namespace DotNetOpenAuth.AspNet.Clients {
1414
using DotNetOpenAuth.OAuth.Messages;
1515

1616
/// <summary>
17-
/// The io auth web worker.
17+
/// The interface implemented by all OAuth web authentication modules in this assembly.
1818
/// </summary>
1919
public interface IOAuthWebWorker {
20-
#region Public Methods and Operators
21-
2220
/// <summary>
23-
/// The prepare authorized request.
21+
/// Creates an HTTP message handler that authorizes outgoing web requests.
2422
/// </summary>
25-
/// <param name="profileEndpoint">The profile endpoint.</param>
2623
/// <param name="accessToken">The access token.</param>
27-
/// <param name="cancellationToken">The cancellation token.</param>
28-
/// <returns>
29-
/// An HTTP request.
30-
/// </returns>
31-
Task<HttpRequestMessage> PrepareAuthorizedRequestAsync(MessageReceivingEndpoint profileEndpoint, string accessToken, CancellationToken cancellationToken = default(CancellationToken));
24+
HttpMessageHandler CreateMessageHandler(string accessToken);
3225

3326
/// <summary>
3427
/// The process user authorization.
@@ -46,7 +39,5 @@ public interface IOAuthWebWorker {
4639
/// <param name="cancellationToken">The cancellation token.</param>
4740
/// <returns>The response message</returns>
4841
Task<HttpResponseMessage> RequestAuthenticationAsync(Uri callback, CancellationToken cancellationToken = default(CancellationToken));
49-
50-
#endregion
5142
}
5243
}

0 commit comments

Comments
 (0)