diff options
Diffstat (limited to 'src/DotNetOAuth')
-rw-r--r-- | src/DotNetOAuth/DotNetOAuth.csproj | 3 | ||||
-rw-r--r-- | src/DotNetOAuth/Messaging/Channel.cs | 219 | ||||
-rw-r--r-- | src/DotNetOAuth/Messaging/ChannelProtection.cs | 41 | ||||
-rw-r--r-- | src/DotNetOAuth/Messaging/ExpiredMessageException.cs | 2 | ||||
-rw-r--r-- | src/DotNetOAuth/Messaging/IChannelBindingElement.cs | 36 | ||||
-rw-r--r-- | src/DotNetOAuth/Messaging/InvalidSignatureException.cs | 2 | ||||
-rw-r--r-- | src/DotNetOAuth/Messaging/MessagingStrings.Designer.cs | 18 | ||||
-rw-r--r-- | src/DotNetOAuth/Messaging/MessagingStrings.resx | 8 | ||||
-rw-r--r-- | src/DotNetOAuth/Messaging/MessagingUtilities.cs | 51 | ||||
-rw-r--r-- | src/DotNetOAuth/Messaging/ReplayedMessageException.cs | 2 | ||||
-rw-r--r-- | src/DotNetOAuth/Messaging/StandardMessageExpirationBindingElement.cs | 100 |
11 files changed, 348 insertions, 134 deletions
diff --git a/src/DotNetOAuth/DotNetOAuth.csproj b/src/DotNetOAuth/DotNetOAuth.csproj index fb41be1..253d4df 100644 --- a/src/DotNetOAuth/DotNetOAuth.csproj +++ b/src/DotNetOAuth/DotNetOAuth.csproj @@ -68,6 +68,8 @@ <ItemGroup>
<Compile Include="Consumer.cs" />
<Compile Include="IWebRequestHandler.cs" />
+ <Compile Include="Messaging\ChannelProtection.cs" />
+ <Compile Include="Messaging\IChannelBindingElement.cs" />
<Compile Include="Messaging\ReplayedMessageException.cs" />
<Compile Include="Messaging\ExpiredMessageException.cs" />
<Compile Include="Messaging\DataContractMemberComparer.cs" />
@@ -87,6 +89,7 @@ <DependentUpon>MessagingStrings.resx</DependentUpon>
</Compile>
<Compile Include="Messaging\MessagingUtilities.cs" />
+ <Compile Include="Messaging\StandardMessageExpirationBindingElement.cs" />
<Compile Include="OAuthChannel.cs" />
<Compile Include="Messaging\Response.cs" />
<Compile Include="Messaging\IProtocolMessage.cs" />
diff --git a/src/DotNetOAuth/Messaging/Channel.cs b/src/DotNetOAuth/Messaging/Channel.cs index 4d644c9..5d52b23 100644 --- a/src/DotNetOAuth/Messaging/Channel.cs +++ b/src/DotNetOAuth/Messaging/Channel.cs @@ -7,9 +7,11 @@ namespace DotNetOAuth.Messaging {
using System;
using System.Collections.Generic;
+ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
+ using System.Linq;
using System.Net;
using System.Text;
using System.Web;
@@ -57,36 +59,41 @@ namespace DotNetOAuth.Messaging { private Response queuedIndirectOrResponseMessage;
/// <summary>
+ /// A list of binding elements in the order they must be applied to outgoing messages.
+ /// </summary>
+ /// <remarks>
+ /// Incoming messages should have the binding elements applied in reverse order.
+ /// </remarks>
+ private List<IChannelBindingElement> bindingElements = new List<IChannelBindingElement>();
+
+ /// <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>
- protected Channel(IMessageTypeProvider messageTypeProvider) {
+ /// <param name="bindingElements">The binding elements to use in sending and receiving messages.</param>
+ protected Channel(IMessageTypeProvider messageTypeProvider, params IChannelBindingElement[] bindingElements) {
if (messageTypeProvider == null) {
throw new ArgumentNullException("messageTypeProvider");
}
- this.MaximumMessageAge = TimeSpan.FromMinutes(13);
this.messageTypeProvider = messageTypeProvider;
+ this.bindingElements = new List<IChannelBindingElement>(ValidateAndPrepareBindingElements(bindingElements));
}
/// <summary>
- /// Gets or sets the maximum age a message implementing the
- /// <see cref="IExpiringProtocolMessage"/> interface can be before
- /// being discarded as too old.
+ /// Gets the binding elements used by this channel, in the order they are applied to outgoing messages.
/// </summary>
- /// <value>The default value is 13 minutes.</value>
/// <remarks>
- /// This time limit should take into account expected time skew for servers
- /// across the Internet. For example, if a server could conceivably have its
- /// clock d = 5 minutes off UTC time, then any two servers could have
- /// their clocks disagree by as much as 2*d = 10 minutes.
- /// If a message should live for at least t = 3 minutes,
- /// this property should be set to (2*d + t) = 13 minutes.
+ /// Incoming messages are processed by this binding elements in the reverse order.
/// </remarks>
- protected internal TimeSpan MaximumMessageAge { get; set; }
+ protected internal ReadOnlyCollection<IChannelBindingElement> BindingElements {
+ get {
+ return this.bindingElements.AsReadOnly();
+ }
+ }
/// <summary>
/// Gets a tool that can figure out what kind of message is being received
@@ -338,56 +345,6 @@ namespace DotNetOAuth.Messaging { }
/// <summary>
- /// Signs a given message according to the rules of the channel.
- /// </summary>
- /// <param name="message">The message to sign.</param>
- protected virtual void Sign(ISignedProtocolMessage message) {
- Debug.Assert(message != null, "message == null");
- throw new NotSupportedException(MessagingStrings.SigningNotSupported);
- }
-
- /// <summary>
- /// Gets whether the signature of a signed message is valid or not
- /// according to the rules of the channel.
- /// </summary>
- /// <param name="message">The message whose signature should be verified.</param>
- /// <returns>True if the signature is valid. False otherwise.</returns>
- protected virtual bool IsSignatureValid(ISignedProtocolMessage message) {
- Debug.Assert(message != null, "message == null");
- throw new NotSupportedException(MessagingStrings.SigningNotSupported);
- }
-
- /// <summary>
- /// Applies replay protection on an outgoing message.
- /// </summary>
- /// <param name="message">The message to apply replay protection to.</param>
- /// <remarks>
- /// <para>Implementing this method typically involves generating and setting a nonce property
- /// on the message.</para>
- /// <para>
- /// At the time this method is called, the
- /// <see cref="IExpiringProtocolMessage.UtcCreationDate"/> property will already be
- /// set on the <paramref name="message"/>.</para>
- /// </remarks>
- protected virtual void ApplyReplayProtection(IReplayProtectedProtocolMessage message) {
- throw new NotSupportedException(MessagingStrings.ReplayProtectionNotSupported);
- }
-
- /// <summary>
- /// Gets whether this message has already been processed based on the
- /// replay protection applied by <see cref="ApplyReplayProtection"/>.
- /// </summary>
- /// <param name="message">The message to be checked against the list of recently received messages.</param>
- /// <returns>True if the message has already been processed. False otherwise.</returns>
- /// <remarks>
- /// An exception should NOT be thrown by this method in case of a message replay.
- /// The caller will be responsible to handle the replay attack.
- /// </remarks>
- protected virtual bool IsMessageReplayed(IReplayProtectedProtocolMessage message) {
- throw new NotSupportedException(MessagingStrings.ReplayProtectionNotSupported);
- }
-
- /// <summary>
/// Gets the protocol message that may be in the given HTTP response stream.
/// </summary>
/// <param name="responseStream">The response that is anticipated to contain an OAuth message.</param>
@@ -446,93 +403,95 @@ namespace DotNetOAuth.Messaging { }
/// <summary>
- /// Prepares a message for transmit by applying signatures, nonces, etc.
+ /// Ensures a consistent and secure set of binding elements and
+ /// sorts them as necessary for a valid sequence of operations.
/// </summary>
- /// <param name="message">The message to prepare for sending.</param>
- private void PrepareMessageForSending(IProtocolMessage message) {
- // The order of operations here is important.
- ISignedProtocolMessage signedMessage = message as ISignedProtocolMessage;
- if (signedMessage != null) {
- IExpiringProtocolMessage expiringMessage = message as IExpiringProtocolMessage;
- if (expiringMessage != null) {
- IReplayProtectedProtocolMessage nonceMessage = message as IReplayProtectedProtocolMessage;
- if (nonceMessage != null) {
- this.ApplyReplayProtection(nonceMessage);
- }
+ /// <param name="elements">The binding elements provided to the channel.</param>
+ /// <returns>The properly ordered list of elements.</returns>
+ /// <exception cref="ProtocolException">Thrown when the binding elements are incomplete or inconsistent with each other.</exception>
+ private static IEnumerable<IChannelBindingElement> ValidateAndPrepareBindingElements(IEnumerable<IChannelBindingElement> elements) {
+ // Filter the elements between the mere transforming ones and the protection ones.
+ var transformationElements = new List<IChannelBindingElement>(
+ elements.Where(element => element.Protection == ChannelProtection.None));
+ var protectionElements = new List<IChannelBindingElement>(
+ elements.Where(element => element.Protection != ChannelProtection.None));
- expiringMessage.UtcCreationDate = DateTime.UtcNow;
+ bool wasLastProtectionPresent = true;
+ foreach (ChannelProtection protectionKind in Enum.GetValues(typeof(ChannelProtection))) {
+ if (protectionKind == ChannelProtection.None) {
+ continue;
}
- this.Sign(signedMessage);
- }
- }
+ int countProtectionsOfThisKind = protectionElements.Count(element => (element.Protection & protectionKind) == protectionKind);
+
+ // Each protection binding element is backed by the presence of its dependent protection(s).
+ if (countProtectionsOfThisKind > 0 && !wasLastProtectionPresent) {
+ throw new ProtocolException(
+ string.Format(
+ CultureInfo.CurrentCulture,
+ MessagingStrings.RequiredProtectionMissing,
+ protectionKind));
+ }
- /// <summary>
- /// Verifies the integrity and applicability of an incoming message.
- /// </summary>
- /// <param name="message">The message just received.</param>
- /// <exception cref="ProtocolException">
- /// Thrown when the message is somehow invalid.
- /// This can be due to tampering, replay attack or expiration, among other things.
- /// </exception>
- private void VerifyMessageAfterReceiving(IProtocolMessage message) {
- // The order of operations is important.
- ISignedProtocolMessage signedMessage = message as ISignedProtocolMessage;
- if (signedMessage != null) {
- this.VerifyMessageSignature(signedMessage);
-
- IExpiringProtocolMessage expiringMessage = message as IExpiringProtocolMessage;
- if (expiringMessage != null) {
- this.VerifyMessageHasNotExpired(expiringMessage);
-
- IReplayProtectedProtocolMessage nonceMessage = message as IReplayProtectedProtocolMessage;
- if (nonceMessage != null) {
- this.VerifyMessageReplayProtection(nonceMessage);
- }
+ // At most one binding element for each protection type.
+ if (countProtectionsOfThisKind > 1) {
+ throw new ProtocolException(
+ string.Format(
+ CultureInfo.CurrentCulture,
+ MessagingStrings.TooManyBindingsOfferingSameProtection,
+ protectionKind,
+ countProtectionsOfThisKind));
}
+ wasLastProtectionPresent = countProtectionsOfThisKind > 0;
}
+
+ // Put the binding elements in order so they are correctly applied to outgoing messages.
+ // Start with the transforming (non-protecting) binding elements first and preserve their original order.
+ var orderedList = new List<IChannelBindingElement>(transformationElements);
+
+ // Now sort the protection binding elements among themselves and add them to the list.
+ orderedList.AddRange(protectionElements.OrderBy(element => element.Protection, BindingElementOutgoingMessageApplicationOrder));
+ return orderedList;
}
/// <summary>
- /// Verifies that a message signature is valid.
+ /// Puts binding elements in their correct outgoing message processing order.
/// </summary>
- /// <param name="signedMessage">The message whose signature is to be verified.</param>
- /// <exception cref="ProtocolException">Thrown if the signature is invalid.</exception>
- private void VerifyMessageSignature(ISignedProtocolMessage signedMessage) {
- Debug.Assert(signedMessage != null, "signedMessage == null");
-
- if (!this.IsSignatureValid(signedMessage)) {
- // TODO: add inResponseTo and remoteReceiver where applicable
- throw new InvalidSignatureException(signedMessage);
- }
+ /// <param name="protection1">The first protection type to compare.</param>
+ /// <param name="protection2">The second protection type to compare.</param>
+ /// <returns>
+ /// -1 if <paramref name="element1"/> should be applied to an outgoing message before <paramref name="element2"/>.
+ /// 1 if <paramref name="element2"/> should be applied to an outgoing message before <paramref name="element1"/>.
+ /// 0 if it doesn't matter.
+ /// </returns>
+ private static int BindingElementOutgoingMessageApplicationOrder(ChannelProtection protection1, ChannelProtection protection2) {
+ Debug.Assert(protection1 != ChannelProtection.None && protection2 != ChannelProtection.None, "This comparison function should only be used to compare protection binding elements. Otherwise we change the order of user-defined message transformations.");
+
+ // Now put the protection ones in the right order.
+ return -((int)protection1).CompareTo((int)protection2); // descending flag ordinal order
}
/// <summary>
- /// Verifies that a given message has not grown too old to process.
+ /// Prepares a message for transmit by applying signatures, nonces, etc.
/// </summary>
- /// <param name="expiringMessage">The message to ensure has not expired.</param>
- /// <exception cref="ProtocolException">Thrown if the message has already expired.</exception>
- private void VerifyMessageHasNotExpired(IExpiringProtocolMessage expiringMessage) {
- Debug.Assert(expiringMessage != null, "expiringMessage == null");
-
- // Yes the UtcCreationDate is supposed to always be in UTC already,
- // but just in case a given message failed to guarantee that, we do it here.
- DateTime expirationDate = expiringMessage.UtcCreationDate.ToUniversalTime() + this.MaximumMessageAge;
- if (expirationDate < DateTime.UtcNow) {
- throw new ExpiredMessageException(expirationDate, expiringMessage);
+ /// <param name="message">The message to prepare for sending.</param>
+ private void PrepareMessageForSending(IProtocolMessage message) {
+ foreach (IChannelBindingElement bindingElement in this.bindingElements) {
+ bindingElement.PrepareMessageForSending(message);
}
}
/// <summary>
- /// Verifies that a message has not already been processed.
+ /// Verifies the integrity and applicability of an incoming message.
/// </summary>
- /// <param name="message">The message to verify.</param>
- /// <exception cref="ProtocolException">Thrown if the message has already been processed.</exception>
- private void VerifyMessageReplayProtection(IReplayProtectedProtocolMessage message) {
- Debug.Assert(message != null, "message == null");
-
- if (this.IsMessageReplayed(message)) {
- throw new ReplayedMessageException(message);
+ /// <param name="message">The message just received.</param>
+ /// <exception cref="ProtocolException">
+ /// Thrown when the message is somehow invalid.
+ /// This can be due to tampering, replay attack or expiration, among other things.
+ /// </exception>
+ private void VerifyMessageAfterReceiving(IProtocolMessage message) {
+ foreach (IChannelBindingElement bindingElement in this.bindingElements.Reverse<IChannelBindingElement>()) {
+ bindingElement.PrepareMessageForReceiving(message);
}
}
}
diff --git a/src/DotNetOAuth/Messaging/ChannelProtection.cs b/src/DotNetOAuth/Messaging/ChannelProtection.cs new file mode 100644 index 0000000..bbc619c --- /dev/null +++ b/src/DotNetOAuth/Messaging/ChannelProtection.cs @@ -0,0 +1,41 @@ +//-----------------------------------------------------------------------
+// <copyright file="ChannelProtection.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOAuth.Messaging {
+ using System;
+
+ /// <summary>
+ /// Categorizes the various types of channel binding elements so they can be properly ordered.
+ /// </summary>
+ /// <remarks>
+ /// The order of these enum values is significant.
+ /// Each successive value requires the protection offered by all the previous values
+ /// in order to be reliable. For example, message expiration is meaningless without
+ /// tamper protection to prevent a user from changing the timestamp on a message.
+ /// </remarks>
+ [Flags]
+ internal enum ChannelProtection {
+ /// <summary>
+ /// No protection.
+ /// </summary>
+ None = 0x0,
+
+ /// <summary>
+ /// A binding element that signs a message before sending and validates its signature upon receiving.
+ /// </summary>
+ TamperProtection = 0x1,
+
+ /// <summary>
+ /// A binding element that enforces a maximum message age between sending and processing on the receiving side.
+ /// </summary>
+ Expiration = 0x2,
+
+ /// <summary>
+ /// A binding element that prepares messages for replay detection and detects replayed messages on the receiving side.
+ /// </summary>
+ ReplayProtection = 0x4,
+ }
+}
\ No newline at end of file diff --git a/src/DotNetOAuth/Messaging/ExpiredMessageException.cs b/src/DotNetOAuth/Messaging/ExpiredMessageException.cs index 3d4ded3..fe37b07 100644 --- a/src/DotNetOAuth/Messaging/ExpiredMessageException.cs +++ b/src/DotNetOAuth/Messaging/ExpiredMessageException.cs @@ -17,7 +17,7 @@ namespace DotNetOAuth.Messaging { /// </summary>
/// <param name="utcExpirationDate">The date the message expired.</param>
/// <param name="faultedMessage">The expired message.</param>
- public ExpiredMessageException(DateTime utcExpirationDate, IExpiringProtocolMessage faultedMessage)
+ public ExpiredMessageException(DateTime utcExpirationDate, IProtocolMessage faultedMessage)
: base(string.Format(MessagingStrings.ExpiredMessage, utcExpirationDate.ToUniversalTime(), DateTime.UtcNow), faultedMessage) {
}
diff --git a/src/DotNetOAuth/Messaging/IChannelBindingElement.cs b/src/DotNetOAuth/Messaging/IChannelBindingElement.cs new file mode 100644 index 0000000..5e72d36 --- /dev/null +++ b/src/DotNetOAuth/Messaging/IChannelBindingElement.cs @@ -0,0 +1,36 @@ +//-----------------------------------------------------------------------
+// <copyright file="IChannelBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ /// <summary>
+ /// An interface that must be implemented by message transforms/validators in order
+ /// to be included in the channel stack.
+ /// </summary>
+ internal interface IChannelBindingElement {
+ /// <summary>
+ /// Gets the protection offered (if any) by this binding element.
+ /// </summary>
+ ChannelProtection Protection { get; }
+
+ /// <summary>
+ /// Prepares a message for sending based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The message to prepare for sending.</param>
+ void PrepareMessageForSending(IProtocolMessage message);
+
+ /// <summary>
+ /// Performs any transformation on an incoming message that may be necessary and/or
+ /// validates an incoming message based on the rules of this channel binding element.
+ /// </summary>
+ /// <param name="message">The incoming message to process.</param>
+ void PrepareMessageForReceiving(IProtocolMessage message);
+ }
+}
diff --git a/src/DotNetOAuth/Messaging/InvalidSignatureException.cs b/src/DotNetOAuth/Messaging/InvalidSignatureException.cs index 1b66a3d..7b65f2d 100644 --- a/src/DotNetOAuth/Messaging/InvalidSignatureException.cs +++ b/src/DotNetOAuth/Messaging/InvalidSignatureException.cs @@ -16,7 +16,7 @@ namespace DotNetOAuth.Messaging { /// Initializes a new instance of the <see cref="InvalidSignatureException"/> class.
/// </summary>
/// <param name="faultedMessage">The message with the invalid signature.</param>
- public InvalidSignatureException(ISignedProtocolMessage faultedMessage)
+ public InvalidSignatureException(IProtocolMessage faultedMessage)
: base(MessagingStrings.SignatureInvalid, faultedMessage) { }
/// <summary>
diff --git a/src/DotNetOAuth/Messaging/MessagingStrings.Designer.cs b/src/DotNetOAuth/Messaging/MessagingStrings.Designer.cs index 2d3985a..702a5be 100644 --- a/src/DotNetOAuth/Messaging/MessagingStrings.Designer.cs +++ b/src/DotNetOAuth/Messaging/MessagingStrings.Designer.cs @@ -169,6 +169,15 @@ namespace DotNetOAuth.Messaging { }
/// <summary>
+ /// Looks up a localized string similar to The binding element offering the {0} protection requires other protection that is not provided..
+ /// </summary>
+ internal static string RequiredProtectionMissing {
+ get {
+ return ResourceManager.GetString("RequiredProtectionMissing", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Looks up a localized string similar to Message signature was incorrect..
/// </summary>
internal static string SignatureInvalid {
@@ -187,6 +196,15 @@ namespace DotNetOAuth.Messaging { }
/// <summary>
+ /// Looks up a localized string similar to Expected at most 1 binding element offering the {0} protection, but found {1}..
+ /// </summary>
+ internal static string TooManyBindingsOfferingSameProtection {
+ get {
+ return ResourceManager.GetString("TooManyBindingsOfferingSameProtection", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Looks up a localized string similar to The type {0} or a derived type was expected, but {1} was given..
/// </summary>
internal static string UnexpectedType {
diff --git a/src/DotNetOAuth/Messaging/MessagingStrings.resx b/src/DotNetOAuth/Messaging/MessagingStrings.resx index be0b864..a7dd42f 100644 --- a/src/DotNetOAuth/Messaging/MessagingStrings.resx +++ b/src/DotNetOAuth/Messaging/MessagingStrings.resx @@ -153,16 +153,22 @@ <data name="ReplayProtectionNotSupported" xml:space="preserve">
<value>This channel does not support replay protection.</value>
</data>
+ <data name="RequiredProtectionMissing" xml:space="preserve">
+ <value>The binding element offering the {0} protection requires other protection that is not provided.</value>
+ </data>
<data name="SignatureInvalid" xml:space="preserve">
<value>Message signature was incorrect.</value>
</data>
<data name="SigningNotSupported" xml:space="preserve">
<value>This channel does not support signing messages. To support signing messages, a derived Channel type must override the Sign and IsSignatureValid methods.</value>
</data>
+ <data name="TooManyBindingsOfferingSameProtection" xml:space="preserve">
+ <value>Expected at most 1 binding element offering the {0} protection, but found {1}.</value>
+ </data>
<data name="UnexpectedType" xml:space="preserve">
<value>The type {0} or a derived type was expected, but {1} was given.</value>
</data>
<data name="UnrecognizedEnumValue" xml:space="preserve">
<value>{0} property has unrecognized value {1}.</value>
</data>
-</root> +</root>
\ No newline at end of file diff --git a/src/DotNetOAuth/Messaging/MessagingUtilities.cs b/src/DotNetOAuth/Messaging/MessagingUtilities.cs index e8069f6..7c95696 100644 --- a/src/DotNetOAuth/Messaging/MessagingUtilities.cs +++ b/src/DotNetOAuth/Messaging/MessagingUtilities.cs @@ -8,6 +8,7 @@ namespace DotNetOAuth.Messaging { using System;
using System.Collections.Generic;
using System.Collections.Specialized;
+ using System.Linq;
using System.Net;
using System.Text;
using System.Web;
@@ -115,5 +116,55 @@ namespace DotNetOAuth.Messaging { return dictionary;
}
+
+ /// <summary>
+ /// Sorts the elements of a sequence in ascending order by using a specified comparer.
+ /// </summary>
+ /// <typeparam name="TSource">The type of the elements of source.</typeparam>
+ /// <typeparam name="TKey">The type of the key returned by keySelector.</typeparam>
+ /// <param name="source">A sequence of values to order.</param>
+ /// <param name="keySelector">A function to extract a key from an element.</param>
+ /// <param name="comparer">A comparison function to compare keys.</param>
+ /// <returns>An System.Linq.IOrderedEnumerable<TElement> whose elements are sorted according to a key.</returns>
+ internal static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Comparison<TKey> comparer) {
+ return System.Linq.Enumerable.OrderBy<TSource, TKey>(source, keySelector, new ComparisonHelper<TKey>(comparer));
+ }
+
+ /// <summary>
+ /// A class to convert a <see cref="Comparison<T>"/> into an <see cref="IComparer<T>"/>.
+ /// </summary>
+ /// <typeparam name="T">The type of objects being compared.</typeparam>
+ private class ComparisonHelper<T> : IComparer<T> {
+ /// <summary>
+ /// The comparison method to use.
+ /// </summary>
+ private Comparison<T> comparison;
+
+ /// <summary>
+ /// Initializes a new instance of the ComparisonHelper class.
+ /// </summary>
+ /// <param name="comparison">The comparison method to use.</param>
+ internal ComparisonHelper(Comparison<T> comparison) {
+ if (comparison == null) {
+ throw new ArgumentNullException("comparison");
+ }
+
+ this.comparison = comparison;
+ }
+
+ #region IComparer<T> Members
+
+ /// <summary>
+ /// Compares two instances of <typeparamref name="T"/>.
+ /// </summary>
+ /// <param name="x">The first object to compare.</param>
+ /// <param name="y">The second object to compare.</param>
+ /// <returns>Any of -1, 0, or 1 according to standard comparison rules.</returns>
+ public int Compare(T x, T y) {
+ return this.comparison(x, y);
+ }
+
+ #endregion
+ }
}
}
diff --git a/src/DotNetOAuth/Messaging/ReplayedMessageException.cs b/src/DotNetOAuth/Messaging/ReplayedMessageException.cs index 1df0a4b..2c4e5cb 100644 --- a/src/DotNetOAuth/Messaging/ReplayedMessageException.cs +++ b/src/DotNetOAuth/Messaging/ReplayedMessageException.cs @@ -17,7 +17,7 @@ namespace DotNetOAuth.Messaging { /// Initializes a new instance of the <see cref="ReplayedMessageException"/> class.
/// </summary>
/// <param name="faultedMessage">The replayed message.</param>
- public ReplayedMessageException(IReplayProtectedProtocolMessage faultedMessage) : base(MessagingStrings.ReplayAttackDetected, faultedMessage) { }
+ public ReplayedMessageException(IProtocolMessage faultedMessage) : base(MessagingStrings.ReplayAttackDetected, faultedMessage) { }
/// <summary>
/// Initializes a new instance of the <see cref="ReplayedMessageException"/> class.
diff --git a/src/DotNetOAuth/Messaging/StandardMessageExpirationBindingElement.cs b/src/DotNetOAuth/Messaging/StandardMessageExpirationBindingElement.cs new file mode 100644 index 0000000..cfa0d31 --- /dev/null +++ b/src/DotNetOAuth/Messaging/StandardMessageExpirationBindingElement.cs @@ -0,0 +1,100 @@ +//-----------------------------------------------------------------------
+// <copyright file="StandardMessageExpirationBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOAuth.Messaging {
+ using System;
+
+ /// <summary>
+ /// A message expiration enforcing binding element that supports messages
+ /// implementing the <see cref="IExpiringProtocolMessage"/> interface.
+ /// </summary>
+ internal class StandardMessageExpirationBindingElement : IChannelBindingElement {
+ /// <summary>
+ /// The default maximum message age to use if the default constructor is called.
+ /// </summary>
+ internal static readonly TimeSpan DefaultMaximumMessageAge = TimeSpan.FromMinutes(13);
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StandardMessageExpirationBindingElement"/> class
+ /// with a default maximum message lifetime of 13 minutes.
+ /// </summary>
+ internal StandardMessageExpirationBindingElement()
+ : this(DefaultMaximumMessageAge) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StandardMessageExpirationBindingElement"/> class.
+ /// </summary>
+ /// <param name="maximumAge">
+ /// <para>The maximum age a message implementing the
+ /// <see cref="IExpiringProtocolMessage"/> interface can be before
+ /// being discarded as too old.</para>
+ /// <para>This time limit should take into account expected time skew for servers
+ /// across the Internet. For example, if a server could conceivably have its
+ /// clock d = 5 minutes off UTC time, then any two servers could have
+ /// their clocks disagree by as much as 2*d = 10 minutes.
+ /// If a message should live for at least t = 3 minutes,
+ /// this property should be set to (2*d + t) = 13 minutes.</para>
+ /// </param>
+ internal StandardMessageExpirationBindingElement(TimeSpan maximumAge) {
+ this.MaximumMessageAge = maximumAge;
+ }
+
+ #region IChannelBindingElement Properties
+
+ /// <summary>
+ /// Gets the protection offered by this binding element.
+ /// </summary>
+ /// <value><see cref="ChannelProtection.Expiration"/></value>
+ ChannelProtection IChannelBindingElement.Protection {
+ get { return ChannelProtection.Expiration; }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets the maximum age a message implementing the
+ /// <see cref="IExpiringProtocolMessage"/> interface can be before
+ /// being discarded as too old.
+ /// </summary>
+ protected internal TimeSpan MaximumMessageAge {
+ get;
+ private set;
+ }
+
+ #region IChannelBindingElement Methods
+
+ /// <summary>
+ /// Sets the timestamp on an outgoing message.
+ /// </summary>
+ /// <param name="message">The outgoing message.</param>
+ void IChannelBindingElement.PrepareMessageForSending(IProtocolMessage message) {
+ IExpiringProtocolMessage expiringMessage = message as IExpiringProtocolMessage;
+ if (expiringMessage != null) {
+ expiringMessage.UtcCreationDate = DateTime.UtcNow;
+ }
+ }
+
+ /// <summary>
+ /// Reads the timestamp on a message and throws an exception if the message is too old.
+ /// </summary>
+ /// <param name="message">The incoming message.</param>
+ /// <exception cref="ExpiredMessageException">Thrown if the given message has already expired.</exception>
+ void IChannelBindingElement.PrepareMessageForReceiving(IProtocolMessage message) {
+ IExpiringProtocolMessage expiringMessage = message as IExpiringProtocolMessage;
+ if (expiringMessage != null) {
+ // Yes the UtcCreationDate is supposed to always be in UTC already,
+ // but just in case a given message failed to guarantee that, we do it here.
+ DateTime expirationDate = expiringMessage.UtcCreationDate.ToUniversalTime() + this.MaximumMessageAge;
+ if (expirationDate < DateTime.UtcNow) {
+ throw new ExpiredMessageException(expirationDate, expiringMessage);
+ }
+ }
+ }
+
+ #endregion
+ }
+}
|