summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj1
-rw-r--r--src/DotNetOpenAuth.Core/IHostFactories.cs41
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/Channel.cs79
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs23
-rw-r--r--src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs4
-rw-r--r--src/DotNetOpenAuth.OpenId/DefaultOpenIdHostFactories.cs54
-rw-r--r--src/DotNetOpenAuth.OpenId/DotNetOpenAuth.OpenId.csproj4
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs5
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs90
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs35
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/IOpenIdHost.cs3
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryServices.cs12
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs4
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs48
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs4
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/Realm.cs14
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequest.cs3
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/UntrustedWebRequestHandler.cs405
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/UriDiscoveryService.cs29
-rw-r--r--src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs37
-rw-r--r--src/DotNetOpenAuth.OpenId/Yadis/DiscoveryResult.cs63
-rw-r--r--src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs128
-rw-r--r--src/DotNetOpenAuth.OpenId/packages.config1
23 files changed, 885 insertions, 202 deletions
diff --git a/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj b/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj
index a71223a..e539ea1 100644
--- a/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj
+++ b/src/DotNetOpenAuth.Core/DotNetOpenAuth.Core.csproj
@@ -20,6 +20,7 @@
</PropertyGroup>
<ItemGroup>
<Compile Include="Assumes.cs" />
+ <Compile Include="IHostFactories.cs" />
<Compile Include="Messaging\Base64WebEncoder.cs" />
<Compile Include="Messaging\Bindings\AsymmetricCryptoKeyStoreWrapper.cs" />
<Compile Include="Messaging\Bindings\CryptoKey.cs" />
diff --git a/src/DotNetOpenAuth.Core/IHostFactories.cs b/src/DotNetOpenAuth.Core/IHostFactories.cs
new file mode 100644
index 0000000..d171ed8
--- /dev/null
+++ b/src/DotNetOpenAuth.Core/IHostFactories.cs
@@ -0,0 +1,41 @@
+//-----------------------------------------------------------------------
+// <copyright file="IHostFactories.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Net.Http;
+ using System.Text;
+ using System.Threading.Tasks;
+
+ /// <summary>
+ /// Provides the host application or tests with the ability to create standard message handlers or stubs.
+ /// </summary>
+ public interface IHostFactories {
+ /// <summary>
+ /// Initializes a new instance of a concrete derivation of <see cref="HttpMessageHandler"/>
+ /// to be used for outbound HTTP traffic.
+ /// </summary>
+ /// <returns>An instance of <see cref="HttpMessageHandler"/>.</returns>
+ /// <remarks>
+ /// An instance of <see cref="WebRequestHandler"/> is recommended where available;
+ /// otherwise an instance of <see cref="HttpClientHandler"/> is recommended.
+ /// </remarks>
+ HttpMessageHandler CreateHttpMessageHandler();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="HttpClient"/> class
+ /// to be used for outbound HTTP traffic.
+ /// </summary>
+ /// <param name="handler">
+ /// The handler to pass to the <see cref="HttpClient"/> constructor.
+ /// May be null to use the default that would be provided by <see cref="CreateHttpMessageHandler"/>.
+ /// </param>
+ /// <returns>An instance of <see cref="HttpClient"/>.</returns>
+ HttpClient CreateHttpClient(HttpMessageHandler handler = null);
+ }
+}
diff --git a/src/DotNetOpenAuth.Core/Messaging/Channel.cs b/src/DotNetOpenAuth.Core/Messaging/Channel.cs
index ad094e0..bff44e7 100644
--- a/src/DotNetOpenAuth.Core/Messaging/Channel.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/Channel.cs
@@ -149,30 +149,19 @@ namespace DotNetOpenAuth.Messaging {
private int maximumIndirectMessageUrlLength = Configuration.DotNetOpenAuthSection.Messaging.MaximumIndirectMessageUrlLength;
/// <summary>
- /// Initializes a new instance of the <see cref="Channel"/> class.
- /// </summary>
- /// <param name="messageTypeProvider">
- /// A class prepared to analyze incoming messages and indicate what concrete
- /// message types can deserialize from it.
- /// </param>
- /// <param name="bindingElements">
- /// The binding elements to use in sending and receiving messages.
- /// The order they are provided is used for outgoing messgaes, and reversed for incoming messages.
- /// </param>
- /// <param name="messageHandler">The HTTP handler to use for outgoing HTTP requests.</param>
- protected Channel(IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements, HttpMessageHandler messageHandler = null) {
+ /// Initializes a new instance of the <see cref="Channel" /> class.
+ /// </summary>
+ /// <param name="messageTypeProvider">A class prepared to analyze incoming messages and indicate what concrete
+ /// message types can deserialize from it.</param>
+ /// <param name="bindingElements">The binding elements to use in sending and receiving messages.
+ /// The order they are provided is used for outgoing messgaes, and reversed for incoming messages.</param>
+ /// <param name="hostFactories">The host factories.</param>
+ protected Channel(IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements, IHostFactories hostFactories) {
Requires.NotNull(messageTypeProvider, "messageTypeProvider");
-
- messageHandler = messageHandler ?? new WebRequestHandler();
- var httpHandler = messageHandler as WebRequestHandler;
- if (httpHandler != null) {
- // TODO: provide this as a recommendation to derived Channel types, but without tampering with
- // the setting once it has been provided to this constructor.
- httpHandler.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
- }
+ Requires.NotNull(hostFactories, "hostFactories");
this.messageTypeProvider = messageTypeProvider;
- this.WebRequestHandler = new HttpClient(messageHandler);
+ this.HostFactories = hostFactories;
this.XmlDictionaryReaderQuotas = DefaultUntrustedXmlDictionaryReaderQuotas;
this.outgoingBindingElements = new List<IChannelBindingElement>(ValidateAndPrepareBindingElements(bindingElements));
@@ -190,14 +179,9 @@ namespace DotNetOpenAuth.Messaging {
internal event EventHandler<ChannelEventArgs> Sending;
/// <summary>
- /// Gets or sets an instance to a <see cref="HttpClient"/> that will be used when
- /// submitting HTTP requests and waiting for responses.
+ /// Gets the host factories instance to use.
/// </summary>
- /// <remarks>
- /// This defaults to a straightforward implementation, but can be set
- /// to a mock object for testing purposes.
- /// </remarks>
- public HttpClient WebRequestHandler { get; set; }
+ public IHostFactories HostFactories { get; private set; }
/// <summary>
/// Gets or sets the maximum allowable size for a 301 Redirect response before we send
@@ -557,8 +541,8 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="response">The response that is anticipated to contain an protocol message.</param>
/// <returns>The deserialized message parts, if found. Null otherwise.</returns>
/// <exception cref="ProtocolException">Thrown when the response is not valid.</exception>
- internal IDictionary<string, string> ReadFromResponseCoreTestHook(HttpResponseMessage response) {
- return this.ReadFromResponseCore(response);
+ internal Task<IDictionary<string, string>> ReadFromResponseCoreAsyncTestHook(HttpResponseMessage response) {
+ return this.ReadFromResponseCoreAsync(response);
}
/// <remarks>
@@ -689,22 +673,24 @@ namespace DotNetOpenAuth.Messaging {
IDictionary<string, string> responseFields;
IDirectResponseProtocolMessage responseMessage;
- using (HttpResponseMessage response = await this.WebRequestHandler.SendAsync(webRequest)) {
- if (response.Content == null) {
- return null;
- }
+ using (var httpClient = this.HostFactories.CreateHttpClient()) {
+ using (HttpResponseMessage response = await httpClient.SendAsync(webRequest)) {
+ if (response.Content == null) {
+ return null;
+ }
- responseFields = this.ReadFromResponseCore(response);
- if (responseFields == null) {
- return null;
- }
+ responseFields = await this.ReadFromResponseCoreAsync(response);
+ if (responseFields == null) {
+ return null;
+ }
- responseMessage = this.MessageFactory.GetNewResponseMessage(request, responseFields);
- if (responseMessage == null) {
- return null;
- }
+ responseMessage = this.MessageFactory.GetNewResponseMessage(request, responseFields);
+ if (responseMessage == null) {
+ return null;
+ }
- this.OnReceivingDirectResponse(response, responseMessage);
+ this.OnReceivingDirectResponse(response, responseMessage);
+ }
}
var messageAccessor = this.MessageDescriptions.GetAccessor(responseMessage);
@@ -713,6 +699,11 @@ namespace DotNetOpenAuth.Messaging {
return responseMessage;
}
+ protected virtual HttpMessageHandler WrapMessageHandler(HttpMessageHandler innerHandler) {
+ // No wrapping by default.
+ return innerHandler;
+ }
+
/// <summary>
/// Called when receiving a direct response message, before deserialization begins.
/// </summary>
@@ -898,7 +889,7 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="response">The response that is anticipated to contain an protocol message.</param>
/// <returns>The deserialized message parts, if found. Null otherwise.</returns>
/// <exception cref="ProtocolException">Thrown when the response is not valid.</exception>
- protected abstract IDictionary<string, string> ReadFromResponseCore(HttpResponseMessage response);
+ protected abstract Task<IDictionary<string, string>> ReadFromResponseCoreAsync(HttpResponseMessage response);
/// <summary>
/// Prepares an HTTP request that carries a given message.
diff --git a/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs b/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs
index 3da62e9..267b003 100644
--- a/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/MessagingUtilities.cs
@@ -378,6 +378,29 @@ namespace DotNetOpenAuth.Messaging {
return GetPublicFacingUrl(request, request.ServerVariables);
}
+ internal static void DisposeIfNotNull(this IDisposable disposable) {
+ if (disposable != null) {
+ disposable.Dispose();
+ }
+ }
+
+ internal static HttpRequestMessage Clone(this HttpRequestMessage original, Uri newRequestUri = null) {
+ Requires.NotNull(original, "original");
+
+ var clone = new HttpRequestMessage(original.Method, newRequestUri ?? original.RequestUri);
+ clone.Content = original.Content;
+ foreach (var header in original.Headers) {
+ clone.Headers.Add(header.Key, header.Value);
+ }
+
+ foreach (var property in original.Properties) {
+ clone.Properties[property.Key] = property.Value;
+ }
+
+ clone.Version = original.Version;
+ return clone;
+ }
+
/// <summary>
/// Gets the URL to the root of a web site, which may include a virtual directory path.
/// </summary>
diff --git a/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs
index 9cb80b0..be37dc4 100644
--- a/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs
+++ b/src/DotNetOpenAuth.Core/Messaging/StandardMessageFactoryChannel.cs
@@ -35,8 +35,8 @@ namespace DotNetOpenAuth.Messaging {
/// The binding elements to use in sending and receiving messages.
/// The order they are provided is used for outgoing messgaes, and reversed for incoming messages.
/// </param>
- protected StandardMessageFactoryChannel(ICollection<Type> messageTypes, ICollection<Version> versions, params IChannelBindingElement[] bindingElements)
- : base(new StandardMessageFactory(), bindingElements) {
+ protected StandardMessageFactoryChannel(ICollection<Type> messageTypes, ICollection<Version> versions, IChannelBindingElement[] bindingElements, IHostFactories hostFactories)
+ : base(new StandardMessageFactory(), bindingElements, hostFactories) {
Requires.NotNull(messageTypes, "messageTypes");
Requires.NotNull(versions, "versions");
diff --git a/src/DotNetOpenAuth.OpenId/DefaultOpenIdHostFactories.cs b/src/DotNetOpenAuth.OpenId/DefaultOpenIdHostFactories.cs
new file mode 100644
index 0000000..18ad727
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/DefaultOpenIdHostFactories.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <copyright file="DefaultHostFactories.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Net.Cache;
+ using System.Net.Http;
+ using System.Text;
+ using System.Threading.Tasks;
+
+ /// <summary>
+ /// Creates default instances of required dependencies.
+ /// </summary>
+ public class DefaultOpenIdHostFactories : IHostFactories {
+ /// <summary>
+ /// Initializes a new instance of a concrete derivation of <see cref="HttpMessageHandler" />
+ /// to be used for outbound HTTP traffic.
+ /// </summary>
+ /// <returns>An instance of <see cref="HttpMessageHandler"/>.</returns>
+ /// <remarks>
+ /// An instance of <see cref="WebRequestHandler" /> is recommended where available;
+ /// otherwise an instance of <see cref="HttpClientHandler" /> is recommended.
+ /// </remarks>
+ public virtual HttpMessageHandler CreateHttpMessageHandler() {
+ var handler = new UntrustedWebRequestHandler();
+ handler.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
+ return handler;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="HttpClient" /> class
+ /// to be used for outbound HTTP traffic.
+ /// </summary>
+ /// <param name="handler">The handler to pass to the <see cref="HttpClient" /> constructor.
+ /// May be null to use the default that would be provided by <see cref="CreateHttpMessageHandler" />.</param>
+ /// <returns>
+ /// An instance of <see cref="HttpClient" />.
+ /// </returns>
+ public HttpClient CreateHttpClient(HttpMessageHandler handler) {
+ handler = handler ?? this.CreateHttpMessageHandler();
+ var untrustedHandler = handler as UntrustedWebRequestHandler;
+ if (untrustedHandler != null) {
+ return untrustedHandler.CreateClient();
+ } else {
+ return new HttpClient(handler);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId/DotNetOpenAuth.OpenId.csproj b/src/DotNetOpenAuth.OpenId/DotNetOpenAuth.OpenId.csproj
index e238d58..e785719 100644
--- a/src/DotNetOpenAuth.OpenId/DotNetOpenAuth.OpenId.csproj
+++ b/src/DotNetOpenAuth.OpenId/DotNetOpenAuth.OpenId.csproj
@@ -30,6 +30,7 @@
<Compile Include="Configuration\OpenIdRelyingPartyElement.cs" />
<Compile Include="Configuration\OpenIdRelyingPartySecuritySettingsElement.cs" />
<Compile Include="Configuration\XriResolverElement.cs" />
+ <Compile Include="DefaultOpenIdHostFactories.cs" />
<Compile Include="OpenIdXrdsHelperRelyingParty.cs" />
<Compile Include="OpenId\Association.cs" />
<Compile Include="OpenId\AuthenticationRequestMode.cs" />
@@ -141,6 +142,7 @@
<Compile Include="OpenId\Protocol.cs" />
<Compile Include="OpenId\IOpenIdApplicationStore.cs" />
<Compile Include="OpenId\RelyingParty\RelyingPartySecuritySettings.cs" />
+ <Compile Include="OpenId\UntrustedWebRequestHandler.cs" />
<Compile Include="OpenId\UriDiscoveryService.cs" />
<Compile Include="OpenId\XriDiscoveryProxyService.cs" />
<Compile Include="OpenId\SecuritySettings.cs" />
@@ -183,6 +185,8 @@
</ProjectReference>
</ItemGroup>
<ItemGroup>
+ <Reference Include="System.Net.Http" />
+ <Reference Include="System.Net.Http.WebRequest" />
<Reference Include="Validation">
<HintPath>..\packages\Validation.2.0.1.12362\lib\portable-windows8+net40+sl5+windowsphone8\Validation.dll</HintPath>
<Private>True</Private>
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs
index 6ad66c0..c74a636 100644
--- a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/KeyValueFormEncoding.cs
@@ -11,6 +11,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
using System.Globalization;
using System.IO;
using System.Text;
+ using System.Threading.Tasks;
using DotNetOpenAuth.Messaging;
using Validation;
@@ -131,12 +132,12 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// <param name="data">The stream of Key-Value Form encoded bytes.</param>
/// <returns>The deserialized dictionary.</returns>
/// <exception cref="FormatException">Thrown when the data is not in the expected format.</exception>
- public IDictionary<string, string> GetDictionary(Stream data) {
+ public async Task<IDictionary<string, string>> GetDictionaryAsync(Stream data) {
using (StreamReader reader = new StreamReader(data, textEncoding)) {
var dict = new Dictionary<string, string>();
int line_num = 0;
string line;
- while ((line = reader.ReadLine()) != null) {
+ while ((line = await reader.ReadLineAsync()) != null) {
line_num++;
if (this.ConformanceLevel == KeyValueFormConformanceLevel.Loose) {
line = line.Trim();
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs
index 5a6b8bb..eb4ca65 100644
--- a/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/ChannelElements/OpenIdChannel.cs
@@ -7,12 +7,18 @@
namespace DotNetOpenAuth.OpenId.ChannelElements {
using System;
using System.Collections.Generic;
+ using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
+ using System.Net.Http;
+ using System.Net.Http.Headers;
using System.Text;
+ using System.Threading.Tasks;
+
+ using DotNetOpenAuth.Configuration;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.OpenId.Extensions;
@@ -45,8 +51,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// <param name="messageTypeProvider">A class prepared to analyze incoming messages and indicate what concrete
/// message types can deserialize from it.</param>
/// <param name="bindingElements">The binding elements to use in sending and receiving messages.</param>
- protected OpenIdChannel(IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements)
- : base(messageTypeProvider, bindingElements) {
+ protected OpenIdChannel(IMessageFactory messageTypeProvider, IChannelBindingElement[] bindingElements, IHostFactories hostFactories)
+ : base(messageTypeProvider, bindingElements, hostFactories ?? new DefaultOpenIdHostFactories()) {
Requires.NotNull(messageTypeProvider, "messageTypeProvider");
// Customize the binding element order, since we play some tricks for higher
@@ -68,11 +74,6 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
}
this.CustomizeBindingElementOrder(outgoingBindingElements, incomingBindingElements);
-
- // Change out the standard web request handler to reflect the standard
- // OpenID pattern that outgoing web requests are to unknown and untrusted
- // servers on the Internet.
- this.WebRequestHandler = new UntrustedWebRequestHandler();
}
/// <summary>
@@ -120,7 +121,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// <returns>
/// The <see cref="HttpWebRequest"/> prepared to send the request.
/// </returns>
- protected override HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request) {
+ protected override HttpRequestMessage CreateHttpRequest(IDirectedProtocolMessage request) {
return this.InitializeRequestAsPost(request);
}
@@ -132,9 +133,11 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// The deserialized message parts, if found. Null otherwise.
/// </returns>
/// <exception cref="ProtocolException">Thrown when the response is not valid.</exception>
- protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) {
+ protected override async Task<IDictionary<string, string>> ReadFromResponseCoreAsync(HttpResponseMessage response) {
try {
- return this.keyValueForm.GetDictionary(response.ResponseStream);
+ using (var responseStream = await response.Content.ReadAsStreamAsync()) {
+ return await this.keyValueForm.GetDictionaryAsync(responseStream);
+ }
} catch (FormatException ex) {
throw ErrorUtilities.Wrap(ex, ex.Message);
}
@@ -145,7 +148,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// </summary>
/// <param name="response">The HTTP direct response.</param>
/// <param name="message">The newly instantiated message, prior to deserialization.</param>
- protected override void OnReceivingDirectResponse(IncomingWebResponse response, IDirectResponseProtocolMessage message) {
+ protected override void OnReceivingDirectResponse(HttpResponseMessage response, IDirectResponseProtocolMessage message) {
base.OnReceivingDirectResponse(response, message);
// Verify that the expected HTTP status code was used for the message,
@@ -155,10 +158,10 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
var httpDirectResponse = message as IHttpDirectResponse;
if (httpDirectResponse != null) {
ErrorUtilities.VerifyProtocol(
- httpDirectResponse.HttpStatusCode == response.Status,
+ httpDirectResponse.HttpStatusCode == response.StatusCode,
MessagingStrings.UnexpectedHttpStatusCode,
(int)httpDirectResponse.HttpStatusCode,
- (int)response.Status);
+ (int)response.StatusCode);
}
}
}
@@ -174,55 +177,58 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// <remarks>
/// This method implements spec V1.0 section 5.3.
/// </remarks>
- protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) {
+ protected override HttpResponseMessage PrepareDirectResponse(IProtocolMessage response) {
var messageAccessor = this.MessageDescriptions.GetAccessor(response);
var fields = messageAccessor.Serialize();
byte[] keyValueEncoding = KeyValueFormEncoding.GetBytes(fields);
- OutgoingWebResponse preparedResponse = new OutgoingWebResponse();
+ var preparedResponse = new HttpResponseMessage();
ApplyMessageTemplate(response, preparedResponse);
- preparedResponse.Headers.Add(HttpResponseHeader.ContentType, KeyValueFormContentType);
- preparedResponse.OriginalMessage = response;
- preparedResponse.ResponseStream = new MemoryStream(keyValueEncoding);
+ var content = new StreamContent(new MemoryStream(keyValueEncoding));
+ content.Headers.ContentType = new MediaTypeHeaderValue(KeyValueFormContentType);
+ preparedResponse.Content = content;
IHttpDirectResponse httpMessage = response as IHttpDirectResponse;
if (httpMessage != null) {
- preparedResponse.Status = httpMessage.HttpStatusCode;
+ preparedResponse.StatusCode = httpMessage.HttpStatusCode;
}
return preparedResponse;
}
- /// <summary>
- /// Gets the direct response of a direct HTTP request.
- /// </summary>
- /// <param name="webRequest">The web request.</param>
- /// <returns>The response to the web request.</returns>
- /// <exception cref="ProtocolException">Thrown on network or protocol errors.</exception>
- protected override IncomingWebResponse GetDirectResponse(HttpWebRequest webRequest) {
- IncomingWebResponse response = this.WebRequestHandler.GetResponse(webRequest, DirectWebRequestOptions.AcceptAllHttpResponses);
-
- // Filter the responses to the allowable set of HTTP status codes.
- if (response.Status != HttpStatusCode.OK && response.Status != HttpStatusCode.BadRequest) {
- if (Logger.Channel.IsErrorEnabled) {
- using (var reader = new StreamReader(response.ResponseStream)) {
+ protected override HttpMessageHandler WrapMessageHandler(HttpMessageHandler innerHandler) {
+ return new ErrorFilteringMessageHandler(base.WrapMessageHandler(innerHandler));
+ }
+
+ private class ErrorFilteringMessageHandler : DelegatingHandler {
+ internal ErrorFilteringMessageHandler(HttpMessageHandler innerHandler)
+ : base(innerHandler) {
+ }
+
+ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) {
+ var response = await base.SendAsync(request, cancellationToken);
+
+ // Filter the responses to the allowable set of HTTP status codes.
+ if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.BadRequest) {
+ if (Logger.Channel.IsErrorEnabled) {
+ var content = await response.Content.ReadAsStringAsync();
Logger.Channel.ErrorFormat(
"Unexpected HTTP status code {0} {1} received in direct response:{2}{3}",
- (int)response.Status,
- response.Status,
+ (int)response.StatusCode,
+ response.StatusCode,
Environment.NewLine,
- reader.ReadToEnd());
+ content);
}
- }
- // Call dispose before throwing since we're not including the response in the
- // exception we're throwing.
- response.Dispose();
+ // Call dispose before throwing since we're not including the response in the
+ // exception we're throwing.
+ response.Dispose();
- ErrorUtilities.ThrowProtocol(OpenIdStrings.UnexpectedHttpStatusCode, (int)response.Status, response.Status);
- }
+ ErrorUtilities.ThrowProtocol(OpenIdStrings.UnexpectedHttpStatusCode, (int)response.StatusCode, response.StatusCode);
+ }
- return response;
+ return response;
+ }
}
}
}
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs b/src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs
index 20b8f1c..4d1450e 100644
--- a/src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/IIdentifierDiscoveryService.cs
@@ -10,7 +10,11 @@ namespace DotNetOpenAuth.OpenId {
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
+ using System.Net.Http;
+ using System.Runtime.CompilerServices;
using System.Text;
+ using System.Threading;
+ using System.Threading.Tasks;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId.RelyingParty;
using Validation;
@@ -23,13 +27,38 @@ namespace DotNetOpenAuth.OpenId {
/// Performs discovery on the specified identifier.
/// </summary>
/// <param name="identifier">The identifier to perform discovery on.</param>
- /// <param name="requestHandler">The means to place outgoing HTTP requests.</param>
/// <param name="abortDiscoveryChain">if set to <c>true</c>, no further discovery services will be called for this identifier.</param>
/// <returns>
/// A sequence of service endpoints yielded by discovery. Must not be null, but may be empty.
/// </returns>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "By design")]
- [Pure]
- IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain);
+ Task<IdentifierDiscoveryServiceResult> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken);
+ }
+
+ /// <summary>
+ /// Describes the result of <see cref="IIdentifierDiscoveryService.DiscoverAsync"/>.
+ /// </summary>
+ public class IdentifierDiscoveryServiceResult {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="IdentifierDiscoveryServiceResult" /> class.
+ /// </summary>
+ /// <param name="results">The results.</param>
+ /// <param name="abortDiscoveryChain">if set to <c>true</c>, no further discovery services will be called for this identifier.</param>
+ public IdentifierDiscoveryServiceResult(IEnumerable<IdentifierDiscoveryResult> results, bool abortDiscoveryChain = false) {
+ Requires.NotNull(results, "results");
+
+ this.Results = results;
+ this.AbortDiscoveryChain = abortDiscoveryChain;
+ }
+
+ /// <summary>
+ /// Gets the results from this individual discovery service.
+ /// </summary>
+ public IEnumerable<IdentifierDiscoveryResult> Results { get; private set; }
+
+ /// <summary>
+ /// Gets a value indicating whether no further discovery services should be called for this identifier.
+ /// </summary>
+ public bool AbortDiscoveryChain { get; private set; }
}
}
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/IOpenIdHost.cs b/src/DotNetOpenAuth.OpenId/OpenId/IOpenIdHost.cs
index 419cc84..0c5bf80 100644
--- a/src/DotNetOpenAuth.OpenId/OpenId/IOpenIdHost.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/IOpenIdHost.cs
@@ -8,6 +8,7 @@ namespace DotNetOpenAuth.OpenId {
using System;
using System.Collections.Generic;
using System.Linq;
+ using System.Net.Http;
using System.Text;
using DotNetOpenAuth.Messaging;
@@ -23,6 +24,6 @@ namespace DotNetOpenAuth.OpenId {
/// <summary>
/// Gets the web request handler.
/// </summary>
- IDirectWebRequestHandler WebRequestHandler { get; }
+ IHostFactories HostFactories { get; }
}
}
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryServices.cs b/src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryServices.cs
index 1b20d4e..4d55c5c 100644
--- a/src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryServices.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/IdentifierDiscoveryServices.cs
@@ -7,6 +7,9 @@
namespace DotNetOpenAuth.OpenId {
using System.Collections.Generic;
using System.Linq;
+ using System.Runtime.CompilerServices;
+ using System.Threading;
+ using System.Threading.Tasks;
using DotNetOpenAuth.Configuration;
using DotNetOpenAuth.Messaging;
using Validation;
@@ -48,15 +51,14 @@ namespace DotNetOpenAuth.OpenId {
/// </summary>
/// <param name="identifier">The identifier to discover services for.</param>
/// <returns>A non-null sequence of services discovered for the identifier.</returns>
- public IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier) {
+ public async Task<IEnumerable<IdentifierDiscoveryResult>> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken) {
Requires.NotNull(identifier, "identifier");
IEnumerable<IdentifierDiscoveryResult> results = Enumerable.Empty<IdentifierDiscoveryResult>();
foreach (var discoverer in this.DiscoveryServices) {
- bool abortDiscoveryChain;
- var discoveryResults = discoverer.Discover(identifier, this.host.WebRequestHandler, out abortDiscoveryChain).CacheGeneratedResults();
- results = results.Concat(discoveryResults);
- if (abortDiscoveryChain) {
+ var discoveryResults = await discoverer.DiscoverAsync(identifier, cancellationToken);
+ results = results.Concat(discoveryResults.Results.CacheGeneratedResults());
+ if (discoveryResults.AbortDiscoveryChain) {
Logger.OpenId.InfoFormat("Further discovery on '{0}' was stopped by the {1} discovery service.", identifier, discoverer.GetType().Name);
break;
}
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs b/src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs
index 9aac107..d67e9fe 100644
--- a/src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Messages/NegativeAssertionResponse.cs
@@ -9,6 +9,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
using System.Collections.Generic;
using System.Linq;
using System.Text;
+ using System.Threading.Tasks;
using DotNetOpenAuth.Messaging;
using Validation;
@@ -123,7 +124,8 @@ namespace DotNetOpenAuth.OpenId.Messages {
setupRequest.ReturnTo = immediateRequest.ReturnTo;
setupRequest.Realm = immediateRequest.Realm;
setupRequest.AssociationHandle = immediateRequest.AssociationHandle;
- return channel.PrepareResponse(setupRequest).GetDirectUriRequest(channel);
+ var response = channel.PrepareResponse(setupRequest);
+ return response.GetDirectUriRequest();
}
/// <summary>
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs
index e04a633..f0ed946 100644
--- a/src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/OpenIdUtilities.cs
@@ -11,7 +11,11 @@ namespace DotNetOpenAuth.OpenId {
using System.Globalization;
using System.IO;
using System.Linq;
+ using System.Net;
+ using System.Net.Cache;
+ using System.Net.Http;
using System.Text.RegularExpressions;
+ using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using DotNetOpenAuth.Messaging;
@@ -180,6 +184,50 @@ namespace DotNetOpenAuth.OpenId {
return fullyQualifiedRealm;
}
+ internal static HttpClient CreateHttpClient(this IHostFactories hostFactories, bool requireSsl, RequestCachePolicy cachePolicy = null) {
+ Requires.NotNull(hostFactories, "hostFactories");
+
+ var handler = hostFactories.CreateHttpMessageHandler();
+ var webRequestHandler = handler as WebRequestHandler;
+ var untrustedHandler = handler as UntrustedWebRequestHandler;
+ if (webRequestHandler != null) {
+ if (cachePolicy != null) {
+ webRequestHandler.CachePolicy = cachePolicy;
+ }
+ } else if (untrustedHandler != null) {
+ if (cachePolicy != null) {
+ untrustedHandler.CachePolicy = cachePolicy;
+ }
+
+ untrustedHandler.IsSslRequired = requireSsl;
+ } else {
+ Logger.Http.DebugFormat("Unable to set cache policy on unsupported {0}.", handler.GetType().FullName);
+ }
+
+ return hostFactories.CreateHttpClient(handler);
+ }
+
+ internal static Uri GetDirectUriRequest(this HttpResponseMessage response) {
+ Requires.NotNull(response, "response");
+ Requires.Argument(
+ response.StatusCode == HttpStatusCode.Redirect || response.StatusCode == HttpStatusCode.RedirectKeepVerb
+ || response.StatusCode == HttpStatusCode.RedirectMethod || response.StatusCode == HttpStatusCode.TemporaryRedirect,
+ "response",
+ "Redirecting response expected.");
+ Requires.Argument(response.Headers.Location != null, "response", "Redirect URL header expected.");
+ Requires.Argument(response.Content == null || response.Content is FormUrlEncodedContent, "response", "FormUrlEncodedContent expected");
+
+ var builder = new UriBuilder(response.Headers.Location);
+ if (response.Content != null) {
+ var content = response.Content.ReadAsStringAsync();
+ Assumes.True(content.IsCompleted); // cached in memory, so it should never complete asynchronously.
+ var formFields = HttpUtility.ParseQueryString(content.Result).ToDictionary();
+ MessagingUtilities.AppendQueryArgs(builder, formFields);
+ }
+
+ return builder.Uri;
+ }
+
/// <summary>
/// Gets the extension factories from the extension aggregator on an OpenID channel.
/// </summary>
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs
index 4a464b9..0b96f7a 100644
--- a/src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Provider/IHostProcessedRequest.cs
@@ -6,6 +6,8 @@
namespace DotNetOpenAuth.OpenId.Provider {
using System;
+ using System.Net.Http;
+ using System.Threading.Tasks;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId.Messages;
using Validation;
@@ -53,6 +55,6 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <para>Return URL verification is only attempted if this method is called.</para>
/// <para>See OpenID Authentication 2.0 spec section 9.2.1.</para>
/// </remarks>
- RelyingPartyDiscoveryResult IsReturnUrlDiscoverable(IDirectWebRequestHandler webRequestHandler);
+ Task<RelyingPartyDiscoveryResult> IsReturnUrlDiscoverableAsync(HttpMessageHandler webRequestHandler);
}
}
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/Realm.cs b/src/DotNetOpenAuth.OpenId/OpenId/Realm.cs
index c1a959e..eaf8088 100644
--- a/src/DotNetOpenAuth.OpenId/OpenId/Realm.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/Realm.cs
@@ -12,7 +12,10 @@ namespace DotNetOpenAuth.OpenId {
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
+ using System.Net.Http;
using System.Text.RegularExpressions;
+ using System.Threading;
+ using System.Threading.Tasks;
using System.Web;
using System.Xml;
using DotNetOpenAuth.Messaging;
@@ -415,15 +418,16 @@ namespace DotNetOpenAuth.OpenId {
/// Searches for an XRDS document at the realm URL, and if found, searches
/// for a description of a relying party endpoints (OpenId login pages).
/// </summary>
- /// <param name="requestHandler">The mechanism to use for sending HTTP requests.</param>
+ /// <param name="hostFactories">The host factories.</param>
/// <param name="allowRedirects">Whether redirects may be followed when discovering the Realm.
/// This may be true when creating an unsolicited assertion, but must be
/// false when performing return URL verification per 2.0 spec section 9.2.1.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// The details of the endpoints if found; or <c>null</c> if no service document was discovered.
/// </returns>
- internal virtual IEnumerable<RelyingPartyEndpointDescription> DiscoverReturnToEndpoints(IDirectWebRequestHandler requestHandler, bool allowRedirects) {
- XrdsDocument xrds = this.Discover(requestHandler, allowRedirects);
+ internal virtual async Task<IEnumerable<RelyingPartyEndpointDescription>> DiscoverReturnToEndpointsAsync(IHostFactories hostFactories, bool allowRedirects, CancellationToken cancellationToken) {
+ XrdsDocument xrds = await this.DiscoverAsync(hostFactories, allowRedirects, cancellationToken);
if (xrds != null) {
return xrds.FindRelyingPartyReceivingEndpoints();
}
@@ -441,9 +445,9 @@ namespace DotNetOpenAuth.OpenId {
/// <returns>
/// The XRDS document if found; or <c>null</c> if no service document was discovered.
/// </returns>
- internal virtual XrdsDocument Discover(IDirectWebRequestHandler requestHandler, bool allowRedirects) {
+ internal virtual async Task<XrdsDocument> DiscoverAsync(IHostFactories hostFactories, bool allowRedirects, CancellationToken cancellationToken) {
// Attempt YADIS discovery
- DiscoveryResult yadisResult = Yadis.Discover(requestHandler, this.UriWithWildcardChangedToWww, false);
+ DiscoveryResult yadisResult = await Yadis.DiscoverAsync(hostFactories, this.UriWithWildcardChangedToWww, false, cancellationToken);
if (yadisResult != null) {
// Detect disallowed redirects, since realm discovery never allows them for security.
ErrorUtilities.VerifyProtocol(allowRedirects || yadisResult.NormalizedUri == yadisResult.RequestUri, OpenIdStrings.RealmCausedRedirectUponDiscovery, yadisResult.RequestUri);
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequest.cs b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequest.cs
index 886029c..35a92e1 100644
--- a/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequest.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/RelyingParty/IAuthenticationRequest.cs
@@ -8,6 +8,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
using System;
using System.Collections.Generic;
using System.Linq;
+ using System.Net.Http;
using System.Text;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId.Messages;
@@ -27,7 +28,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// Gets the HTTP response the relying party should send to the user agent
/// to redirect it to the OpenID Provider to start the OpenID authentication process.
/// </summary>
- OutgoingWebResponse RedirectingResponse { get; }
+ HttpResponseMessage RedirectingResponse { get; }
/// <summary>
/// Gets the URL that the user agent will return to after authentication
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/UntrustedWebRequestHandler.cs b/src/DotNetOpenAuth.OpenId/OpenId/UntrustedWebRequestHandler.cs
new file mode 100644
index 0000000..c61ac7f
--- /dev/null
+++ b/src/DotNetOpenAuth.OpenId/OpenId/UntrustedWebRequestHandler.cs
@@ -0,0 +1,405 @@
+//-----------------------------------------------------------------------
+// <copyright file="UntrustedWebRequestHandler.cs" company="Outercurve Foundation">
+// Copyright (c) Outercurve Foundation. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Globalization;
+ using System.IO;
+ using System.Net;
+ using System.Net.Cache;
+ using System.Net.Http;
+ using System.Text.RegularExpressions;
+ using System.Threading;
+ using System.Threading.Tasks;
+ using DotNetOpenAuth.Configuration;
+ using DotNetOpenAuth.Messaging;
+ using Validation;
+
+ /// <summary>
+ /// A paranoid HTTP get/post request engine. It helps to protect against attacks from remote
+ /// server leaving dangling connections, sending too much data, causing requests against
+ /// internal servers, etc.
+ /// </summary>
+ /// <remarks>
+ /// Protections include:
+ /// * Conservative maximum time to receive the complete response.
+ /// * Only HTTP and HTTPS schemes are permitted.
+ /// * Internal IP address ranges are not permitted: 127.*.*.*, 1::*
+ /// * Internal host names are not permitted (periods must be found in the host name)
+ /// If a particular host would be permitted but is in the blacklist, it is not allowed.
+ /// If a particular host would not be permitted but is in the whitelist, it is allowed.
+ /// </remarks>
+ public class UntrustedWebRequestHandler : HttpMessageHandler {
+ /// <summary>
+ /// The set of URI schemes allowed in untrusted web requests.
+ /// </summary>
+ private ICollection<string> allowableSchemes = new List<string> { "http", "https" };
+
+ /// <summary>
+ /// The collection of blacklisted hosts.
+ /// </summary>
+ private ICollection<string> blacklistHosts = new List<string>(Configuration.BlacklistHosts.KeysAsStrings);
+
+ /// <summary>
+ /// The collection of regular expressions used to identify additional blacklisted hosts.
+ /// </summary>
+ private ICollection<Regex> blacklistHostsRegex = new List<Regex>(Configuration.BlacklistHostsRegex.KeysAsRegexs);
+
+ /// <summary>
+ /// The collection of whitelisted hosts.
+ /// </summary>
+ private ICollection<string> whitelistHosts = new List<string>(Configuration.WhitelistHosts.KeysAsStrings);
+
+ /// <summary>
+ /// The collection of regular expressions used to identify additional whitelisted hosts.
+ /// </summary>
+ private ICollection<Regex> whitelistHostsRegex = new List<Regex>(Configuration.WhitelistHostsRegex.KeysAsRegexs);
+
+ /// <summary>
+ /// The maximum redirections to follow in the course of a single request.
+ /// </summary>
+ [DebuggerBrowsable(DebuggerBrowsableState.Never)]
+ private int maximumRedirections = Configuration.MaximumRedirections;
+
+ private readonly InternalWebRequestHandler innerHandler;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UntrustedWebRequestHandler" /> class.
+ /// </summary>
+ /// <param name="innerHandler">
+ /// The inner handler. This handler will be modified to suit the purposes of this wrapping handler,
+ /// and should not be used independently of this wrapper after construction of this object.
+ /// </param>
+ public UntrustedWebRequestHandler(WebRequestHandler innerHandler = null) {
+ this.innerHandler = new InternalWebRequestHandler(innerHandler ?? new WebRequestHandler());
+
+ // If SSL is required throughout, we cannot allow auto redirects because
+ // it may include a pass through an unprotected HTTP request.
+ // We have to follow redirects manually.
+ // It also allows us to ignore HttpWebResponse.FinalUri since that can be affected by
+ // the Content-Location header and open security holes.
+ this.MaxAutomaticRedirections = Configuration.MaximumRedirections;
+ this.InnerWebRequestHandler.AllowAutoRedirect = false;
+
+ if (Debugger.IsAttached) {
+ // Since a debugger is attached, requests may be MUCH slower,
+ // so give ourselves huge timeouts.
+ this.InnerWebRequestHandler.ReadWriteTimeout = (int)TimeSpan.FromHours(1).TotalMilliseconds;
+ } else {
+ this.InnerWebRequestHandler.ReadWriteTimeout = (int)Configuration.ReadWriteTimeout.TotalMilliseconds;
+ }
+ }
+
+ protected WebRequestHandler InnerWebRequestHandler {
+ get { return (WebRequestHandler)this.innerHandler.InnerHandler; }
+ }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether all requests must use SSL.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if SSL is required; otherwise, <c>false</c>.
+ /// </value>
+ public bool IsSslRequired { get; set; }
+
+ /// <summary>
+ /// Gets or sets the cache policy.
+ /// </summary>
+ public RequestCachePolicy CachePolicy {
+ get { return this.InnerWebRequestHandler.CachePolicy; }
+ set { this.InnerWebRequestHandler.CachePolicy = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the total number of redirections to allow on any one request.
+ /// Default is 10.
+ /// </summary>
+ public int MaxAutomaticRedirections {
+ get {
+ return this.maximumRedirections;
+ }
+
+ set {
+ Requires.Range(value >= 0, "value");
+ this.maximumRedirections = value;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the time (in milliseconds) allowed to wait for single read or write operation to complete.
+ /// Default is 500 milliseconds.
+ /// </summary>
+ public int ReadWriteTimeout {
+ get { return this.InnerWebRequestHandler.ReadWriteTimeout; }
+ set { this.InnerWebRequestHandler.ReadWriteTimeout = value; }
+ }
+
+ /// <summary>
+ /// Gets a collection of host name literals that should be allowed even if they don't
+ /// pass standard security checks.
+ /// </summary>
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Whitelist",
+ Justification = "Spelling as intended.")]
+ public ICollection<string> WhitelistHosts {
+ get {
+ return this.whitelistHosts;
+ }
+ }
+
+ /// <summary>
+ /// Gets a collection of host name regular expressions that indicate hosts that should
+ /// be allowed even though they don't pass standard security checks.
+ /// </summary>
+ [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Whitelist",
+ Justification = "Spelling as intended.")]
+ public ICollection<Regex> WhitelistHostsRegex {
+ get {
+ return this.whitelistHostsRegex;
+ }
+ }
+
+ /// <summary>
+ /// Gets a collection of host name literals that should be rejected even if they
+ /// pass standard security checks.
+ /// </summary>
+ public ICollection<string> BlacklistHosts {
+ get {
+ return this.blacklistHosts;
+ }
+ }
+
+ /// <summary>
+ /// Gets a collection of host name regular expressions that indicate hosts that should
+ /// be rejected even if they pass standard security checks.
+ /// </summary>
+ public ICollection<Regex> BlacklistHostsRegex {
+ get {
+ return this.blacklistHostsRegex;
+ }
+ }
+
+ /// <summary>
+ /// Gets the configuration for this class that is specified in the host's .config file.
+ /// </summary>
+ private static UntrustedWebRequestElement Configuration {
+ get { return DotNetOpenAuthSection.Messaging.UntrustedWebRequest; }
+ }
+
+ public HttpClient CreateClient() {
+ var client = new HttpClient(this);
+ client.MaxResponseContentBufferSize = Configuration.MaximumBytesToRead;
+
+ if (Debugger.IsAttached) {
+ // Since a debugger is attached, requests may be MUCH slower,
+ // so give ourselves huge timeouts.
+ client.Timeout = TimeSpan.FromHours(1);
+ } else {
+ client.Timeout = Configuration.Timeout;
+ }
+
+ return client;
+ }
+
+ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
+ this.EnsureAllowableRequestUri(request.RequestUri);
+
+ // Since we may require SSL for every redirect, we handle each redirect manually
+ // in order to detect and fail if any redirect sends us to an HTTP url.
+ // We COULD allow automatic redirect in the cases where HTTPS is not required,
+ // but our mock request infrastructure can't do redirects on its own either.
+ Uri originalRequestUri = request.RequestUri;
+ int i;
+ for (i = 0; i < this.MaxAutomaticRedirections; i++) {
+ this.EnsureAllowableRequestUri(request.RequestUri);
+ var response = await this.innerHandler.SendAsync(request, cancellationToken);
+ if (response.StatusCode == HttpStatusCode.MovedPermanently || response.StatusCode == HttpStatusCode.Redirect
+ || response.StatusCode == HttpStatusCode.RedirectMethod || response.StatusCode == HttpStatusCode.RedirectKeepVerb) {
+ // We have no copy of the post entity stream to repeat on our manually
+ // cloned HttpWebRequest, so we have to bail.
+ ErrorUtilities.VerifyProtocol(request.Method != HttpMethod.Post, MessagingStrings.UntrustedRedirectsOnPOSTNotSupported);
+ Uri redirectUri = new Uri(request.RequestUri, response.Headers.Location);
+ request = request.Clone(redirectUri);
+ } else {
+ return response;
+ }
+ }
+
+ throw ErrorUtilities.ThrowProtocol(MessagingStrings.TooManyRedirects, originalRequestUri);
+ }
+
+ /// <summary>
+ /// Determines whether an IP address is the IPv6 equivalent of "localhost/127.0.0.1".
+ /// </summary>
+ /// <param name="ip">The ip address to check.</param>
+ /// <returns>
+ /// <c>true</c> if this is a loopback IP address; <c>false</c> otherwise.
+ /// </returns>
+ private static bool IsIPv6Loopback(IPAddress ip) {
+ Requires.NotNull(ip, "ip");
+ byte[] addressBytes = ip.GetAddressBytes();
+ for (int i = 0; i < addressBytes.Length - 1; i++) {
+ if (addressBytes[i] != 0) {
+ return false;
+ }
+ }
+ if (addressBytes[addressBytes.Length - 1] != 1) {
+ return false;
+ }
+ return true;
+ }
+
+ /// <summary>
+ /// Determines whether the given host name is in a host list or host name regex list.
+ /// </summary>
+ /// <param name="host">The host name.</param>
+ /// <param name="stringList">The list of host names.</param>
+ /// <param name="regexList">The list of regex patterns of host names.</param>
+ /// <returns>
+ /// <c>true</c> if the specified host falls within at least one of the given lists; otherwise, <c>false</c>.
+ /// </returns>
+ private static bool IsHostInList(string host, ICollection<string> stringList, ICollection<Regex> regexList) {
+ Requires.NotNullOrEmpty(host, "host");
+ Requires.NotNull(stringList, "stringList");
+ Requires.NotNull(regexList, "regexList");
+ foreach (string testHost in stringList) {
+ if (string.Equals(host, testHost, StringComparison.OrdinalIgnoreCase)) {
+ return true;
+ }
+ }
+ foreach (Regex regex in regexList) {
+ if (regex.IsMatch(host)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /// <summary>
+ /// Determines whether a given host is whitelisted.
+ /// </summary>
+ /// <param name="host">The host name to test.</param>
+ /// <returns>
+ /// <c>true</c> if the host is whitelisted; otherwise, <c>false</c>.
+ /// </returns>
+ private bool IsHostWhitelisted(string host) {
+ return IsHostInList(host, this.WhitelistHosts, this.WhitelistHostsRegex);
+ }
+
+ /// <summary>
+ /// Determines whether a given host is blacklisted.
+ /// </summary>
+ /// <param name="host">The host name to test.</param>
+ /// <returns>
+ /// <c>true</c> if the host is blacklisted; otherwise, <c>false</c>.
+ /// </returns>
+ private bool IsHostBlacklisted(string host) {
+ return IsHostInList(host, this.BlacklistHosts, this.BlacklistHostsRegex);
+ }
+
+ /// <summary>
+ /// Verify that the request qualifies under our security policies
+ /// </summary>
+ /// <param name="requestUri">The request URI.</param>
+ /// <param name="requireSsl">If set to <c>true</c>, only web requests that can be made entirely over SSL will succeed.</param>
+ /// <exception cref="ProtocolException">Thrown when the URI is disallowed for security reasons.</exception>
+ private void EnsureAllowableRequestUri(Uri requestUri) {
+ ErrorUtilities.VerifyProtocol(
+ this.IsUriAllowable(requestUri), MessagingStrings.UnsafeWebRequestDetected, requestUri);
+ ErrorUtilities.VerifyProtocol(
+ !this.IsSslRequired || string.Equals(requestUri.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase),
+ MessagingStrings.InsecureWebRequestWithSslRequired,
+ requestUri);
+ }
+
+ /// <summary>
+ /// Determines whether a URI is allowed based on scheme and host name.
+ /// No requireSSL check is done here
+ /// </summary>
+ /// <param name="uri">The URI to test for whether it should be allowed.</param>
+ /// <returns>
+ /// <c>true</c> if [is URI allowable] [the specified URI]; otherwise, <c>false</c>.
+ /// </returns>
+ private bool IsUriAllowable(Uri uri) {
+ Requires.NotNull(uri, "uri");
+ if (!this.allowableSchemes.Contains(uri.Scheme)) {
+ Logger.Http.WarnFormat("Rejecting URL {0} because it uses a disallowed scheme.", uri);
+ return false;
+ }
+
+ // Allow for whitelist or blacklist to override our detection.
+ Func<string, bool> failsUnlessWhitelisted = (string reason) => {
+ if (IsHostWhitelisted(uri.DnsSafeHost)) {
+ return true;
+ }
+ Logger.Http.WarnFormat("Rejecting URL {0} because {1}.", uri, reason);
+ return false;
+ };
+
+ // Try to interpret the hostname as an IP address so we can test for internal
+ // IP address ranges. Note that IP addresses can appear in many forms
+ // (e.g. http://127.0.0.1, http://2130706433, http://0x0100007f, http://::1
+ // So we convert them to a canonical IPAddress instance, and test for all
+ // non-routable IP ranges: 10.*.*.*, 127.*.*.*, ::1
+ // Note that Uri.IsLoopback is very unreliable, not catching many of these variants.
+ IPAddress hostIPAddress;
+ if (IPAddress.TryParse(uri.DnsSafeHost, out hostIPAddress)) {
+ byte[] addressBytes = hostIPAddress.GetAddressBytes();
+
+ // The host is actually an IP address.
+ switch (hostIPAddress.AddressFamily) {
+ case System.Net.Sockets.AddressFamily.InterNetwork:
+ if (addressBytes[0] == 127 || addressBytes[0] == 10) {
+ return failsUnlessWhitelisted("it is a loopback address.");
+ }
+ break;
+ case System.Net.Sockets.AddressFamily.InterNetworkV6:
+ if (IsIPv6Loopback(hostIPAddress)) {
+ return failsUnlessWhitelisted("it is a loopback address.");
+ }
+ break;
+ default:
+ return failsUnlessWhitelisted("it does not use an IPv4 or IPv6 address.");
+ }
+ } else {
+ // The host is given by name. We require names to contain periods to
+ // help make sure it's not an internal address.
+ if (!uri.Host.Contains(".")) {
+ return failsUnlessWhitelisted("it does not contain a period in the host name.");
+ }
+ }
+ if (this.IsHostBlacklisted(uri.DnsSafeHost)) {
+ Logger.Http.WarnFormat("Rejected URL {0} because it is blacklisted.", uri);
+ return false;
+ }
+ return true;
+ }
+
+ /// <summary>
+ /// A <see cref="DelegatingHandler"/> derived type that makes its SendAsync method available internally.
+ /// </summary>
+ private class InternalWebRequestHandler : DelegatingHandler {
+ internal InternalWebRequestHandler(HttpMessageHandler innerHandler)
+ : base(innerHandler) {
+ }
+
+ /// <summary>
+ /// Creates an instance of <see cref="T:System.Net.Http.HttpResponseMessage" /> based on the information provided in the <see cref="T:System.Net.Http.HttpRequestMessage" /> as an operation that will not block.
+ /// </summary>
+ /// <param name="request">The HTTP request message.</param>
+ /// <param name="cancellationToken">A cancellation token to cancel the operation.</param>
+ /// <returns>
+ /// Returns <see cref="T:System.Threading.Tasks.Task`1" />.The task object representing the asynchronous operation.
+ /// </returns>
+ protected internal new Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
+ return base.SendAsync(request, cancellationToken);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/UriDiscoveryService.cs b/src/DotNetOpenAuth.OpenId/OpenId/UriDiscoveryService.cs
index c262ac9..25eebe6 100644
--- a/src/DotNetOpenAuth.OpenId/OpenId/UriDiscoveryService.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/UriDiscoveryService.cs
@@ -8,14 +8,19 @@ namespace DotNetOpenAuth.OpenId {
using System;
using System.Collections.Generic;
using System.Linq;
+ using System.Net.Http;
+ using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
+ using System.Threading;
+ using System.Threading.Tasks;
using System.Web.UI.HtmlControls;
using System.Xml;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.Xrds;
using DotNetOpenAuth.Yadis;
+ using Validation;
/// <summary>
/// The discovery service for URI identifiers.
@@ -24,10 +29,14 @@ namespace DotNetOpenAuth.OpenId {
/// <summary>
/// Initializes a new instance of the <see cref="UriDiscoveryService"/> class.
/// </summary>
- public UriDiscoveryService() {
+ public UriDiscoveryService(IHostFactories hostFactories) {
+ Requires.NotNull(hostFactories, "hostFactories");
+ this.HostFactories = hostFactories;
}
- #region IDiscoveryService Members
+ public IHostFactories HostFactories { get; private set; }
+
+ #region IIdentifierDiscoveryService Members
/// <summary>
/// Performs discovery on the specified identifier.
@@ -38,17 +47,20 @@ namespace DotNetOpenAuth.OpenId {
/// <returns>
/// A sequence of service endpoints yielded by discovery. Must not be null, but may be empty.
/// </returns>
- public IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain) {
- abortDiscoveryChain = false;
+ public async Task<IdentifierDiscoveryServiceResult> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken) {
+ Requires.NotNull(identifier, "identifier");
+ cancellationToken.ThrowIfCancellationRequested();
+
var uriIdentifier = identifier as UriIdentifier;
if (uriIdentifier == null) {
- return Enumerable.Empty<IdentifierDiscoveryResult>();
+ return new IdentifierDiscoveryServiceResult(Enumerable.Empty<IdentifierDiscoveryResult>());
}
var endpoints = new List<IdentifierDiscoveryResult>();
// Attempt YADIS discovery
- DiscoveryResult yadisResult = Yadis.Discover(requestHandler, uriIdentifier, identifier.IsDiscoverySecureEndToEnd);
+ DiscoveryResult yadisResult = await Yadis.DiscoverAsync(this.HostFactories, uriIdentifier, identifier.IsDiscoverySecureEndToEnd, cancellationToken);
+ cancellationToken.ThrowIfCancellationRequested();
if (yadisResult != null) {
if (yadisResult.IsXrds) {
try {
@@ -67,7 +79,7 @@ namespace DotNetOpenAuth.OpenId {
// Failing YADIS discovery of an XRDS document, we try HTML discovery.
if (endpoints.Count == 0) {
- yadisResult.TryRevertToHtmlResponse();
+ await yadisResult.TryRevertToHtmlResponseAsync();
var htmlEndpoints = new List<IdentifierDiscoveryResult>(DiscoverFromHtml(yadisResult.NormalizedUri, uriIdentifier, yadisResult.ResponseText));
if (htmlEndpoints.Any()) {
Logger.Yadis.DebugFormat("Total services discovered in HTML: {0}", htmlEndpoints.Count);
@@ -83,7 +95,8 @@ namespace DotNetOpenAuth.OpenId {
Logger.Yadis.Debug("Skipping HTML discovery because XRDS contained service endpoints.");
}
}
- return endpoints;
+
+ return new IdentifierDiscoveryServiceResult(endpoints);
}
#endregion
diff --git a/src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs b/src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs
index a3e8345..0f9b746 100644
--- a/src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs
+++ b/src/DotNetOpenAuth.OpenId/OpenId/XriDiscoveryProxyService.cs
@@ -10,7 +10,11 @@ namespace DotNetOpenAuth.OpenId {
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
+ using System.Net.Http;
+ using System.Runtime.CompilerServices;
using System.Text;
+ using System.Threading;
+ using System.Threading.Tasks;
using System.Xml;
using DotNetOpenAuth.Configuration;
using DotNetOpenAuth.Messaging;
@@ -39,28 +43,34 @@ namespace DotNetOpenAuth.OpenId {
/// <summary>
/// Initializes a new instance of the <see cref="XriDiscoveryProxyService"/> class.
/// </summary>
- public XriDiscoveryProxyService() {
+ public XriDiscoveryProxyService(IHostFactories hostFactories) {
+ Requires.NotNull(hostFactories, "hostFactories");
+ this.HostFactories = hostFactories;
}
+ public IHostFactories HostFactories { get; private set; }
+
#region IDiscoveryService Members
/// <summary>
/// Performs discovery on the specified identifier.
/// </summary>
/// <param name="identifier">The identifier to perform discovery on.</param>
- /// <param name="requestHandler">The means to place outgoing HTTP requests.</param>
- /// <param name="abortDiscoveryChain">if set to <c>true</c>, no further discovery services will be called for this identifier.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>
/// A sequence of service endpoints yielded by discovery. Must not be null, but may be empty.
/// </returns>
- public IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain) {
- abortDiscoveryChain = false;
+ public async Task<IdentifierDiscoveryServiceResult> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken) {
+ Requires.NotNull(identifier, "identifier");
+
var xriIdentifier = identifier as XriIdentifier;
if (xriIdentifier == null) {
- return Enumerable.Empty<IdentifierDiscoveryResult>();
+ return new IdentifierDiscoveryServiceResult(Enumerable.Empty<IdentifierDiscoveryResult>());
}
- return DownloadXrds(xriIdentifier, requestHandler).XrdElements.CreateServiceEndpoints(xriIdentifier);
+ var xrds = await DownloadXrdsAsync(xriIdentifier, this.HostFactories, cancellationToken);
+ var endpoints = xrds.XrdElements.CreateServiceEndpoints(xriIdentifier);
+ return new IdentifierDiscoveryServiceResult(endpoints);
}
#endregion
@@ -71,14 +81,19 @@ namespace DotNetOpenAuth.OpenId {
/// <param name="identifier">The identifier.</param>
/// <param name="requestHandler">The request handler.</param>
/// <returns>The XRDS document.</returns>
- private static XrdsDocument DownloadXrds(XriIdentifier identifier, IDirectWebRequestHandler requestHandler) {
+ private static async Task<XrdsDocument> DownloadXrdsAsync(XriIdentifier identifier, IHostFactories hostFactories, CancellationToken cancellationToken) {
Requires.NotNull(identifier, "identifier");
- Requires.NotNull(requestHandler, "requestHandler");
+ Requires.NotNull(hostFactories, "hostFactories");
+
XrdsDocument doc;
- using (var xrdsResponse = Yadis.Request(requestHandler, GetXrdsUrl(identifier), identifier.IsDiscoverySecureEndToEnd)) {
+ using (var xrdsResponse = await Yadis.RequestAsync(GetXrdsUrl(identifier), identifier.IsDiscoverySecureEndToEnd, hostFactories, cancellationToken)) {
var readerSettings = MessagingUtilities.CreateUntrustedXmlReaderSettings();
- doc = new XrdsDocument(XmlReader.Create(xrdsResponse.ResponseStream, readerSettings));
+ await xrdsResponse.Content.LoadIntoBufferAsync();
+ using (var xrdsStream = await xrdsResponse.Content.ReadAsStreamAsync()) {
+ doc = new XrdsDocument(XmlReader.Create(xrdsStream, readerSettings));
+ }
}
+
ErrorUtilities.VerifyProtocol(doc.IsXrdResolutionSuccessful, OpenIdStrings.XriResolutionFailed);
return doc;
}
diff --git a/src/DotNetOpenAuth.OpenId/Yadis/DiscoveryResult.cs b/src/DotNetOpenAuth.OpenId/Yadis/DiscoveryResult.cs
index 06c6fc7..64f7b66 100644
--- a/src/DotNetOpenAuth.OpenId/Yadis/DiscoveryResult.cs
+++ b/src/DotNetOpenAuth.OpenId/Yadis/DiscoveryResult.cs
@@ -7,10 +7,15 @@
namespace DotNetOpenAuth.Yadis {
using System;
using System.IO;
+ using System.Net;
+ using System.Net.Http;
+ using System.Net.Http.Headers;
using System.Net.Mime;
+ using System.Threading.Tasks;
using System.Web.UI.HtmlControls;
using System.Xml;
using DotNetOpenAuth.Messaging;
+ using Validation;
/// <summary>
/// Contains the result of YADIS discovery.
@@ -20,7 +25,7 @@ namespace DotNetOpenAuth.Yadis {
/// The original web response, backed up here if the final web response is the preferred response to use
/// in case it turns out to not work out.
/// </summary>
- private CachedDirectWebResponse htmlFallback;
+ private HttpResponseMessage htmlFallback;
/// <summary>
/// Initializes a new instance of the <see cref="DiscoveryResult"/> class.
@@ -28,22 +33,7 @@ namespace DotNetOpenAuth.Yadis {
/// <param name="requestUri">The user-supplied identifier.</param>
/// <param name="initialResponse">The initial response.</param>
/// <param name="finalResponse">The final response.</param>
- public DiscoveryResult(Uri requestUri, CachedDirectWebResponse initialResponse, CachedDirectWebResponse finalResponse) {
- this.RequestUri = requestUri;
- this.NormalizedUri = initialResponse.FinalUri;
- if (finalResponse == null || finalResponse.Status != System.Net.HttpStatusCode.OK) {
- this.ApplyHtmlResponse(initialResponse);
- } else {
- this.ContentType = finalResponse.ContentType;
- this.ResponseText = finalResponse.GetResponseString();
- this.IsXrds = true;
- if (initialResponse != finalResponse) {
- this.YadisLocation = finalResponse.RequestUri;
- }
-
- // Back up the initial HTML response in case the XRDS is not useful.
- this.htmlFallback = initialResponse;
- }
+ private DiscoveryResult() {
}
/// <summary>
@@ -68,7 +58,7 @@ namespace DotNetOpenAuth.Yadis {
/// <summary>
/// Gets the Content-Type associated with the <see cref="ResponseText"/>.
/// </summary>
- public ContentType ContentType { get; private set; }
+ public MediaTypeHeaderValue ContentType { get; private set; }
/// <summary>
/// Gets the text in the final response.
@@ -83,12 +73,35 @@ namespace DotNetOpenAuth.Yadis {
/// </summary>
public bool IsXrds { get; private set; }
+ internal static async Task<DiscoveryResult> CreateAsync(
+ Uri requestUri, HttpResponseMessage initialResponse, HttpResponseMessage finalResponse) {
+
+ var result = new DiscoveryResult();
+ result.RequestUri = requestUri;
+ result.NormalizedUri = initialResponse.RequestMessage.RequestUri;
+ if (finalResponse == null || finalResponse.StatusCode != HttpStatusCode.OK) {
+ await result.ApplyHtmlResponseAsync(initialResponse);
+ } else {
+ result.ContentType = finalResponse.Content.Headers.ContentType;
+ result.ResponseText = await finalResponse.Content.ReadAsStringAsync();
+ result.IsXrds = true;
+ if (initialResponse != finalResponse) {
+ result.YadisLocation = finalResponse.RequestMessage.RequestUri;
+ }
+
+ // Back up the initial HTML response in case the XRDS is not useful.
+ result.htmlFallback = initialResponse;
+ }
+
+ return result;
+ }
+
/// <summary>
/// Reverts to the HTML response after the XRDS response didn't work out.
/// </summary>
- internal void TryRevertToHtmlResponse() {
+ internal async Task TryRevertToHtmlResponseAsync() {
if (this.htmlFallback != null) {
- this.ApplyHtmlResponse(this.htmlFallback);
+ await this.ApplyHtmlResponseAsync(this.htmlFallback);
this.htmlFallback = null;
}
}
@@ -96,10 +109,12 @@ namespace DotNetOpenAuth.Yadis {
/// <summary>
/// Applies the HTML response to the object.
/// </summary>
- /// <param name="initialResponse">The initial response.</param>
- private void ApplyHtmlResponse(CachedDirectWebResponse initialResponse) {
- this.ContentType = initialResponse.ContentType;
- this.ResponseText = initialResponse.GetResponseString();
+ /// <param name="response">The initial response.</param>
+ private async Task ApplyHtmlResponseAsync(HttpResponseMessage response) {
+ Requires.NotNull(response, "response");
+
+ this.ContentType = response.Content.Headers.ContentType;
+ this.ResponseText = await response.Content.ReadAsStringAsync();
this.IsXrds = this.ContentType != null && this.ContentType.MediaType == ContentTypes.Xrds;
}
}
diff --git a/src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs b/src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs
index 4a06ea7..f0d5402 100644
--- a/src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs
+++ b/src/DotNetOpenAuth.OpenId/Yadis/Yadis.cs
@@ -9,6 +9,10 @@ namespace DotNetOpenAuth.Yadis {
using System.IO;
using System.Net;
using System.Net.Cache;
+ using System.Net.Http;
+ using System.Net.Http.Headers;
+ using System.Threading;
+ using System.Threading.Tasks;
using System.Web.UI.HtmlControls;
using System.Xml;
using DotNetOpenAuth.Configuration;
@@ -17,6 +21,9 @@ namespace DotNetOpenAuth.Yadis {
using DotNetOpenAuth.Xrds;
using Validation;
+ using System.Linq;
+ using System.Collections.Generic;
+
/// <summary>
/// YADIS discovery manager.
/// </summary>
@@ -53,16 +60,21 @@ namespace DotNetOpenAuth.Yadis {
/// or if <paramref name="requireSsl"/> is true but part of discovery
/// is not protected by SSL.
/// </returns>
- public static DiscoveryResult Discover(IDirectWebRequestHandler requestHandler, UriIdentifier uri, bool requireSsl) {
- CachedDirectWebResponse response;
+ public static async Task<DiscoveryResult> DiscoverAsync(IHostFactories hostFactories, UriIdentifier uri, bool requireSsl, CancellationToken cancellationToken) {
+ Requires.NotNull(hostFactories, "hostFactories");
+ Requires.NotNull(uri, "uri");
+
+ HttpResponseMessage response;
try {
if (requireSsl && !string.Equals(uri.Uri.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) {
Logger.Yadis.WarnFormat("Discovery on insecure identifier '{0}' aborted.", uri);
return null;
}
- response = Request(requestHandler, uri, requireSsl, ContentTypes.Html, ContentTypes.XHtml, ContentTypes.Xrds).GetSnapshot(MaximumResultToScan);
- if (response.Status != System.Net.HttpStatusCode.OK) {
- Logger.Yadis.ErrorFormat("HTTP error {0} {1} while performing discovery on {2}.", (int)response.Status, response.Status, uri);
+
+ response = await RequestAsync(uri, requireSsl, hostFactories, cancellationToken, ContentTypes.Html, ContentTypes.XHtml, ContentTypes.Xrds);
+ await response.Content.LoadIntoBufferAsync();
+ if (response.StatusCode != System.Net.HttpStatusCode.OK) {
+ Logger.Yadis.ErrorFormat("HTTP error {0} {1} while performing discovery on {2}.", (int)response.StatusCode, response.StatusCode, uri);
return null;
}
} catch (ArgumentException ex) {
@@ -70,13 +82,18 @@ namespace DotNetOpenAuth.Yadis {
Logger.Yadis.WarnFormat("Unsafe OpenId URL detected ({0}). Request aborted. {1}", uri, ex);
return null;
}
- CachedDirectWebResponse response2 = null;
- if (IsXrdsDocument(response)) {
+ HttpResponseMessage response2 = null;
+ if (await IsXrdsDocumentAsync(response)) {
Logger.Yadis.Debug("An XRDS response was received from GET at user-supplied identifier.");
Reporting.RecordEventOccurrence("Yadis", "XRDS in initial response");
response2 = response;
} else {
- string uriString = response.Headers.Get(HeaderName);
+ IEnumerable<string> uriStrings;
+ string uriString = null;
+ if (response.Headers.TryGetValues(HeaderName, out uriStrings)) {
+ uriString = uriStrings.FirstOrDefault();
+ }
+
Uri url = null;
if (uriString != null) {
if (Uri.TryCreate(uriString, UriKind.Absolute, out url)) {
@@ -84,8 +101,10 @@ namespace DotNetOpenAuth.Yadis {
Reporting.RecordEventOccurrence("Yadis", "XRDS referenced in HTTP header");
}
}
- if (url == null && response.ContentType != null && (response.ContentType.MediaType == ContentTypes.Html || response.ContentType.MediaType == ContentTypes.XHtml)) {
- url = FindYadisDocumentLocationInHtmlMetaTags(response.GetResponseString());
+
+ var contentType = response.Content.Headers.ContentType;
+ if (url == null && contentType != null && (contentType.MediaType == ContentTypes.Html || contentType.MediaType == ContentTypes.XHtml)) {
+ url = FindYadisDocumentLocationInHtmlMetaTags(await response.Content.ReadAsStringAsync());
if (url != null) {
Logger.Yadis.DebugFormat("{0} found in HTML Http-Equiv tag. Preparing to pull XRDS from {1}", HeaderName, url);
Reporting.RecordEventOccurrence("Yadis", "XRDS referenced in HTML");
@@ -93,16 +112,17 @@ namespace DotNetOpenAuth.Yadis {
}
if (url != null) {
if (!requireSsl || string.Equals(url.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) {
- response2 = Request(requestHandler, url, requireSsl, ContentTypes.Xrds).GetSnapshot(MaximumResultToScan);
- if (response2.Status != HttpStatusCode.OK) {
- Logger.Yadis.ErrorFormat("HTTP error {0} {1} while performing discovery on {2}.", (int)response2.Status, response2.Status, uri);
+ response2 = await RequestAsync(url, requireSsl, hostFactories, cancellationToken, ContentTypes.Xrds);
+ if (response2.StatusCode != HttpStatusCode.OK) {
+ Logger.Yadis.ErrorFormat("HTTP error {0} {1} while performing discovery on {2}.", (int)response2.StatusCode, response2.StatusCode, uri);
}
} else {
Logger.Yadis.WarnFormat("XRDS document at insecure location '{0}'. Aborting YADIS discovery.", url);
}
}
}
- return new DiscoveryResult(uri, response, response2);
+
+ return await DiscoveryResult.CreateAsync(uri, response, response2);
}
/// <summary>
@@ -129,43 +149,46 @@ namespace DotNetOpenAuth.Yadis {
/// <summary>
/// Sends a YADIS HTTP request as part of identifier discovery.
/// </summary>
- /// <param name="requestHandler">The request handler to use to actually submit the request.</param>
/// <param name="uri">The URI to GET.</param>
/// <param name="requireSsl">Whether only HTTPS URLs should ever be retrieved.</param>
+ /// <param name="hostFactories">The host factories.</param>
+ /// <param name="cancellationToken">The cancellation token.</param>
/// <param name="acceptTypes">The value of the Accept HTTP header to include in the request.</param>
- /// <returns>The HTTP response retrieved from the request.</returns>
- internal static IncomingWebResponse Request(IDirectWebRequestHandler requestHandler, Uri uri, bool requireSsl, params string[] acceptTypes) {
- Requires.NotNull(requestHandler, "requestHandler");
+ /// <returns>
+ /// The HTTP response retrieved from the request.
+ /// </returns>
+ internal static async Task<HttpResponseMessage> RequestAsync(Uri uri, bool requireSsl, IHostFactories hostFactories, CancellationToken cancellationToken, params string[] acceptTypes) {
Requires.NotNull(uri, "uri");
+ Requires.NotNull(hostFactories, "hostFactories");
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
- request.CachePolicy = IdentifierDiscoveryCachePolicy;
- if (acceptTypes != null) {
- request.Accept = string.Join(",", acceptTypes);
- }
-
- DirectWebRequestOptions options = DirectWebRequestOptions.None;
- if (requireSsl) {
- options |= DirectWebRequestOptions.RequireSsl;
- }
+ using (var httpClient = hostFactories.CreateHttpClient(requireSsl, IdentifierDiscoveryCachePolicy)) {
+ var request = new HttpRequestMessage(HttpMethod.Get, uri);
+ if (acceptTypes != null) {
+ request.Headers.Accept.AddRange(acceptTypes.Select(at => new MediaTypeWithQualityHeaderValue(at)));
+ }
- try {
- return requestHandler.GetResponse(request, options);
- } catch (ProtocolException ex) {
- var webException = ex.InnerException as WebException;
- if (webException != null) {
- var response = webException.Response as HttpWebResponse;
- if (response != null && response.IsFromCache) {
+ HttpResponseMessage response = null;
+ try {
+ response = await httpClient.SendAsync(request, cancellationToken);
+ // http://stackoverflow.com/questions/14103154/how-to-determine-if-an-httpresponsemessage-was-fulfilled-from-cache-using-httpcl
+ if (!response.IsSuccessStatusCode && response.Headers.Age.HasValue && response.Headers.Age.Value > TimeSpan.Zero) {
// We don't want to report error responses from the cache, since the server may have fixed
// whatever was causing the problem. So try again with cache disabled.
- Logger.Messaging.Error("An HTTP error response was obtained from the cache. Retrying with cache disabled.", ex);
+ Logger.Messaging.ErrorFormat("An HTTP {0} response was obtained from the cache. Retrying with cache disabled.", response.StatusCode);
+ response.Dispose(); // discard the old one
+
var nonCachingRequest = request.Clone();
- nonCachingRequest.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Reload);
- return requestHandler.GetResponse(nonCachingRequest, options);
+ using (var nonCachingHttpClient = hostFactories.CreateHttpClient(requireSsl, new RequestCachePolicy(RequestCacheLevel.Reload))) {
+ response = await nonCachingHttpClient.SendAsync(nonCachingRequest, cancellationToken);
+ }
}
- }
- throw;
+ response.EnsureSuccessStatusCode();
+ return response;
+ } catch {
+ response.DisposeIfNotNull();
+ throw;
+ }
}
}
@@ -176,25 +199,26 @@ namespace DotNetOpenAuth.Yadis {
/// <returns>
/// <c>true</c> if the response constains an XRDS document; otherwise, <c>false</c>.
/// </returns>
- private static bool IsXrdsDocument(CachedDirectWebResponse response) {
- if (response.ContentType == null) {
+ private static async Task<bool> IsXrdsDocumentAsync(HttpResponseMessage response) {
+ if (response.Content.Headers.ContentType == null) {
return false;
}
- if (response.ContentType.MediaType == ContentTypes.Xrds) {
+ if (response.Content.Headers.ContentType.MediaType == ContentTypes.Xrds) {
return true;
}
- if (response.ContentType.MediaType == ContentTypes.Xml) {
+ if (response.Content.Headers.ContentType.MediaType == ContentTypes.Xml) {
// This COULD be an XRDS document with an imprecise content-type.
- response.ResponseStream.Seek(0, SeekOrigin.Begin);
- var readerSettings = MessagingUtilities.CreateUntrustedXmlReaderSettings();
- XmlReader reader = XmlReader.Create(response.ResponseStream, readerSettings);
- while (reader.Read() && reader.NodeType != XmlNodeType.Element) {
- // intentionally blank
- }
- if (reader.NamespaceURI == XrdsNode.XrdsNamespace && reader.Name == "XRDS") {
- return true;
+ using (var responseStream = await response.Content.ReadAsStreamAsync()) {
+ var readerSettings = MessagingUtilities.CreateUntrustedXmlReaderSettings();
+ XmlReader reader = XmlReader.Create(responseStream, readerSettings);
+ while (await reader.ReadAsync() && reader.NodeType != XmlNodeType.Element) {
+ // intentionally blank
+ }
+ if (reader.NamespaceURI == XrdsNode.XrdsNamespace && reader.Name == "XRDS") {
+ return true;
+ }
}
}
diff --git a/src/DotNetOpenAuth.OpenId/packages.config b/src/DotNetOpenAuth.OpenId/packages.config
index 58890d8..1d93cf5 100644
--- a/src/DotNetOpenAuth.OpenId/packages.config
+++ b/src/DotNetOpenAuth.OpenId/packages.config
@@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
+ <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" />
<package id="Validation" version="2.0.1.12362" targetFramework="net45" />
</packages> \ No newline at end of file