summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj8
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs33
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs12
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs10
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs8
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/StandardMessageFactoryTests.cs178
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs6
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs4
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/TestDirectResponseMessageWithHttpStatus.cs12
-rw-r--r--src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs127
-rw-r--r--src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs21
-rw-r--r--src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs15
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs24
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs17
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs8
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs13
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs14
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs8
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs2
-rw-r--r--src/DotNetOpenAuth.Test/OpenId/RelyingParty/AssociationsTests.cs (renamed from src/DotNetOpenAuth.Test/OpenId/AssociationsTests.cs)3
-rw-r--r--src/DotNetOpenAuth.TestWeb/OpenIdProviderEndpoint.ashx2
-rw-r--r--src/DotNetOpenAuth.sln17
-rw-r--r--src/DotNetOpenAuth/CodeAnalysisDictionary.xml71
-rw-r--r--src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd31
-rw-r--r--src/DotNetOpenAuth/Configuration/MessagingElement.cs31
-rw-r--r--src/DotNetOpenAuth/Configuration/OpenIdProviderElement.cs5
-rw-r--r--src/DotNetOpenAuth/Configuration/OpenIdProviderSecuritySettingsElement.cs17
-rw-r--r--src/DotNetOpenAuth/Configuration/OpenIdRelyingPartyElement.cs4
-rw-r--r--src/DotNetOpenAuth/Configuration/OpenIdRelyingPartySecuritySettingsElement.cs18
-rw-r--r--src/DotNetOpenAuth/DotNetOpenAuth.csproj155
-rw-r--r--src/DotNetOpenAuth/GlobalSuppressions.cs1
-rw-r--r--src/DotNetOpenAuth/Messaging/BinaryDataBagFormatter.cs80
-rw-r--r--src/DotNetOpenAuth/Messaging/Bindings/AsymmetricCryptoKeyStoreWrapper.cs163
-rw-r--r--src/DotNetOpenAuth/Messaging/Bindings/CryptoKey.cs93
-rw-r--r--src/DotNetOpenAuth/Messaging/Bindings/CryptoKeyCollisionException.cs68
-rw-r--r--src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs1
-rw-r--r--src/DotNetOpenAuth/Messaging/Bindings/ICryptoKeyStore.cs118
-rw-r--r--src/DotNetOpenAuth/Messaging/Bindings/MemoryCryptoKeyStore.cs156
-rw-r--r--src/DotNetOpenAuth/Messaging/Channel.cs147
-rw-r--r--src/DotNetOpenAuth/Messaging/DataBag.cs147
-rw-r--r--src/DotNetOpenAuth/Messaging/DataBagFormatterBase.cs354
-rw-r--r--src/DotNetOpenAuth/Messaging/EnumerableCache.cs2
-rw-r--r--src/DotNetOpenAuth/Messaging/IDataBagFormatter.cs75
-rw-r--r--src/DotNetOpenAuth/Messaging/IDirectWebRequestHandler.cs.orig222
-rw-r--r--src/DotNetOpenAuth/Messaging/IHttpDirectResponse.cs10
-rw-r--r--src/DotNetOpenAuth/Messaging/IHttpDirectResponseContract.cs43
-rw-r--r--src/DotNetOpenAuth/Messaging/IHttpIndirectResponse.cs22
-rw-r--r--src/DotNetOpenAuth/Messaging/IStreamSerializingDataBag.cs55
-rw-r--r--src/DotNetOpenAuth/Messaging/MessageSerializer.cs111
-rw-r--r--src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs36
-rw-r--r--src/DotNetOpenAuth/Messaging/MessagingStrings.resx12
-rw-r--r--src/DotNetOpenAuth/Messaging/MessagingUtilities.cs678
-rw-r--r--src/DotNetOpenAuth/Messaging/OutgoingWebResponse.cs90
-rw-r--r--src/DotNetOpenAuth/Messaging/OutgoingWebResponseActionResult.cs2
-rw-r--r--src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs233
-rw-r--r--src/DotNetOpenAuth/Messaging/Reflection/MessageDescriptionCollection.cs32
-rw-r--r--src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs80
-rw-r--r--src/DotNetOpenAuth/Messaging/StandardMessageFactory.cs298
-rw-r--r--src/DotNetOpenAuth/Messaging/StandardMessageFactoryChannel.cs111
-rw-r--r--src/DotNetOpenAuth/Messaging/StandardWebRequestHandler.cs9
-rw-r--r--src/DotNetOpenAuth/Messaging/TimespanSecondsEncoder.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/TimespanSecondsEncoder.cs)9
-rw-r--r--src/DotNetOpenAuth/Messaging/TimestampEncoder.cs61
-rw-r--r--src/DotNetOpenAuth/Messaging/UriStyleMessageFormatter.cs77
-rw-r--r--src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs49
-rw-r--r--src/DotNetOpenAuth/OAuth/ChannelElements/OAuthPrincipal.cs18
-rw-r--r--src/DotNetOpenAuth/OAuth/ChannelElements/TokenHandlingBindingElement.cs2
-rw-r--r--src/DotNetOpenAuth/OAuth/Protocol.cs2
-rw-r--r--src/DotNetOpenAuth/OAuth2/AuthorizationServer.cs258
-rw-r--r--src/DotNetOpenAuth/OAuth2/AuthorizationServerDescription.cs62
-rw-r--r--src/DotNetOpenAuth/OAuth2/AuthorizationState.cs93
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AccessRequestBindingElement.cs158
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AccessToken.cs102
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AccessTokenBindingElement.cs93
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AuthServerAllFlowsBindingElement.cs83
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AuthServerBindingElementBase.cs92
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCode.cs100
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs101
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationDataBag.cs51
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs66
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/GrantTypeEncoder.cs78
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/IAuthorizationCarryingRequest.cs54
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/IAuthorizationDescription.cs90
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs108
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ChannelBase.cs69
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ClientChannel.cs122
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs153
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/RefreshToken.cs56
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/ScopeEncoder.cs51
-rw-r--r--src/DotNetOpenAuth/OAuth2/ClientBase.cs233
-rw-r--r--src/DotNetOpenAuth/OAuth2/IAccessTokenAnalyzer.cs64
-rw-r--r--src/DotNetOpenAuth/OAuth2/IAuthorizationServer.cs238
-rw-r--r--src/DotNetOpenAuth/OAuth2/IAuthorizationState.cs67
-rw-r--r--src/DotNetOpenAuth/OAuth2/IClientAuthorizationTracker.cs53
-rw-r--r--src/DotNetOpenAuth/OAuth2/IConsumerDescription.cs101
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessProtectedResourceRequest.cs73
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs94
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs41
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenFailedResponse.cs86
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRefreshRequest.cs75
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRequestBase.cs78
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs50
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenSuccessResponse.cs99
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AuthenticatedClientRequestBase.cs42
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs81
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationRequest.cs118
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationResponseType.cs25
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs121
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs76
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs69
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/GrantType.cs42
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/IAccessTokenRequest.cs37
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/IMessageWithClientState.cs21
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/MessageBase.cs239
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/OAuth 2 Messages.cd164
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/ScopedAccessTokenRequest.cs41
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/UnauthorizedResponse.cs115
-rw-r--r--src/DotNetOpenAuth/OAuth2/OAuthStrings.Designer.cs144
-rw-r--r--src/DotNetOpenAuth/OAuth2/OAuthStrings.resx147
-rw-r--r--src/DotNetOpenAuth/OAuth2/OAuthUtilities.cs123
-rw-r--r--src/DotNetOpenAuth/OAuth2/Protocol.cs355
-rw-r--r--src/DotNetOpenAuth/OAuth2/ResourceServer.cs136
-rw-r--r--src/DotNetOpenAuth/OAuth2/StandardAccessTokenAnalyzer.cs66
-rw-r--r--src/DotNetOpenAuth/OAuth2/UserAgentClient.cs108
-rw-r--r--src/DotNetOpenAuth/OAuth2/WebServerClient.cs130
-rw-r--r--src/DotNetOpenAuth/OpenId/Association.cs10
-rw-r--r--src/DotNetOpenAuth/OpenId/AssociationMemoryStore.cs133
-rw-r--r--src/DotNetOpenAuth/OpenId/Behaviors/GsaIcamProfile.cs11
-rw-r--r--src/DotNetOpenAuth/OpenId/ChannelElements/OpenIdChannel.cs112
-rw-r--r--src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToNonceBindingElement.cs11
-rw-r--r--src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs50
-rw-r--r--src/DotNetOpenAuth/OpenId/ChannelElements/SigningBindingElement.cs33
-rw-r--r--src/DotNetOpenAuth/OpenId/DiffieHellman/DHKeyGeneration.cs8
-rw-r--r--src/DotNetOpenAuth/OpenId/DiffieHellman/DHParameters.cs9
-rw-r--r--src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellman.cs9
-rw-r--r--src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellmanManaged.cs9
-rw-r--r--src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Gender.cs2
-rw-r--r--src/DotNetOpenAuth/OpenId/HmacShaAssociation.cs26
-rw-r--r--src/DotNetOpenAuth/OpenId/IAssociationStore.cs189
-rw-r--r--src/DotNetOpenAuth/OpenId/IOpenIdApplicationStore.cs16
-rw-r--r--src/DotNetOpenAuth/OpenId/Messages/AssociateDiffieHellmanResponse.cs9
-rw-r--r--src/DotNetOpenAuth/OpenId/Messages/AssociateRequest.cs11
-rw-r--r--src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponse.cs27
-rw-r--r--src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponseContract.cs3
-rw-r--r--src/DotNetOpenAuth/OpenId/Messages/AssociateUnencryptedResponse.cs17
-rw-r--r--src/DotNetOpenAuth/OpenId/Messages/CheckAuthenticationResponse.cs4
-rw-r--r--src/DotNetOpenAuth/OpenId/Messages/DirectErrorResponse.cs8
-rw-r--r--src/DotNetOpenAuth/OpenId/OpenIdUtilities.cs35
-rw-r--r--src/DotNetOpenAuth/OpenId/Provider/AnonymousRequest.cs2
-rw-r--r--src/DotNetOpenAuth/OpenId/Provider/AssociationDataBag.cs95
-rw-r--r--src/DotNetOpenAuth/OpenId/Provider/AssociationRelyingPartyType.cs26
-rw-r--r--src/DotNetOpenAuth/OpenId/Provider/IProviderApplicationStore.cs20
-rw-r--r--src/DotNetOpenAuth/OpenId/Provider/IProviderAssociationStore.cs90
-rw-r--r--src/DotNetOpenAuth/OpenId/Provider/OpenIdProvider.cs141
-rw-r--r--src/DotNetOpenAuth/OpenId/Provider/ProviderAssociationHandleEncoder.cs84
-rw-r--r--src/DotNetOpenAuth/OpenId/Provider/ProviderAssociationKeyStorage.cs79
-rw-r--r--src/DotNetOpenAuth/OpenId/Provider/ProviderEndpoint.cs5
-rw-r--r--src/DotNetOpenAuth/OpenId/Provider/ProviderSecuritySettings.cs13
-rw-r--r--src/DotNetOpenAuth/OpenId/Provider/StandardProviderApplicationStore.cs116
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/AssociationManager.cs8
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/Associations.cs (renamed from src/DotNetOpenAuth/OpenId/Associations.cs)2
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/AuthenticationRequest.cs10
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/CryptoKeyStoreAsRelyingPartyAssociationStore.cs87
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/IRelyingPartyApplicationStore.cs21
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/IRelyingPartyAssociationStore.cs153
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs2
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdMobileTextBox.cs4
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingParty.cs28
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs4
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs4
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/PositiveAnonymousResponse.cs4
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/PrivateSecretManager.cs122
-rw-r--r--src/DotNetOpenAuth/OpenId/RelyingParty/StandardRelyingPartyApplicationStore.cs65
-rw-r--r--src/DotNetOpenAuth/Reporting.cs23
-rw-r--r--src/version.txt2
177 files changed, 11213 insertions, 1078 deletions
diff --git a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
index 2067ede..9bae939 100644
--- a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
+++ b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
@@ -173,6 +173,7 @@
<Reference Include="System.ServiceModel">
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
+ <Reference Include="System.ServiceModel.Web" />
<Reference Include="System.Web" />
<Reference Include="System.Xml" />
<Reference Include="System.Xml.Linq">
@@ -204,6 +205,7 @@
<Compile Include="Messaging\Bindings\StandardExpirationBindingElementTests.cs" />
<Compile Include="Messaging\Reflection\MessagePartTests.cs" />
<Compile Include="Messaging\Reflection\ValueMappingTests.cs" />
+ <Compile Include="Messaging\StandardMessageFactoryTests.cs" />
<Compile Include="Mocks\AssociateUnencryptedRequestNoSslCheck.cs" />
<Compile Include="Mocks\CoordinatingChannel.cs" />
<Compile Include="Mocks\CoordinatingHttpRequestInfo.cs" />
@@ -229,6 +231,9 @@
<Compile Include="Mocks\TestChannel.cs" />
<Compile Include="Mocks\TestMessage.cs" />
<Compile Include="Mocks\TestMessageFactory.cs" />
+ <Compile Include="OAuth2\MessageFactoryTests.cs" />
+ <Compile Include="OAuth2\OAuth2ChannelTests.cs" />
+ <Compile Include="OAuth2\OAuth2TestBase.cs" />
<Compile Include="OAuth\ChannelElements\HmacSha1SigningBindingElementTests.cs" />
<Compile Include="OAuth\ChannelElements\OAuthChannelTests.cs" />
<Compile Include="OAuth\ChannelElements\PlaintextSigningBindingElementTest.cs" />
@@ -238,7 +243,7 @@
<Compile Include="OAuth\ProtocolTests.cs" />
<Compile Include="OAuth\ServiceProviderDescriptionTests.cs" />
<Compile Include="OAuth\ServiceProviderTests.cs" />
- <Compile Include="OpenId\AssociationsTests.cs" />
+ <Compile Include="OpenId\RelyingParty\AssociationsTests.cs" />
<Compile Include="OpenId\AssociationTests.cs" />
<Compile Include="OpenId\AuthenticationTests.cs" />
<Compile Include="OpenId\ChannelElements\ExtensionsBindingElementTests.cs" />
@@ -359,6 +364,7 @@
<EmbeddedResource Include="OpenId\Discovery\xrdsdiscovery\xrds20dual.xml" />
</ItemGroup>
<ItemGroup>
+ <Folder Include="OAuth2\ChannelElements\" />
<Folder Include="OpenId\UI\" />
</ItemGroup>
<ItemGroup>
diff --git a/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs b/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs
index 91cccf1..07743e1 100644
--- a/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs
@@ -7,6 +7,9 @@
namespace DotNetOpenAuth.Test.Messaging {
using System;
using System.Collections.Generic;
+ using System.IO;
+ using System.Runtime.Serialization.Json;
+ using System.Text;
using System.Xml;
using DotNetOpenAuth.Messaging;
using NUnit.Framework;
@@ -52,10 +55,38 @@ namespace DotNetOpenAuth.Test.Messaging {
Assert.IsFalse(actual.ContainsKey("EmptyMember"));
}
+ /// <summary>
+ /// Verifies JSON serialization
+ /// </summary>
+ [TestCase]
+ public void SerializeDeserializeJson() {
+ var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
+ var message = GetStandardTestMessage(FieldFill.CompleteBeforeBindings);
+
+ var ms = new MemoryStream();
+ var writer = JsonReaderWriterFactory.CreateJsonWriter(ms, Encoding.UTF8);
+ MessageSerializer.Serialize(this.MessageDescriptions.GetAccessor(message), writer);
+ writer.Flush();
+
+ string actual = Encoding.UTF8.GetString(ms.ToArray());
+ string expected = @"{""age"":15,""Name"":""Andrew"",""Location"":""http:\/\/localtest\/path"",""Timestamp"":""2008-09-19T08:00:00Z""}";
+ Assert.AreEqual(expected, actual);
+
+ ms.Position = 0;
+ var deserialized = new Mocks.TestDirectedMessage();
+ var reader = JsonReaderWriterFactory.CreateJsonReader(ms, XmlDictionaryReaderQuotas.Max);
+ MessageSerializer.Deserialize(this.MessageDescriptions.GetAccessor(deserialized), reader);
+ Assert.AreEqual(message.Age, deserialized.Age);
+ Assert.AreEqual(message.EmptyMember, deserialized.EmptyMember);
+ Assert.AreEqual(message.Location, deserialized.Location);
+ Assert.AreEqual(message.Name, deserialized.Name);
+ Assert.AreEqual(message.Timestamp, deserialized.Timestamp);
+ }
+
[TestCase, ExpectedException(typeof(ArgumentNullException))]
public void DeserializeNull() {
var serializer = MessageSerializer.Get(typeof(Mocks.TestMessage));
- serializer.Deserialize(null, null);
+ MessageSerializer.Deserialize(null, null);
}
[TestCase]
diff --git a/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs
index 33970a5..79751ae 100644
--- a/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs
@@ -217,6 +217,18 @@ namespace DotNetOpenAuth.Test.Messaging {
MessagingUtilities.GetHttpDeliveryMethod("UNRECOGNIZED");
}
+ [TestCase]
+ public void EncryptDecrypt() {
+ const string PlainText = "Hi folks!";
+ byte[] key = MessagingUtilities.GetCryptoRandomData(128 / 8);
+ var cipher = MessagingUtilities.Encrypt(PlainText, key);
+
+ Console.WriteLine("Encrypted \"{0}\" ({1} length) to {2} encrypted bytes.", PlainText, PlainText.Length, cipher.Length);
+
+ string roundTripped = MessagingUtilities.Decrypt(cipher, key);
+ Assert.AreEqual(PlainText, roundTripped);
+ }
+
/// <summary>
/// Verifies that the time-independent string equality check works accurately.
/// </summary>
diff --git a/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs
index e57df65..92f39cc 100644
--- a/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/Reflection/MessageDescriptionTests.cs
@@ -73,6 +73,16 @@ namespace DotNetOpenAuth.Test.Messaging.Reflection {
Assert.IsTrue(v30.Mapping["OptionalIn10RequiredIn25AndLater"].IsRequired);
}
+ /// <summary>
+ /// Verifies that the constructors cache is properly initialized.
+ /// </summary>
+ [TestCase]
+ public void CtorsCache() {
+ var message = new MessageDescription(typeof(MultiVersionMessage), new Version(1, 0));
+ Assert.IsNotNull(message.Constructors);
+ Assert.AreEqual(1, message.Constructors.Length);
+ }
+
private class MultiVersionMessage : Mocks.TestBaseMessage {
#pragma warning disable 0649 // these fields are never written to, but part of the test
[MessagePart]
diff --git a/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs b/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs
index 63be45a..037a68e 100644
--- a/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs
+++ b/src/DotNetOpenAuth.Test/Messaging/ResponseTests.cs
@@ -14,13 +14,13 @@ namespace DotNetOpenAuth.Test.Messaging {
[TestFixture]
public class ResponseTests : TestBase {
[TestCase, ExpectedException(typeof(InvalidOperationException))]
- public void SendWithoutAspNetContext() {
+ public void RespondWithoutAspNetContext() {
HttpContext.Current = null;
- new OutgoingWebResponse().Send();
+ new OutgoingWebResponse().Respond();
}
[TestCase]
- public void Send() {
+ public void Respond() {
StringWriter writer = new StringWriter();
HttpRequest httpRequest = new HttpRequest("file", "http://server", string.Empty);
HttpResponse httpResponse = new HttpResponse(writer);
@@ -31,7 +31,7 @@ namespace DotNetOpenAuth.Test.Messaging {
response.Status = System.Net.HttpStatusCode.OK;
response.Headers["someHeaderName"] = "someHeaderValue";
response.Body = "some body";
- response.Send();
+ response.Respond();
string results = writer.ToString();
// For some reason the only output in test is the body... the headers require a web host
Assert.AreEqual(response.Body, results);
diff --git a/src/DotNetOpenAuth.Test/Messaging/StandardMessageFactoryTests.cs b/src/DotNetOpenAuth.Test/Messaging/StandardMessageFactoryTests.cs
new file mode 100644
index 0000000..2b0b4e7
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/Messaging/StandardMessageFactoryTests.cs
@@ -0,0 +1,178 @@
+//-----------------------------------------------------------------------
+// <copyright file="StandardMessageFactoryTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using DotNetOpenAuth.Test.Mocks;
+ using NUnit.Framework;
+
+ [TestFixture]
+ public class StandardMessageFactoryTests : MessagingTestBase {
+ private static readonly Version V1 = new Version(1, 0);
+ private static readonly MessageReceivingEndpoint receiver = new MessageReceivingEndpoint("http://receiver", HttpDeliveryMethods.PostRequest);
+
+ private StandardMessageFactory factory;
+
+ public override void SetUp() {
+ base.SetUp();
+
+ this.factory = new StandardMessageFactory();
+ }
+
+ /// <summary>
+ /// Verifies that AddMessageTypes throws the appropriate exception on null input.
+ /// </summary>
+ [TestCase, ExpectedException(typeof(ArgumentNullException))]
+ public void AddMessageTypesNull() {
+ this.factory.AddMessageTypes(null);
+ }
+
+ /// <summary>
+ /// Verifies that AddMessageTypes throws the appropriate exception on null input.
+ /// </summary>
+ [TestCase, ExpectedException(typeof(ArgumentException))]
+ public void AddMessageTypesNullMessageDescription() {
+ this.factory.AddMessageTypes(new MessageDescription[] { null });
+ }
+
+ /// <summary>
+ /// Verifies very simple recognition of a single message type
+ /// </summary>
+ [TestCase]
+ public void SingleRequestMessageType() {
+ this.factory.AddMessageTypes(new MessageDescription[] { MessageDescriptions.Get(typeof(RequestMessageMock), V1) });
+ var fields = new Dictionary<string, string> {
+ { "random", "bits" },
+ };
+ Assert.IsNull(this.factory.GetNewRequestMessage(receiver, fields));
+ fields["Age"] = "18";
+ Assert.IsInstanceOf(typeof(RequestMessageMock), this.factory.GetNewRequestMessage(receiver, fields));
+ }
+
+ /// <summary>
+ /// Verifies very simple recognition of a single message type
+ /// </summary>
+ [TestCase]
+ public void SingleResponseMessageType() {
+ this.factory.AddMessageTypes(new MessageDescription[] { MessageDescriptions.Get(typeof(DirectResponseMessageMock), V1) });
+ var fields = new Dictionary<string, string> {
+ { "random", "bits" },
+ };
+ IDirectedProtocolMessage request = new RequestMessageMock(receiver.Location, V1);
+ Assert.IsNull(this.factory.GetNewResponseMessage(request, fields));
+ fields["Age"] = "18";
+ IDirectResponseProtocolMessage response = this.factory.GetNewResponseMessage(request, fields);
+ Assert.IsInstanceOf<DirectResponseMessageMock>(response);
+ Assert.AreSame(request, response.OriginatingRequest);
+
+ // Verify that we can instantiate a response with a derived-type of an expected request message.
+ request = new TestSignedDirectedMessage();
+ response = this.factory.GetNewResponseMessage(request, fields);
+ Assert.IsInstanceOf<DirectResponseMessageMock>(response);
+ Assert.AreSame(request, response.OriginatingRequest);
+ }
+
+ private class DirectResponseMessageMock : IDirectResponseProtocolMessage {
+ internal DirectResponseMessageMock(RequestMessageMock request) {
+ this.OriginatingRequest = request;
+ }
+
+ internal DirectResponseMessageMock(TestDirectedMessage request) {
+ this.OriginatingRequest = request;
+ }
+
+ [MessagePart(IsRequired = true)]
+ public int Age { get; set; }
+
+ #region IDirectResponseProtocolMessage Members
+
+ public IDirectedProtocolMessage OriginatingRequest { get; private set; }
+
+ #endregion
+
+ #region IProtocolMessage Members
+
+ public MessageProtections RequiredProtection {
+ get { throw new NotImplementedException(); }
+ }
+
+ public MessageTransport Transport {
+ get { throw new NotImplementedException(); }
+ }
+
+ #endregion
+
+ #region IMessage Members
+
+ public Version Version {
+ get { throw new NotImplementedException(); }
+ }
+
+ public System.Collections.Generic.IDictionary<string, string> ExtraData {
+ get { throw new NotImplementedException(); }
+ }
+
+ public void EnsureValidMessage() {
+ throw new NotImplementedException();
+ }
+
+ #endregion
+ }
+
+ private class RequestMessageMock : IDirectedProtocolMessage {
+ internal RequestMessageMock(Uri recipient, Version version) {
+ }
+
+ [MessagePart(IsRequired = true)]
+ public int Age { get; set; }
+
+ #region IDirectedProtocolMessage Members
+
+ public HttpDeliveryMethods HttpMethods {
+ get { throw new NotImplementedException(); }
+ }
+
+ public Uri Recipient {
+ get { throw new NotImplementedException(); }
+ }
+
+ #endregion
+
+ #region IProtocolMessage Members
+
+ public MessageProtections RequiredProtection {
+ get { throw new NotImplementedException(); }
+ }
+
+ public MessageTransport Transport {
+ get { throw new NotImplementedException(); }
+ }
+
+ #endregion
+
+ #region IMessage Members
+
+ public Version Version {
+ get { throw new NotImplementedException(); }
+ }
+
+ public System.Collections.Generic.IDictionary<string, string> ExtraData {
+ get { throw new NotImplementedException(); }
+ }
+
+ public void EnsureValidMessage() {
+ throw new NotImplementedException();
+ }
+
+ #endregion
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs
index 62ea871..a744053 100644
--- a/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/CoordinatingOutgoingWebResponse.cs
@@ -7,6 +7,7 @@
namespace DotNetOpenAuth.Test.Mocks {
using System;
using System.Collections.Generic;
+ using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
@@ -28,7 +29,12 @@ namespace DotNetOpenAuth.Test.Mocks {
this.OriginalMessage = message;
}
+ [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use the Respond method instead, and prepare for execution to continue on this page beyond the call to Respond.")]
public override void Send() {
+ this.Respond();
+ }
+
+ public override void Respond() {
this.receivingChannel.PostMessage(this.OriginalMessage);
}
}
diff --git a/src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs b/src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs
index 439acbb..515e69e 100644
--- a/src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/TestBadChannel.cs
@@ -17,8 +17,8 @@ namespace DotNetOpenAuth.Test.Mocks {
: base(badConstructorParam ? null : new TestMessageFactory()) {
}
- internal new void Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) {
- base.Create301RedirectResponse(message, fields);
+ internal new void Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields, bool payloadInFragment = false) {
+ base.Create301RedirectResponse(message, fields, payloadInFragment);
}
internal new void CreateFormPostResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) {
diff --git a/src/DotNetOpenAuth.Test/Mocks/TestDirectResponseMessageWithHttpStatus.cs b/src/DotNetOpenAuth.Test/Mocks/TestDirectResponseMessageWithHttpStatus.cs
index d692320..20fd6c4 100644
--- a/src/DotNetOpenAuth.Test/Mocks/TestDirectResponseMessageWithHttpStatus.cs
+++ b/src/DotNetOpenAuth.Test/Mocks/TestDirectResponseMessageWithHttpStatus.cs
@@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Test.Mocks {
using System;
using System.Collections.Generic;
using System.Linq;
+ using System.Net;
using System.Text;
using DotNetOpenAuth.Messaging;
@@ -23,8 +24,15 @@ namespace DotNetOpenAuth.Test.Mocks {
/// <summary>
/// Gets or sets the HTTP status code that the direct respones should be sent with.
/// </summary>
- /// <value></value>
- public System.Net.HttpStatusCode HttpStatusCode { get; set; }
+ public HttpStatusCode HttpStatusCode { get; set; }
+
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ /// <value>May be an empty collection, but must not be <c>null</c>.</value>
+ public WebHeaderCollection Headers {
+ get { return new WebHeaderCollection(); }
+ }
#endregion
}
diff --git a/src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs b/src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs
new file mode 100644
index 0000000..e6237ca
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs
@@ -0,0 +1,127 @@
+//-----------------------------------------------------------------------
+// <copyright file="MessageFactoryTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+ using DotNetOpenAuth.OAuth2.Messages;
+ using Moq;
+ using NUnit.Framework;
+
+ /// <summary>
+ /// Verifies that the WRAP message types are recognized.
+ /// </summary>
+ public class MessageFactoryTests : OAuth2TestBase {
+ private readonly MessageReceivingEndpoint recipient = new MessageReceivingEndpoint("http://who", HttpDeliveryMethods.PostRequest);
+ private OAuth2AuthorizationServerChannel channel;
+ private IMessageFactory messageFactory;
+
+ public override void SetUp() {
+ base.SetUp();
+
+ this.channel = new OAuth2AuthorizationServerChannel(new Mock<IAuthorizationServer>().Object);
+ this.messageFactory = this.channel.MessageFactoryTestHook;
+ }
+
+ #region End user authorization messages
+
+ [TestCase]
+ public void EndUserAuthorizationRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.response_type, "code" },
+ { Protocol.client_id, "abc" },
+ { Protocol.redirect_uri, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(EndUserAuthorizationRequest), request);
+ }
+
+ [TestCase]
+ public void EndUserAuthorizationSuccessResponseWithCode() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.code, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(EndUserAuthorizationSuccessResponseBase), request);
+ }
+
+ [TestCase, Ignore("Not yet supported")]
+ public void EndUserAuthorizationSuccessResponseWithAccessToken() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.access_token, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(EndUserAuthorizationSuccessResponseBase), request);
+ }
+
+ [TestCase]
+ public void EndUserAuthorizationFailedResponse() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.error, "access-denied" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(EndUserAuthorizationFailedResponse), request);
+ }
+
+ #endregion
+
+ #region Access token request messages
+
+ [TestCase]
+ public void AccessTokenRefreshRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.refresh_token, "abc" },
+ { Protocol.grant_type, "refresh-token" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(AccessTokenRefreshRequest), request);
+ }
+
+ [TestCase]
+ public void AccessTokenAuthorizationCodeRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.code, "code" },
+ { Protocol.grant_type, "authorization-code" },
+ { Protocol.redirect_uri, "http://someUri" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(AccessTokenAuthorizationCodeRequest), request);
+ }
+
+ [TestCase]
+ public void AccessTokenBasicCredentialsRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.client_secret, "abc" },
+ { Protocol.grant_type, "basic-credentials" },
+ { Protocol.username, "abc" },
+ { Protocol.password, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(AccessTokenResourceOwnerPasswordCredentialsRequest), request);
+ }
+
+ [TestCase]
+ public void AccessTokenClientCredentialsRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.client_secret, "abc" },
+ { Protocol.grant_type, "none" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(AccessTokenClientCredentialsRequest), request);
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs b/src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs
new file mode 100644
index 0000000..c263eb6
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs
@@ -0,0 +1,21 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuth2ChannelTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+ using DotNetOpenAuth.OAuth2.Messages;
+ using NUnit.Framework;
+
+ [TestFixture]
+ public class OAuth2ChannelTests : OAuth2TestBase {
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs b/src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs
new file mode 100644
index 0000000..6c13c5e
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs
@@ -0,0 +1,15 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuth2TestBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ public class OAuth2TestBase : TestBase {
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs
index 390a5f1..9c9e446 100644
--- a/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/AssociationHandshakeTests.cs
@@ -87,7 +87,7 @@ namespace DotNetOpenAuth.Test.OpenId {
// Ensure that the response is a suggestion that the RP try again with HMAC-SHA1
AssociateUnsuccessfulResponse renegotiateResponse = (AssociateUnsuccessfulResponse)req.ResponseMessageTestHook;
Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, renegotiateResponse.AssociationType);
- op.SendResponse(req);
+ op.Respond(req);
// Receive second attempt request for an HMAC-SHA1 association.
req = (AutoResponsiveRequest)op.GetRequest();
@@ -97,7 +97,7 @@ namespace DotNetOpenAuth.Test.OpenId {
// Ensure that the response is a success response.
AssociateSuccessfulResponse successResponse = (AssociateSuccessfulResponse)req.ResponseMessageTestHook;
Assert.AreEqual(protocol.Args.SignatureAlgorithm.HMAC_SHA1, successResponse.AssociationType);
- op.SendResponse(req);
+ op.Respond(req);
});
coordinator.Run();
}
@@ -168,7 +168,7 @@ namespace DotNetOpenAuth.Test.OpenId {
AssociateUnsuccessfulResponse renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request);
renegotiateResponse.AssociationType = "HMAC-UNKNOWN";
renegotiateResponse.SessionType = "DH-UNKNOWN";
- op.Channel.Send(renegotiateResponse);
+ op.Channel.Respond(renegotiateResponse);
});
coordinator.Run();
}
@@ -195,7 +195,7 @@ namespace DotNetOpenAuth.Test.OpenId {
AssociateUnsuccessfulResponse renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request);
renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA1;
renegotiateResponse.SessionType = protocol.Args.SessionType.NoEncryption;
- op.Channel.Send(renegotiateResponse);
+ op.Channel.Respond(renegotiateResponse);
});
coordinator.Run();
}
@@ -220,7 +220,7 @@ namespace DotNetOpenAuth.Test.OpenId {
AssociateUnsuccessfulResponse renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request);
renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA1;
renegotiateResponse.SessionType = protocol.Args.SessionType.DH_SHA256;
- op.Channel.Send(renegotiateResponse);
+ op.Channel.Respond(renegotiateResponse);
});
coordinator.Run();
}
@@ -245,7 +245,7 @@ namespace DotNetOpenAuth.Test.OpenId {
AssociateUnsuccessfulResponse renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request);
renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA1;
renegotiateResponse.SessionType = protocol.Args.SessionType.DH_SHA1;
- op.Channel.Send(renegotiateResponse);
+ op.Channel.Respond(renegotiateResponse);
// Receive second-try
request = op.Channel.ReadFromRequest<AssociateRequest>();
@@ -254,7 +254,7 @@ namespace DotNetOpenAuth.Test.OpenId {
renegotiateResponse = new AssociateUnsuccessfulResponse(request.Version, request);
renegotiateResponse.AssociationType = protocol.Args.SignatureAlgorithm.HMAC_SHA256;
renegotiateResponse.SessionType = protocol.Args.SessionType.DH_SHA256;
- op.Channel.Send(renegotiateResponse);
+ op.Channel.Respond(renegotiateResponse);
});
coordinator.Run();
}
@@ -332,7 +332,7 @@ namespace DotNetOpenAuth.Test.OpenId {
IRequest req = op.GetRequest();
Assert.IsNotNull(req, "Expected incoming request but did not receive it.");
Assert.IsTrue(req.IsResponseReady);
- op.SendResponse(req);
+ op.Respond(req);
});
coordinator.IncomingMessageFilter = message => {
Assert.AreSame(opDescription.Version, message.Version, "The message was recognized as version {0} but was expected to be {1}.", message.Version, Protocol.Lookup(opDescription.Version).ProtocolVersion);
@@ -352,9 +352,10 @@ namespace DotNetOpenAuth.Test.OpenId {
if (expectSuccess) {
Assert.IsNotNull(rpAssociation);
- Assert.AreSame(rpAssociation, coordinator.RelyingParty.AssociationManager.AssociationStoreTestHook.GetAssociation(opDescription.Uri, rpAssociation.Handle));
- opAssociation = coordinator.Provider.AssociationStore.GetAssociation(AssociationRelyingPartyType.Smart, rpAssociation.Handle);
- Assert.IsNotNull(opAssociation, "The Provider should have stored the association.");
+ Association actual = coordinator.RelyingParty.AssociationManager.AssociationStoreTestHook.GetAssociation(opDescription.Uri, rpAssociation.Handle);
+ Assert.AreEqual(rpAssociation, actual);
+ opAssociation = coordinator.Provider.AssociationStore.Deserialize(new TestSignedDirectedMessage(), false, rpAssociation.Handle);
+ Assert.IsNotNull(opAssociation, "The Provider could not decode the association handle.");
Assert.AreEqual(opAssociation.Handle, rpAssociation.Handle);
Assert.AreEqual(expectedAssociationType, rpAssociation.GetAssociationType(protocol));
@@ -372,7 +373,6 @@ namespace DotNetOpenAuth.Test.OpenId {
}
} else {
Assert.IsNull(coordinator.RelyingParty.AssociationManager.AssociationStoreTestHook.GetAssociation(opDescription.Uri, new RelyingPartySecuritySettings()));
- Assert.IsNull(coordinator.Provider.AssociationStore.GetAssociation(AssociationRelyingPartyType.Smart, new ProviderSecuritySettings()));
}
}
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs b/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs
index 27db93e..99565ed 100644
--- a/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/AuthenticationTests.cs
@@ -138,8 +138,10 @@ namespace DotNetOpenAuth.Test.OpenId {
private void ParameterizedAuthenticationTest(Protocol protocol, bool statelessRP, bool sharedAssociation, bool positive, bool immediate, bool tamper) {
Contract.Requires<ArgumentException>(!statelessRP || !sharedAssociation, "The RP cannot be stateless while sharing an association with the OP.");
Contract.Requires<ArgumentException>(positive || !tamper, "Cannot tamper with a negative response.");
- ProviderSecuritySettings securitySettings = new ProviderSecuritySettings();
- Association association = sharedAssociation ? HmacShaAssociation.Create(protocol, protocol.Args.SignatureAlgorithm.Best, AssociationRelyingPartyType.Smart, securitySettings) : null;
+ var securitySettings = new ProviderSecuritySettings();
+ var cryptoKeyStore = new MemoryCryptoKeyStore();
+ var associationStore = new ProviderAssociationHandleEncoder(cryptoKeyStore);
+ Association association = sharedAssociation ? HmacShaAssociation.Create(protocol, protocol.Args.SignatureAlgorithm.Best, AssociationRelyingPartyType.Smart, associationStore, securitySettings) : null;
var coordinator = new OpenIdCoordinator(
rp => {
var request = new CheckIdRequest(protocol.Version, OPUri, immediate ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup);
@@ -153,7 +155,7 @@ namespace DotNetOpenAuth.Test.OpenId {
request.LocalIdentifier = "http://localid";
request.ReturnTo = RPUri;
request.Realm = RPUri;
- rp.Channel.Send(request);
+ rp.Channel.Respond(request);
if (positive) {
if (tamper) {
try {
@@ -197,7 +199,8 @@ namespace DotNetOpenAuth.Test.OpenId {
},
op => {
if (association != null) {
- op.AssociationStore.StoreAssociation(AssociationRelyingPartyType.Smart, association);
+ var key = cryptoKeyStore.GetCurrentKey(ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, TimeSpan.FromSeconds(1));
+ op.CryptoKeyStore.StoreKey(ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, key.Key, key.Value);
}
var request = op.Channel.ReadFromRequest<CheckIdRequest>();
@@ -208,20 +211,20 @@ namespace DotNetOpenAuth.Test.OpenId {
} else {
response = new NegativeAssertionResponse(request, op.Channel);
}
- op.Channel.Send(response);
+ op.Channel.Respond(response);
if (positive && (statelessRP || !sharedAssociation)) {
var checkauthRequest = op.Channel.ReadFromRequest<CheckAuthenticationRequest>();
var checkauthResponse = new CheckAuthenticationResponse(checkauthRequest.Version, checkauthRequest);
checkauthResponse.IsValid = checkauthRequest.IsValid;
- op.Channel.Send(checkauthResponse);
+ op.Channel.Respond(checkauthResponse);
if (!tamper) {
// Respond to the replay attack.
checkauthRequest = op.Channel.ReadFromRequest<CheckAuthenticationRequest>();
checkauthResponse = new CheckAuthenticationResponse(checkauthRequest.Version, checkauthRequest);
checkauthResponse.IsValid = checkauthRequest.IsValid;
- op.Channel.Send(checkauthResponse);
+ op.Channel.Respond(checkauthResponse);
}
}
});
diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs
index 5edd51f..5f1fc45 100644
--- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/ExtensionsBindingElementTests.cs
@@ -128,11 +128,11 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
},
op => {
RegisterMockExtension(op.Channel);
- op.Channel.Send(CreateResponseWithExtensions(protocol));
- op.SendResponse(op.GetRequest()); // check_auth
+ op.Channel.Respond(CreateResponseWithExtensions(protocol));
+ op.Respond(op.GetRequest()); // check_auth
op.SecuritySettings.SignOutgoingExtensions = false;
- op.Channel.Send(CreateResponseWithExtensions(protocol));
- op.SendResponse(op.GetRequest()); // check_auth
+ op.Channel.Respond(CreateResponseWithExtensions(protocol));
+ op.Respond(op.GetRequest()); // check_auth
});
coordinator.Run();
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs
index eaaef34..5e0ccf5 100644
--- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/OpenIdChannelTests.cs
@@ -29,7 +29,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
[SetUp]
public void Setup() {
this.webHandler = new Mocks.TestWebRequestHandler();
- this.channel = new OpenIdChannel(new AssociationMemoryStore<Uri>(), new NonceMemoryStore(maximumMessageAge), new RelyingPartySecuritySettings());
+ this.channel = new OpenIdChannel(new MemoryCryptoKeyStore(), new NonceMemoryStore(maximumMessageAge), new RelyingPartySecuritySettings());
this.channel.WebRequestHandler = this.webHandler;
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs
index 6160680..e6f3e6e 100644
--- a/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/ChannelElements/SigningBindingElementTests.cs
@@ -7,6 +7,7 @@
namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
using System;
using System.Linq;
+ using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.ChannelElements;
using DotNetOpenAuth.OpenId.Messages;
@@ -23,10 +24,12 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
public void SignaturesMatchKnownGood() {
Protocol protocol = Protocol.V20;
var settings = new ProviderSecuritySettings();
- var store = new AssociationMemoryStore<AssociationRelyingPartyType>();
+ var cryptoStore = new MemoryCryptoKeyStore();
byte[] associationSecret = Convert.FromBase64String("rsSwv1zPWfjPRQU80hciu8FPDC+GONAMJQ/AvSo1a2M=");
- Association association = HmacShaAssociation.Create("mock", associationSecret, TimeSpan.FromDays(1));
- store.StoreAssociation(AssociationRelyingPartyType.Smart, association);
+ string handle = "mock";
+ cryptoStore.StoreKey(ProviderAssociationKeyStorage.SharedAssociationBucket, handle, new CryptoKey(associationSecret, DateTime.UtcNow.AddDays(1)));
+
+ var store = new ProviderAssociationKeyStorage(cryptoStore);
SigningBindingElement signer = new SigningBindingElement(store, settings);
signer.Channel = new TestChannel(this.MessageDescriptions);
@@ -34,7 +37,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
ITamperResistantOpenIdMessage signedMessage = message;
message.ProviderEndpoint = new Uri("http://provider");
signedMessage.UtcCreationDate = DateTime.Parse("1/1/2009");
- signedMessage.AssociationHandle = association.Handle;
+ signedMessage.AssociationHandle = handle;
Assert.IsNotNull(signer.ProcessOutgoingMessage(message));
Assert.AreEqual("o9+uN7qTaUS9v0otbHTuNAtbkpBm14+es9QnNo6IHD4=", signedMessage.Signature);
}
@@ -45,7 +48,7 @@ namespace DotNetOpenAuth.Test.OpenId.ChannelElements {
[TestCase]
public void SignedResponsesIncludeExtraDataInSignature() {
Protocol protocol = Protocol.Default;
- SigningBindingElement sbe = new SigningBindingElement(new AssociationMemoryStore<AssociationRelyingPartyType>(), new ProviderSecuritySettings());
+ SigningBindingElement sbe = new SigningBindingElement(new ProviderAssociationHandleEncoder(new MemoryCryptoKeyStore()), new ProviderSecuritySettings());
sbe.Channel = new TestChannel(this.MessageDescriptions);
IndirectSignedResponse response = new IndirectSignedResponse(protocol.Version, RPUri);
response.ReturnTo = RPUri;
diff --git a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs
index 334fc93..0f40bc3 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Extensions/ExtensionTestUtilities.cs
@@ -10,6 +10,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
using System.Diagnostics.Contracts;
using System.Linq;
using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.ChannelElements;
using DotNetOpenAuth.OpenId.Extensions;
@@ -33,8 +34,10 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
Protocol protocol,
IEnumerable<IOpenIdMessageExtension> requests,
IEnumerable<IOpenIdMessageExtension> responses) {
- ProviderSecuritySettings securitySettings = new ProviderSecuritySettings();
- Association association = HmacShaAssociation.Create(protocol, protocol.Args.SignatureAlgorithm.Best, AssociationRelyingPartyType.Smart, securitySettings);
+ var securitySettings = new ProviderSecuritySettings();
+ var cryptoKeyStore = new MemoryCryptoKeyStore();
+ var associationStore = new ProviderAssociationHandleEncoder(cryptoKeyStore);
+ Association association = HmacShaAssociation.Create(protocol, protocol.Args.SignatureAlgorithm.Best, AssociationRelyingPartyType.Smart, associationStore, securitySettings);
var coordinator = new OpenIdCoordinator(
rp => {
RegisterExtension(rp.Channel, Mocks.MockOpenIdExtension.Factory);
@@ -49,7 +52,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
requestBase.Extensions.Add(extension);
}
- rp.Channel.Send(requestBase);
+ rp.Channel.Respond(requestBase);
var response = rp.Channel.ReadFromRequest<PositiveAssertionResponse>();
var receivedResponses = response.Extensions.Cast<IOpenIdMessageExtension>();
@@ -57,7 +60,8 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
},
op => {
RegisterExtension(op.Channel, Mocks.MockOpenIdExtension.Factory);
- op.AssociationStore.StoreAssociation(AssociationRelyingPartyType.Smart, association);
+ var key = cryptoKeyStore.GetCurrentKey(ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, TimeSpan.FromSeconds(1));
+ op.CryptoKeyStore.StoreKey(ProviderAssociationHandleEncoder.AssociationHandleEncodingSecretBucket, key.Key, key.Value);
var request = op.Channel.ReadFromRequest<CheckIdRequest>();
var response = new PositiveAssertionResponse(request);
var receivedRequests = request.Extensions.Cast<IOpenIdMessageExtension>();
@@ -67,7 +71,7 @@ namespace DotNetOpenAuth.Test.OpenId.Extensions {
response.Extensions.Add(extensionResponse);
}
- op.Channel.Send(response);
+ op.Channel.Respond(response);
});
coordinator.Run();
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs b/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs
index 17ab090..6e3a289 100644
--- a/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/NonIdentityTests.cs
@@ -21,7 +21,7 @@ namespace DotNetOpenAuth.Test.OpenId {
var coordinator = new OpenIdCoordinator(
rp => {
var request = new SignedResponseRequest(protocol.Version, OPUri, mode);
- rp.Channel.Send(request);
+ rp.Channel.Respond(request);
},
op => {
var request = op.Channel.ReadFromRequest<SignedResponseRequest>();
@@ -38,18 +38,18 @@ namespace DotNetOpenAuth.Test.OpenId {
var request = rp.CreateRequest(GetMockIdentifier(protocol.ProtocolVersion), RPRealmUri, RPUri);
request.IsExtensionOnly = true;
- rp.Channel.Send(request.RedirectingResponse.OriginalMessage);
+ rp.Channel.Respond(request.RedirectingResponse.OriginalMessage);
IAuthenticationResponse response = rp.GetResponse();
Assert.AreEqual(AuthenticationStatus.ExtensionsOnly, response.Status);
},
op => {
var assocRequest = op.GetRequest();
- op.SendResponse(assocRequest);
+ op.Respond(assocRequest);
var request = (IAnonymousRequest)op.GetRequest();
request.IsApproved = true;
Assert.IsNotInstanceOf<CheckIdRequest>(request);
- op.SendResponse(request);
+ op.Respond(request);
});
coordinator.Run();
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs
index 414585f..4143a08 100644
--- a/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/OpenIdTestBase.cs
@@ -171,7 +171,7 @@ namespace DotNetOpenAuth.Test.OpenId {
}
}
- provider.SendResponse(request);
+ provider.Respond(request);
}
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs
index 75d871c..c8c3831 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Provider/OpenIdProviderTests.cs
@@ -105,7 +105,7 @@ namespace DotNetOpenAuth.Test.OpenId.Provider {
op => {
IRequest request = op.GetRequest();
Assert.IsInstanceOf<AutoResponsiveRequest>(request);
- op.SendResponse(request);
+ op.Respond(request);
});
coordinator.Run();
}
diff --git a/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs b/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs
index 4530982..365c5c5 100644
--- a/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/Provider/PerformanceTests.cs
@@ -78,8 +78,8 @@ namespace DotNetOpenAuth.Test.OpenId.Provider {
protocol,
assocType,
AssociationRelyingPartyType.Smart,
+ this.provider.AssociationStore,
this.provider.SecuritySettings);
- this.provider.AssociationStore.StoreAssociation(AssociationRelyingPartyType.Smart, assoc);
var checkidRequest = this.CreateCheckIdRequest(true);
MeasurePerformance(
() => {
diff --git a/src/DotNetOpenAuth.Test/OpenId/AssociationsTests.cs b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AssociationsTests.cs
index b3d7e4d..531fb45 100644
--- a/src/DotNetOpenAuth.Test/OpenId/AssociationsTests.cs
+++ b/src/DotNetOpenAuth.Test/OpenId/RelyingParty/AssociationsTests.cs
@@ -4,13 +4,14 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace DotNetOpenAuth.Test.OpenId {
+namespace DotNetOpenAuth.Test.OpenId.RelyingParty {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using DotNetOpenAuth.OpenId;
+ using DotNetOpenAuth.OpenId.RelyingParty;
using NUnit.Framework;
[TestFixture]
diff --git a/src/DotNetOpenAuth.TestWeb/OpenIdProviderEndpoint.ashx b/src/DotNetOpenAuth.TestWeb/OpenIdProviderEndpoint.ashx
index b282a3b..ca23eac 100644
--- a/src/DotNetOpenAuth.TestWeb/OpenIdProviderEndpoint.ashx
+++ b/src/DotNetOpenAuth.TestWeb/OpenIdProviderEndpoint.ashx
@@ -13,7 +13,7 @@ public class OpenIdProviderEndpoint : IHttpHandler {
authRequest.IsAuthenticated = true;
}
- provider.SendResponse(request);
+ provider.Respond(request);
}
}
diff --git a/src/DotNetOpenAuth.sln b/src/DotNetOpenAuth.sln
index cf7f97e..2fd5b89 100644
--- a/src/DotNetOpenAuth.sln
+++ b/src/DotNetOpenAuth.sln
@@ -14,6 +14,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Specs", "Specs", "{CD57219F-24F4-4136-8741-6063D0D7A031}"
ProjectSection(SolutionItems) = preProject
+ ..\doc\specs\draft-ietf-oauth-v2-16.txt = ..\doc\specs\draft-ietf-oauth-v2-16.txt
+ ..\doc\specs\draft-ietf-oauth.html = ..\doc\specs\draft-ietf-oauth.html
..\doc\specs\ICAM_OpenID20Profile.pdf = ..\doc\specs\ICAM_OpenID20Profile.pdf
..\doc\specs\OAuth Core 1.0.htm = ..\doc\specs\OAuth Core 1.0.htm
..\doc\specs\OAuth Core 1.0a (Draft 3).htm = ..\doc\specs\OAuth Core 1.0a (Draft 3).htm
@@ -140,12 +142,14 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenIdWebRingSsoProvider",
EndProject
Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "OpenIdRelyingPartyWebFormsVB", "..\samples\OpenIdRelyingPartyWebFormsVB\OpenIdRelyingPartyWebFormsVB.vbproj", "{F289B925-4307-4BEC-B411-885CE70E3379}"
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuthConsumer", "..\samples\OAuthConsumer\OAuthConsumer.csproj", "{9529606E-AF76-4387-BFB7-3D10A5B399AA}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuthClient", "..\samples\OAuthClient\OAuthClient.csproj", "{9529606E-AF76-4387-BFB7-3D10A5B399AA}"
ProjectSection(ProjectDependencies) = postProject
{E135F455-0669-49F8-9207-07FCA8C8FC79} = {E135F455-0669-49F8-9207-07FCA8C8FC79}
EndProjectSection
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuthServiceProvider", "..\samples\OAuthServiceProvider\OAuthServiceProvider.csproj", "{E135F455-0669-49F8-9207-07FCA8C8FC79}"
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuthResourceServer", "..\samples\OAuthResourceServer\OAuthResourceServer.csproj", "{E135F455-0669-49F8-9207-07FCA8C8FC79}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OAuthAuthorizationServer", "..\samples\OAuthAuthorizationServer\OAuthAuthorizationServer.csproj", "{C78E8235-1D46-43EB-A912-80B522C4E9AE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -306,6 +310,14 @@ Global
{E135F455-0669-49F8-9207-07FCA8C8FC79}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E135F455-0669-49F8-9207-07FCA8C8FC79}.Release|Any CPU.Build.0 = Release|Any CPU
{E135F455-0669-49F8-9207-07FCA8C8FC79}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.CodeAnalysis|Any CPU.ActiveCfg = Release|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.CodeAnalysis|Any CPU.Build.0 = Release|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.Release|Any CPU.Build.0 = Release|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.ReleaseNoUI|Any CPU.ActiveCfg = Release|Any CPU
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE}.ReleaseNoUI|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -327,6 +339,7 @@ Global
{6EC36418-DBC5-4AD1-A402-413604AA7A08} = {1E2CBAA5-60A3-4AED-912E-541F5753CDC6}
{9529606E-AF76-4387-BFB7-3D10A5B399AA} = {1E2CBAA5-60A3-4AED-912E-541F5753CDC6}
{E135F455-0669-49F8-9207-07FCA8C8FC79} = {1E2CBAA5-60A3-4AED-912E-541F5753CDC6}
+ {C78E8235-1D46-43EB-A912-80B522C4E9AE} = {1E2CBAA5-60A3-4AED-912E-541F5753CDC6}
{6EB90284-BD15-461C-BBF2-131CF55F7C8B} = {8A5CEDB9-7F8A-4BE2-A1B9-97130F453277}
{5C65603B-235F-47E6-B536-06385C60DE7F} = {E9ED920D-1F83-48C0-9A4B-09CCE505FE6D}
{A78F8FC6-7B03-4230-BE41-761E400D6810} = {B9EB8729-4B54-4453-B089-FE6761BA3057}
diff --git a/src/DotNetOpenAuth/CodeAnalysisDictionary.xml b/src/DotNetOpenAuth/CodeAnalysisDictionary.xml
new file mode 100644
index 0000000..8c90df3
--- /dev/null
+++ b/src/DotNetOpenAuth/CodeAnalysisDictionary.xml
@@ -0,0 +1,71 @@
+<?xml version="1.0" encoding="utf-8" ?>
+<Dictionary>
+ <Words>
+ <!--
+ This is a list of case-insensitive words that exist in the dictionary
+ but you do not want to be recognized by IdentifiersShouldBeSpelledCorrectly.
+ Do not add deprecated terms to this list, instead add these to the
+ <Deprecated> section below.
+ -->
+ <Unrecognized>
+ <!--<Word>cb</Word>-->
+ </Unrecognized>
+ <!--
+ This is a list of case-insensitive words that do not exist in the dictionary
+ but you still want to be considered as recognized by
+ IdentifiersShouldBeSpelledCorrectly. Do not add compound words (e.g. 'FileName')
+ to this list as this will cause CompoundWordsShouldBeBeCasedCorrectly to fire on
+ usages of the compound word stating that they should be changed to their discrete equivalent
+ (for example 'FileName' -> 'Filename').
+ -->
+ <Recognized>
+ <Word>OAuth</Word>
+ <!--<Word>cryptoKeyStore</Word>
+ <Word>containingMessage</Word>
+ <Word>httpRequestInfo</Word>
+ <Word>faultedMessage</Word>
+ <Word>keyStore</Word>
+ <Word>authorizationServer</Word>
+ <Word>bytesToSign</Word>
+ <Word>clientCallback</Word>-->
+ </Recognized>
+ <Deprecated>
+ <!--
+ This is a list of deprecated terms with their preferred alternates and is
+ used by UsePreferredTerms. The deprecated terms are case-insensitive,
+ however, make sure to pascal-case the preferred alternates. If a word
+ does not have a preferred alternate, simply leave it blank.
+ -->
+ <!--<Term PreferredAlternate="EnterpriseServices">complus</Term>-->
+ </Deprecated>
+ <Compound>
+ <!--
+ This is a list of discrete terms with their compound alternates and is used by
+ CompoundWordsShouldBeCasedCorrectly. These are words that exist in the
+ dictionary as discrete terms, however, should actually be cased as compound words.
+ For example, 'Filename' exists in the dictionary and hence the spelling rules will
+ not see it as unrecognized but its actual preferred usage is 'FileName'; adding it
+ below causes CompoundWordsShouldBeCasedCorrectly to fire. The discrete terms are
+ case-insensitive, however, be sure to pascal-case the compound alternates.
+ Any discrete terms added below automatically get added to the list of discrete
+ exceptions to prevent CompoundWordsShouldBeCasedCorrectly from firing both on the
+ compound word (for example 'WhiteSpace') and its discrete alternate (for example
+ 'Whitespace').
+ -->
+ <Term CompoundAlternate="OAuth">oauth</Term>
+ <!--<Term CompoundAlternate="DataBind">databind</Term>-->
+ </Compound>
+ <DiscreteExceptions>
+ <!--
+ This is a list of case-insensitive exceptions to the CompoundWordsShouldBeCasedCorrectly
+ discrete term check. As this check works solely on the basis of whether two consecutive
+ tokens exists in the dictionary, it can have a high false positive rate. For example,
+ 'onset' exists in the dictionary but the user probably intended it to be 'OnSet'.
+ Adding this word below prevents this rule from firing telling the user to change 'OnSet'
+ to 'Onset'.
+ -->
+ <Term>oauth</Term>
+ <!--<Term>onset</Term>-->
+ </DiscreteExceptions>
+ </Words>
+</Dictionary> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd b/src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd
index 0b27948..065b5ee 100644
--- a/src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd
+++ b/src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd
@@ -218,6 +218,14 @@
</xs:documentation>
</xs:annotation>
</xs:attribute>
+ <xs:attribute name="relaxSslRequirements" type="xs:boolean" default="false">
+ <xs:annotation>
+ <xs:documentation>
+ Whether SSL requirements within the library are disabled/relaxed.
+ Use for TESTING ONLY.
+ </xs:documentation>
+ </xs:annotation>
+ </xs:attribute>
<xs:attribute name="maximumIndirectMessageUrlLength" type="xs:int" default="2048">
<xs:annotation>
<xs:documentation>
@@ -228,6 +236,13 @@
</xs:documentation>
</xs:annotation>
</xs:attribute>
+ <xs:attribute name="privateSecretMaximumAge" type="xs:string" default="28.00:00:00">
+ <xs:annotation>
+ <xs:documentation>
+ The maximum age of a secret used for private signing or encryption before it is renewed.
+ </xs:documentation>
+ </xs:annotation>
+ </xs:attribute>
</xs:complexType>
</xs:element>
<xs:element name="openid">
@@ -330,13 +345,6 @@
</xs:documentation>
</xs:annotation>
</xs:attribute>
- <xs:attribute name="privateSecretMaximumAge" type="xs:string">
- <xs:annotation>
- <xs:documentation>
- The maximum age of a secret used for private signing before it is renewed.
- </xs:documentation>
- </xs:annotation>
- </xs:attribute>
<xs:attribute name="requireDirectedIdentity" type="xs:boolean">
<xs:annotation>
<xs:documentation>
@@ -573,6 +581,15 @@
</xs:documentation>
</xs:annotation>
</xs:attribute>
+ <xs:attribute name="encodeAssociationSecretsInHandles" type="xs:boolean" default="true">
+ <xs:annotation>
+ <xs:documentation>
+ Whether the Provider should ease the burden of storing associations
+ by encoding their secrets (in signed, encrypted form) into the association handles themselves, storing only
+ a few rotating, private symmetric keys in the Provider's store instead.
+ </xs:documentation>
+ </xs:annotation>
+ </xs:attribute>
<xs:attribute name="unsolicitedAssertionVerification">
<xs:annotation>
<xs:documentation>
diff --git a/src/DotNetOpenAuth/Configuration/MessagingElement.cs b/src/DotNetOpenAuth/Configuration/MessagingElement.cs
index 28b34a3..1c46bcf 100644
--- a/src/DotNetOpenAuth/Configuration/MessagingElement.cs
+++ b/src/DotNetOpenAuth/Configuration/MessagingElement.cs
@@ -32,6 +32,11 @@ namespace DotNetOpenAuth.Configuration {
private const string MaximumClockSkewConfigName = "clockSkew";
/// <summary>
+ /// The name of the attribute that indicates whether to disable SSL requirements across the library.
+ /// </summary>
+ private const string RelaxSslRequirementsConfigName = "relaxSslRequirements";
+
+ /// <summary>
/// The name of the attribute that controls whether messaging rules are strictly followed.
/// </summary>
private const string StrictConfigName = "strict";
@@ -51,6 +56,11 @@ namespace DotNetOpenAuth.Configuration {
private const string MaximumIndirectMessageUrlLengthConfigName = "maximumIndirectMessageUrlLength";
/// <summary>
+ /// Gets the name of the @privateSecretMaximumAge attribute.
+ /// </summary>
+ private const string PrivateSecretMaximumAgeConfigName = "privateSecretMaximumAge";
+
+ /// <summary>
/// Gets the actual maximum message lifetime that a program should allow.
/// </summary>
/// <value>The sum of the <see cref="MaximumMessageLifetime"/> and
@@ -60,6 +70,17 @@ namespace DotNetOpenAuth.Configuration {
}
/// <summary>
+ /// Gets or sets the maximum lifetime of a private symmetric secret,
+ /// that may be used for signing or encryption.
+ /// </summary>
+ /// <value>The default value is 28 days (twice the age of the longest association).</value>
+ [ConfigurationProperty(PrivateSecretMaximumAgeConfigName, DefaultValue = "28.00:00:00")]
+ public TimeSpan PrivateSecretMaximumAge {
+ get { return (TimeSpan)this[PrivateSecretMaximumAgeConfigName]; }
+ set { this[PrivateSecretMaximumAgeConfigName] = value; }
+ }
+
+ /// <summary>
/// Gets or sets the time between a message's creation and its receipt
/// before it is considered expired.
/// </summary>
@@ -102,6 +123,16 @@ namespace DotNetOpenAuth.Configuration {
}
/// <summary>
+ /// Gets or sets a value indicating whether SSL requirements within the library are disabled/relaxed.
+ /// Use for TESTING ONLY.
+ /// </summary>
+ [ConfigurationProperty(RelaxSslRequirementsConfigName, DefaultValue = false)]
+ internal bool RelaxSslRequirements {
+ get { return (bool)this[RelaxSslRequirementsConfigName]; }
+ set { this[RelaxSslRequirementsConfigName] = value; }
+ }
+
+ /// <summary>
/// Gets or sets a value indicating whether messaging rules are strictly
/// adhered to.
/// </summary>
diff --git a/src/DotNetOpenAuth/Configuration/OpenIdProviderElement.cs b/src/DotNetOpenAuth/Configuration/OpenIdProviderElement.cs
index b51ccfb..a594e86 100644
--- a/src/DotNetOpenAuth/Configuration/OpenIdProviderElement.cs
+++ b/src/DotNetOpenAuth/Configuration/OpenIdProviderElement.cs
@@ -7,6 +7,7 @@
namespace DotNetOpenAuth.Configuration {
using System.Configuration;
using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.OpenId;
using DotNetOpenAuth.OpenId.Provider;
/// <summary>
@@ -58,8 +59,8 @@ namespace DotNetOpenAuth.Configuration {
/// Gets or sets the type to use for storing application state.
/// </summary>
[ConfigurationProperty(StoreConfigName)]
- public TypeConfigurationElement<IProviderApplicationStore> ApplicationStore {
- get { return (TypeConfigurationElement<IProviderApplicationStore>)this[StoreConfigName] ?? new TypeConfigurationElement<IProviderApplicationStore>(); }
+ public TypeConfigurationElement<IOpenIdApplicationStore> ApplicationStore {
+ get { return (TypeConfigurationElement<IOpenIdApplicationStore>)this[StoreConfigName] ?? new TypeConfigurationElement<IOpenIdApplicationStore>(); }
set { this[StoreConfigName] = value; }
}
}
diff --git a/src/DotNetOpenAuth/Configuration/OpenIdProviderSecuritySettingsElement.cs b/src/DotNetOpenAuth/Configuration/OpenIdProviderSecuritySettingsElement.cs
index 3545fc5..0d8e8b4 100644
--- a/src/DotNetOpenAuth/Configuration/OpenIdProviderSecuritySettingsElement.cs
+++ b/src/DotNetOpenAuth/Configuration/OpenIdProviderSecuritySettingsElement.cs
@@ -36,6 +36,11 @@ namespace DotNetOpenAuth.Configuration {
private const string AssociationsConfigName = "associations";
/// <summary>
+ /// The name of the @encodeAssociationSecretsInHandles attribute.
+ /// </summary>
+ private const string EncodeAssociationSecretsInHandlesConfigName = "encodeAssociationSecretsInHandles";
+
+ /// <summary>
/// Gets the name of the @requireSsl attribute.
/// </summary>
private const string RequireSslConfigName = "requireSsl";
@@ -116,6 +121,17 @@ namespace DotNetOpenAuth.Configuration {
}
/// <summary>
+ /// Gets or sets a value indicating whether the Provider should ease the burden of storing associations
+ /// by encoding their secrets (in signed, encrypted form) into the association handles themselves, storing only
+ /// a few rotating, private symmetric keys in the Provider's store instead.
+ /// </summary>
+ [ConfigurationProperty(EncodeAssociationSecretsInHandlesConfigName, DefaultValue = ProviderSecuritySettings.EncodeAssociationSecretsInHandlesDefault)]
+ public bool EncodeAssociationSecretsInHandles {
+ get { return (bool)this[EncodeAssociationSecretsInHandlesConfigName]; }
+ set { this[EncodeAssociationSecretsInHandlesConfigName] = value; }
+ }
+
+ /// <summary>
/// Initializes a programmatically manipulatable bag of these security settings with the settings from the config file.
/// </summary>
/// <returns>The newly created security settings object.</returns>
@@ -126,6 +142,7 @@ namespace DotNetOpenAuth.Configuration {
settings.MaximumHashBitLength = this.MaximumHashBitLength;
settings.ProtectDownlevelReplayAttacks = this.ProtectDownlevelReplayAttacks;
settings.UnsolicitedAssertionVerification = this.UnsolicitedAssertionVerification;
+ settings.EncodeAssociationSecretsInHandles = this.EncodeAssociationSecretsInHandles;
foreach (AssociationTypeElement element in this.AssociationLifetimes) {
Contract.Assume(element != null);
settings.AssociationLifetimes.Add(element.AssociationType, element.MaximumLifetime);
diff --git a/src/DotNetOpenAuth/Configuration/OpenIdRelyingPartyElement.cs b/src/DotNetOpenAuth/Configuration/OpenIdRelyingPartyElement.cs
index 915776c..17b890f 100644
--- a/src/DotNetOpenAuth/Configuration/OpenIdRelyingPartyElement.cs
+++ b/src/DotNetOpenAuth/Configuration/OpenIdRelyingPartyElement.cs
@@ -87,8 +87,8 @@ namespace DotNetOpenAuth.Configuration {
/// Gets or sets the type to use for storing application state.
/// </summary>
[ConfigurationProperty(StoreConfigName)]
- public TypeConfigurationElement<IRelyingPartyApplicationStore> ApplicationStore {
- get { return (TypeConfigurationElement<IRelyingPartyApplicationStore>)this[StoreConfigName] ?? new TypeConfigurationElement<IRelyingPartyApplicationStore>(); }
+ public TypeConfigurationElement<IOpenIdApplicationStore> ApplicationStore {
+ get { return (TypeConfigurationElement<IOpenIdApplicationStore>)this[StoreConfigName] ?? new TypeConfigurationElement<IOpenIdApplicationStore>(); }
set { this[StoreConfigName] = value; }
}
diff --git a/src/DotNetOpenAuth/Configuration/OpenIdRelyingPartySecuritySettingsElement.cs b/src/DotNetOpenAuth/Configuration/OpenIdRelyingPartySecuritySettingsElement.cs
index 4347e2c..e116f52 100644
--- a/src/DotNetOpenAuth/Configuration/OpenIdRelyingPartySecuritySettingsElement.cs
+++ b/src/DotNetOpenAuth/Configuration/OpenIdRelyingPartySecuritySettingsElement.cs
@@ -61,11 +61,6 @@ namespace DotNetOpenAuth.Configuration {
private const string IgnoreUnsignedExtensionsConfigName = "ignoreUnsignedExtensions";
/// <summary>
- /// Gets the name of the @privateSecretMaximumAge attribute.
- /// </summary>
- private const string PrivateSecretMaximumAgeConfigName = "privateSecretMaximumAge";
-
- /// <summary>
/// Gets the name of the @allowDualPurposeIdentifiers attribute.
/// </summary>
private const string AllowDualPurposeIdentifiersConfigName = "allowDualPurposeIdentifiers";
@@ -152,17 +147,6 @@ namespace DotNetOpenAuth.Configuration {
}
/// <summary>
- /// Gets or sets the maximum allowable age of the secret a Relying Party
- /// uses to its return_to URLs and nonces with 1.0 Providers.
- /// </summary>
- /// <value>The default value is 7 days.</value>
- [ConfigurationProperty(PrivateSecretMaximumAgeConfigName, DefaultValue = "07:00:00")]
- public TimeSpan PrivateSecretMaximumAge {
- get { return (TimeSpan)this[PrivateSecretMaximumAgeConfigName]; }
- set { this[PrivateSecretMaximumAgeConfigName] = value; }
- }
-
- /// <summary>
/// Gets or sets a value indicating whether all unsolicited assertions should be ignored.
/// </summary>
/// <value>The default value is <c>false</c>.</value>
@@ -263,7 +247,7 @@ namespace DotNetOpenAuth.Configuration {
settings.MinimumRequiredOpenIdVersion = this.MinimumRequiredOpenIdVersion;
settings.MinimumHashBitLength = this.MinimumHashBitLength;
settings.MaximumHashBitLength = this.MaximumHashBitLength;
- settings.PrivateSecretMaximumAge = this.PrivateSecretMaximumAge;
+ settings.PrivateSecretMaximumAge = DotNetOpenAuthSection.Configuration.Messaging.PrivateSecretMaximumAge;
settings.RejectUnsolicitedAssertions = this.RejectUnsolicitedAssertions;
settings.RejectDelegatingIdentifiers = this.RejectDelegatingIdentifiers;
settings.IgnoreUnsignedExtensions = this.IgnoreUnsignedExtensions;
diff --git a/src/DotNetOpenAuth/DotNetOpenAuth.csproj b/src/DotNetOpenAuth/DotNetOpenAuth.csproj
index 52930af..be4e21b 100644
--- a/src/DotNetOpenAuth/DotNetOpenAuth.csproj
+++ b/src/DotNetOpenAuth/DotNetOpenAuth.csproj
@@ -217,6 +217,7 @@ http://opensource.org/licenses/ms-pl.html
<RequiredTargetFramework>3.0</RequiredTargetFramework>
</Reference>
<Reference Include="System" />
+ <Reference Include="System.Security" />
<Reference Include="System.configuration" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
@@ -274,6 +275,7 @@ http://opensource.org/licenses/ms-pl.html
<Reference Include="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
</ItemGroup>
<ItemGroup>
+ <Compile Include="Messaging\Bindings\AsymmetricCryptoKeyStoreWrapper.cs" />
<Compile Include="ComponentModel\ClaimTypeSuggestions.cs" />
<Compile Include="ComponentModel\ConverterBase.cs" />
<Compile Include="ComponentModel\SuggestedStringsConverterContract.cs" />
@@ -304,6 +306,9 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="Configuration\HostNameOrRegexCollection.cs" />
<Compile Include="Configuration\HostNameElement.cs" />
<Compile Include="Configuration\XriResolverElement.cs" />
+ <Compile Include="Messaging\Bindings\CryptoKey.cs" />
+ <Compile Include="Messaging\Bindings\CryptoKeyCollisionException.cs" />
+ <Compile Include="Messaging\Bindings\ICryptoKeyStore.cs" />
<Compile Include="IEmbeddedResourceRetrieval.cs" />
<Compile Include="InfoCard\ClaimType.cs" />
<Compile Include="InfoCard\InfoCardImage.cs" />
@@ -317,14 +322,19 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="InfoCard\Token\TokenUtility.cs" />
<Compile Include="InfoCard\Token\TokenDecryptor.cs" />
<Compile Include="InfoCard\WellKnownIssuers.cs" />
+ <Compile Include="Messaging\Bindings\MemoryCryptoKeyStore.cs" />
+ <Compile Include="Messaging\BinaryDataBagFormatter.cs" />
<Compile Include="Messaging\CachedDirectWebResponse.cs" />
<Compile Include="Messaging\ChannelContract.cs" />
+ <Compile Include="Messaging\DataBagFormatterBase.cs" />
+ <Compile Include="Messaging\IHttpIndirectResponse.cs" />
<Compile Include="Messaging\IMessageOriginalPayload.cs" />
<Compile Include="Messaging\DirectWebRequestOptions.cs" />
<Compile Include="Messaging\EnumerableCache.cs" />
<Compile Include="Messaging\HostErrorException.cs" />
<Compile Include="Messaging\IHttpDirectResponse.cs" />
<Compile Include="Messaging\IExtensionMessage.cs" />
+ <Compile Include="Messaging\IHttpDirectResponseContract.cs" />
<Compile Include="Messaging\IMessage.cs" />
<Compile Include="Messaging\IncomingWebResponse.cs" />
<Compile Include="Messaging\IDirectResponseProtocolMessage.cs" />
@@ -336,6 +346,7 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="Messaging\IncomingWebResponseContract.cs" />
<Compile Include="Messaging\IProtocolMessageWithExtensions.cs" />
<Compile Include="Messaging\InternalErrorException.cs" />
+ <Compile Include="Messaging\IStreamSerializingDataBag.cs" />
<Compile Include="Messaging\KeyedCollectionDelegate.cs" />
<Compile Include="Messaging\MultipartPostPart.cs" />
<Compile Include="Messaging\NetworkDirectWebResponse.cs" />
@@ -345,6 +356,59 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="Messaging\Reflection\IMessagePartOriginalEncoder.cs" />
<Compile Include="Messaging\Reflection\MessageDescriptionCollection.cs" />
<Compile Include="Mvc\OpenIdAjaxOptions.cs" />
+ <Compile Include="Messaging\StandardMessageFactory.cs" />
+ <Compile Include="OAuth2\AuthorizationState.cs" />
+ <Compile Include="OAuth2\ChannelElements\AccessRequestBindingElement.cs" />
+ <Compile Include="OAuth2\ChannelElements\AccessToken.cs" />
+ <Compile Include="OAuth2\ChannelElements\AccessTokenBindingElement.cs" />
+ <Compile Include="OAuth2\ChannelElements\AuthorizationDataBag.cs" />
+ <Compile Include="OAuth2\ChannelElements\AuthServerBindingElementBase.cs" />
+ <Compile Include="OAuth2\ChannelElements\GrantTypeEncoder.cs" />
+ <Compile Include="OAuth2\ChannelElements\EndUserAuthorizationResponseTypeEncoder.cs" />
+ <Compile Include="Messaging\IDataBagFormatter.cs" />
+ <Compile Include="OAuth2\ChannelElements\OAuth2ChannelBase.cs" />
+ <Compile Include="OAuth2\ChannelElements\OAuth2ClientChannel.cs" />
+ <Compile Include="OAuth2\ChannelElements\ScopeEncoder.cs" />
+ <Compile Include="Messaging\UriStyleMessageFormatter.cs" />
+ <Compile Include="OAuth2\ChannelElements\IAuthorizationDescription.cs" />
+ <Compile Include="OAuth2\ChannelElements\IAuthorizationCarryingRequest.cs" />
+ <Compile Include="OAuth2\ChannelElements\OAuth2ResourceServerChannel.cs" />
+ <Compile Include="Messaging\StandardMessageFactoryChannel.cs" />
+ <Compile Include="OAuth2\ChannelElements\RefreshToken.cs" />
+ <Compile Include="Messaging\DataBag.cs" />
+ <Compile Include="Messaging\TimestampEncoder.cs" />
+ <Compile Include="OAuth2\ChannelElements\AuthorizationCode.cs" />
+ <Compile Include="OAuth2\ChannelElements\AuthorizationCodeBindingElement.cs" />
+ <Compile Include="OAuth2\ChannelElements\AuthServerAllFlowsBindingElement.cs" />
+ <Compile Include="OAuth2\IAccessTokenAnalyzer.cs" />
+ <Compile Include="OAuth2\IAuthorizationServer.cs" />
+ <Compile Include="OAuth2\IAuthorizationState.cs" />
+ <Compile Include="OAuth2\IClientAuthorizationTracker.cs" />
+ <Compile Include="OAuth2\IConsumerDescription.cs" />
+ <Compile Include="OAuth2\Messages\AccessProtectedResourceRequest.cs" />
+ <Compile Include="OAuth2\Messages\AccessTokenAuthorizationCodeRequest.cs" />
+ <Compile Include="OAuth2\Messages\AccessTokenResourceOwnerPasswordCredentialsRequest.cs" />
+ <Compile Include="OAuth2\Messages\AccessTokenRequestBase.cs" />
+ <Compile Include="OAuth2\Messages\AccessTokenClientCredentialsRequest.cs" />
+ <Compile Include="OAuth2\Messages\AuthenticatedClientRequestBase.cs" />
+ <Compile Include="OAuth2\Messages\EndUserAuthorizationSuccessAccessTokenResponse.cs" />
+ <Compile Include="OAuth2\Messages\EndUserAuthorizationFailedResponse.cs" />
+ <Compile Include="OAuth2\Messages\EndUserAuthorizationSuccessAuthCodeResponse.cs" />
+ <Compile Include="OAuth2\Messages\GrantType.cs" />
+ <Compile Include="OAuth2\Messages\AccessTokenRefreshRequest.cs" />
+ <Compile Include="OAuth2\Messages\EndUserAuthorizationResponseType.cs" />
+ <Compile Include="OAuth2\Messages\IAccessTokenRequest.cs" />
+ <Compile Include="OAuth2\Messages\IMessageWithClientState.cs" />
+ <Compile Include="OAuth2\Messages\ScopedAccessTokenRequest.cs" />
+ <Compile Include="OAuth2\Messages\UnauthorizedResponse.cs" />
+ <Compile Include="OAuth2\Messages\AccessTokenFailedResponse.cs" />
+ <Compile Include="OAuth2\Messages\AccessTokenSuccessResponse.cs" />
+ <Compile Include="OAuth2\Messages\EndUserAuthorizationSuccessResponseBase.cs" />
+ <Compile Include="OAuth2\ResourceServer.cs" />
+ <Compile Include="OAuth2\StandardAccessTokenAnalyzer.cs" />
+ <Compile Include="OAuth2\UserAgentClient.cs" />
+ <Compile Include="OAuth2\AuthorizationServer.cs" />
+ <Compile Include="OAuth2\OAuthUtilities.cs" />
<Compile Include="OAuth\ChannelElements\ICombinedOpenIdProviderTokenManager.cs" />
<Compile Include="OAuth\ChannelElements\IConsumerDescription.cs" />
<Compile Include="OAuth\ChannelElements\IConsumerTokenManager.cs" />
@@ -438,8 +502,13 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="OAuth\ChannelElements\OAuthServiceProviderMessageFactory.cs" />
<Compile Include="Messaging\ProtocolException.cs" />
<Compile Include="OpenId\Association.cs" />
- <Compile Include="OpenId\AssociationMemoryStore.cs" />
- <Compile Include="OpenId\Associations.cs" />
+ <Compile Include="OpenId\Provider\AssociationDataBag.cs" />
+ <Compile Include="OpenId\Provider\IProviderAssociationStore.cs" />
+ <Compile Include="OpenId\Provider\ProviderAssociationHandleEncoder.cs" />
+ <Compile Include="OpenId\Provider\ProviderAssociationKeyStorage.cs" />
+ <Compile Include="OpenId\RelyingParty\CryptoKeyStoreAsRelyingPartyAssociationStore.cs" />
+ <Compile Include="OpenId\RelyingParty\IRelyingPartyAssociationStore.cs" />
+ <Compile Include="OpenId\RelyingParty\Associations.cs" />
<Compile Include="OpenId\Behaviors\AXFetchAsSregTransform.cs" />
<Compile Include="OpenId\Behaviors\BehaviorStrings.Designer.cs">
<AutoGen>True</AutoGen>
@@ -488,7 +557,7 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\PapeUtilities.cs" />
<Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\PolicyRequest.cs" />
<Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\PolicyResponse.cs" />
- <Compile Include="OpenId\Extensions\ProviderAuthenticationPolicy\TimespanSecondsEncoder.cs" />
+ <Compile Include="Messaging\TimespanSecondsEncoder.cs" />
<Compile Include="OpenId\Extensions\SimpleRegistration\ClaimsRequest.cs" />
<Compile Include="OpenId\Extensions\SimpleRegistration\ClaimsResponse.cs" />
<Compile Include="OpenId\Extensions\SimpleRegistration\Constants.cs" />
@@ -519,6 +588,7 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="OpenId\Messages\SignedResponseRequest.cs" />
<Compile Include="OpenId\NoDiscoveryIdentifier.cs" />
<Compile Include="OpenId\OpenIdUtilities.cs" />
+ <Compile Include="OpenId\Provider\AssociationRelyingPartyType.cs" />
<Compile Include="OpenId\Provider\PrivatePersonalIdentifierProviderBase.cs" />
<Compile Include="OpenId\Provider\AnonymousRequest.cs" />
<Compile Include="OpenId\Provider\AnonymousRequestEventArgs.cs" />
@@ -531,7 +601,6 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="OpenId\Provider\IDirectedIdentityIdentifierProvider.cs" />
<Compile Include="OpenId\Provider\IHostProcessedRequest.cs" />
<Compile Include="OpenId\Provider\IErrorReporting.cs" />
- <Compile Include="OpenId\Provider\IProviderApplicationStore.cs" />
<Compile Include="OpenId\Provider\IProviderBehavior.cs" />
<Compile Include="OpenId\Provider\IRequest.cs" />
<Compile Include="OpenId\Provider\ProviderEndpoint.cs" />
@@ -553,7 +622,6 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="OpenId\DiffieHellman\mono\PrimeGeneratorBase.cs" />
<Compile Include="OpenId\DiffieHellman\mono\SequentialSearchPrimeGeneratorBase.cs" />
<Compile Include="OpenId\HmacShaAssociation.cs" />
- <Compile Include="OpenId\IAssociationStore.cs" />
<Compile Include="OpenId\Messages\AssociateUnencryptedRequest.cs" />
<Compile Include="OpenId\Provider\OpenIdProvider.cs" />
<Compile Include="OpenId\Messages\AssociateDiffieHellmanRequest.cs" />
@@ -593,9 +661,8 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="OpenId\Protocol.cs" />
<Compile Include="OpenId\ProviderEndpointDescription.cs" />
<Compile Include="OpenId\Provider\ProviderSecuritySettings.cs" />
- <Compile Include="OpenId\RelyingParty\IRelyingPartyApplicationStore.cs" />
+ <Compile Include="OpenId\IOpenIdApplicationStore.cs" />
<Compile Include="OpenId\RelyingParty\PositiveAuthenticationResponseSnapshot.cs" />
- <Compile Include="OpenId\RelyingParty\PrivateSecretManager.cs" />
<Compile Include="OpenId\RelyingParty\RelyingPartySecuritySettings.cs" />
<Compile Include="OpenId\IdentifierDiscoveryResult.cs" />
<Compile Include="OpenId\OpenIdXrdsHelper.cs" />
@@ -615,6 +682,18 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="Messaging\StandardWebRequestHandler.cs" />
<Compile Include="Messaging\MessageReceivingEndpoint.cs" />
<Compile Include="Reporting.cs" />
+ <Compile Include="OAuth2\ChannelElements\OAuth2AuthorizationServerChannel.cs" />
+ <Compile Include="OAuth2\ClientBase.cs" />
+ <Compile Include="OAuth2\Messages\MessageBase.cs" />
+ <Compile Include="OAuth2\Messages\EndUserAuthorizationRequest.cs" />
+ <Compile Include="OAuth2\Protocol.cs" />
+ <Compile Include="OAuth2\OAuthStrings.Designer.cs">
+ <AutoGen>True</AutoGen>
+ <DesignTime>True</DesignTime>
+ <DependentUpon>OAuthStrings.resx</DependentUpon>
+ </Compile>
+ <Compile Include="OAuth2\AuthorizationServerDescription.cs" />
+ <Compile Include="OAuth2\WebServerClient.cs" />
<Compile Include="Util.cs" />
<Compile Include="OAuth\Protocol.cs" />
<Compile Include="OAuth\ServiceProvider.cs" />
@@ -641,32 +720,33 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="Yadis\Yadis.cs" />
</ItemGroup>
<ItemGroup Condition=" '$(NoUIControls)' != 'true' ">
- <Compile Include="OpenId\RelyingParty\OpenIdTextBox.cs"/>
- <Compile Include="OpenId\RelyingParty\OpenIdLogin.cs"/>
- <Compile Include="OpenId\RelyingParty\OpenIdAjaxRelyingParty.cs"/>
- <Compile Include="OpenId\RelyingParty\SelectorButtonContract.cs"/>
- <Compile Include="OpenId\RelyingParty\SelectorProviderButton.cs"/>
- <Compile Include="OpenId\RelyingParty\SelectorOpenIdButton.cs"/>
- <Compile Include="XrdsPublisher.cs"/>
- <Compile Include="InfoCard\ReceivingTokenEventArgs.cs"/>
- <Compile Include="InfoCard\TokenProcessingErrorEventArgs.cs"/>
- <Compile Include="InfoCard\InfoCardSelector.cs"/>
- <Compile Include="InfoCard\ReceivedTokenEventArgs.cs"/>
- <Compile Include="Mvc\OpenIdHelper.cs"/>
- <Compile Include="OpenId\RelyingParty\SelectorButton.cs"/>
- <Compile Include="OpenId\Provider\IdentityEndpoint.cs"/>
- <Compile Include="OpenId\Provider\IdentityEndpointNormalizationEventArgs.cs"/>
- <Compile Include="OpenId\RelyingParty\SelectorInfoCardButton.cs"/>
- <Compile Include="OpenId\RelyingParty\OpenIdMobileTextBox.cs" Condition=" '$(ClrVersion)' != '4' "/>
- <Compile Include="OpenId\RelyingParty\OpenIdAjaxTextBox.cs"/>
- <Compile Include="OpenId\RelyingParty\OpenIdSelector.cs"/>
- <Compile Include="OpenId\RelyingParty\OpenIdRelyingPartyAjaxControlBase.cs"/>
- <Compile Include="OpenId\RelyingParty\OpenIdButton.cs"/>
- <Compile Include="OpenId\RelyingParty\OpenIdRelyingPartyControlBase.cs"/>
+ <Compile Include="OpenId\RelyingParty\OpenIdTextBox.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdLogin.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdAjaxRelyingParty.cs" />
+ <Compile Include="OpenId\RelyingParty\SelectorButtonContract.cs" />
+ <Compile Include="OpenId\RelyingParty\SelectorProviderButton.cs" />
+ <Compile Include="OpenId\RelyingParty\SelectorOpenIdButton.cs" />
+ <Compile Include="XrdsPublisher.cs" />
+ <Compile Include="InfoCard\ReceivingTokenEventArgs.cs" />
+ <Compile Include="InfoCard\TokenProcessingErrorEventArgs.cs" />
+ <Compile Include="InfoCard\InfoCardSelector.cs" />
+ <Compile Include="InfoCard\ReceivedTokenEventArgs.cs" />
+ <Compile Include="Mvc\OpenIdHelper.cs" />
+ <Compile Include="OpenId\RelyingParty\SelectorButton.cs" />
+ <Compile Include="OpenId\Provider\IdentityEndpoint.cs" />
+ <Compile Include="OpenId\Provider\IdentityEndpointNormalizationEventArgs.cs" />
+ <Compile Include="OpenId\RelyingParty\SelectorInfoCardButton.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdMobileTextBox.cs" Condition=" '$(ClrVersion)' != '4' " />
+ <Compile Include="OpenId\RelyingParty\OpenIdAjaxTextBox.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdSelector.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdRelyingPartyAjaxControlBase.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdButton.cs" />
+ <Compile Include="OpenId\RelyingParty\OpenIdRelyingPartyControlBase.cs" />
</ItemGroup>
<ItemGroup>
<None Include="Configuration\DotNetOpenAuth.xsd" />
<None Include="Migrated rules for DotNetOpenAuth.ruleset" />
+ <None Include="OAuth2\Messages\OAuth 2 Messages.cd" />
<None Include="OAuth\ClassDiagram.cd" />
<None Include="OAuth\Messages\OAuth Messages.cd" />
<None Include="Messaging\Bindings\Bindings.cd" />
@@ -679,6 +759,7 @@ http://opensource.org/licenses/ms-pl.html
<EmbeddedResource Include="Messaging\MessagingStrings.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>MessagingStrings.Designer.cs</LastGenOutput>
+ <SubType>Designer</SubType>
</EmbeddedResource>
<EmbeddedResource Include="OAuth\OAuthStrings.resx">
<Generator>ResXFileCodeGenerator</Generator>
@@ -750,6 +831,10 @@ http://opensource.org/licenses/ms-pl.html
<EmbeddedResource Include="OpenId\RelyingParty\OpenIdRelyingPartyAjaxControlBase.js">
<Copyright>$(StandardCopyright)</Copyright>
</EmbeddedResource>
+ <EmbeddedResource Include="OAuth2\OAuthStrings.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>OAuthStrings.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
<EmbeddedResource Include="Strings.sr.resx" />
<EmbeddedResource Include="Xrds\XrdsStrings.sr.resx" />
</ItemGroup>
@@ -778,6 +863,7 @@ http://opensource.org/licenses/ms-pl.html
<ProductName>Windows Installer 3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
+ <CodeAnalysisDictionary Include="CodeAnalysisDictionary.xml" />
<Content Include="DotNetOpenAuth.ico" />
</ItemGroup>
<ItemGroup>
@@ -794,16 +880,9 @@ http://opensource.org/licenses/ms-pl.html
<ILMergeTargetPlatformDirectory Condition=" '$(ClrVersion)' == '4' ">"$(MSBuildProgramFiles32)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0"</ILMergeTargetPlatformDirectory>
</PropertyGroup>
<MakeDir Directories="$(ILMergeOutputAssemblyDirectory)" />
- <ILMerge ExcludeFile="$(ProjectRoot)ILMergeInternalizeExceptions.txt"
- InputAssemblies="@(ILMergeInputAssemblies)"
- OutputFile="$(ILMergeOutputAssembly)"
- KeyFile="$(PublicKeyFile)"
- DelaySign="true"
- ToolPath="$(ProjectRoot)tools\ILMerge"
- TargetPlatformVersion="$(ClrVersion).0"
- TargetPlatformDirectory="$(ILMergeTargetPlatformDirectory)" />
+ <ILMerge ExcludeFile="$(ProjectRoot)ILMergeInternalizeExceptions.txt" InputAssemblies="@(ILMergeInputAssemblies)" OutputFile="$(ILMergeOutputAssembly)" KeyFile="$(PublicKeyFile)" DelaySign="true" ToolPath="$(ProjectRoot)tools\ILMerge" TargetPlatformVersion="$(ClrVersion).0" TargetPlatformDirectory="$(ILMergeTargetPlatformDirectory)" />
</Target>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))\EnlistmentInfo.targets" Condition=" '$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), EnlistmentInfo.targets))' != '' " />
-</Project>
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/GlobalSuppressions.cs b/src/DotNetOpenAuth/GlobalSuppressions.cs
index 8539422..2bc6c04 100644
--- a/src/DotNetOpenAuth/GlobalSuppressions.cs
+++ b/src/DotNetOpenAuth/GlobalSuppressions.cs
@@ -67,3 +67,4 @@ using System.Diagnostics.CodeAnalysis;
[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "iframe", Scope = "resource", Target = "DotNetOpenAuth.OpenId.OpenIdStrings.resources")]
[assembly: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "Sig", Scope = "resource", Target = "DotNetOpenAuth.OpenId.OpenIdStrings.resources")]
[assembly: SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", MessageId = "DSig", Scope = "resource", Target = "DotNetOpenAuth.OpenId.OpenIdStrings.resources")]
+[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "DotNetOpenAuth.OAuth2.ChannelElements")]
diff --git a/src/DotNetOpenAuth/Messaging/BinaryDataBagFormatter.cs b/src/DotNetOpenAuth/Messaging/BinaryDataBagFormatter.cs
new file mode 100644
index 0000000..591adc3
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/BinaryDataBagFormatter.cs
@@ -0,0 +1,80 @@
+//-----------------------------------------------------------------------
+// <copyright file="BinaryDataBagFormatter.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.IO;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// A compact binary <see cref="DataBag"/> serialization class.
+ /// </summary>
+ /// <typeparam name="T">The <see cref="DataBag"/>-derived type to serialize/deserialize.</typeparam>
+ internal class BinaryDataBagFormatter<T> : DataBagFormatterBase<T> where T : DataBag, IStreamSerializingDataBag, new() {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BinaryDataBagFormatter&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="signingKey">The crypto service provider with the asymmetric key to use for signing or verifying the token.</param>
+ /// <param name="encryptingKey">The crypto service provider with the asymmetric key to use for encrypting or decrypting the token.</param>
+ /// <param name="compressed">A value indicating whether the data in this instance will be GZip'd.</param>
+ /// <param name="maximumAge">The maximum age of a token that can be decoded; useful only when <paramref name="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ protected internal BinaryDataBagFormatter(RSACryptoServiceProvider signingKey = null, RSACryptoServiceProvider encryptingKey = null, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : base(signingKey, encryptingKey, compressed, maximumAge, decodeOnceOnly) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="BinaryDataBagFormatter&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store used when signing or encrypting.</param>
+ /// <param name="bucket">The bucket in which symmetric keys are stored for signing/encrypting data.</param>
+ /// <param name="signed">A value indicating whether the data in this instance will be protected against tampering.</param>
+ /// <param name="encrypted">A value indicating whether the data in this instance will be protected against eavesdropping.</param>
+ /// <param name="compressed">A value indicating whether the data in this instance will be GZip'd.</param>
+ /// <param name="minimumAge">The minimum age.</param>
+ /// <param name="maximumAge">The maximum age of a token that can be decoded; useful only when <paramref name="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ protected internal BinaryDataBagFormatter(ICryptoKeyStore cryptoKeyStore = null, string bucket = null, bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? minimumAge = null, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : base(cryptoKeyStore, bucket, signed, encrypted, compressed, minimumAge, maximumAge, decodeOnceOnly) {
+ Contract.Requires<ArgumentException>((cryptoKeyStore != null && bucket != null) || (!signed && !encrypted));
+ }
+
+ /// <summary>
+ /// Serializes the <see cref="DataBag"/> instance to a buffer.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <returns>The buffer containing the serialized data.</returns>
+ protected override byte[] SerializeCore(T message) {
+ using (var stream = new MemoryStream()) {
+ message.Serialize(stream);
+ return stream.ToArray();
+ }
+ }
+
+ /// <summary>
+ /// Deserializes the <see cref="DataBag"/> instance from a buffer.
+ /// </summary>
+ /// <param name="message">The message instance to initialize with data from the buffer.</param>
+ /// <param name="data">The data buffer.</param>
+ protected override void DeserializeCore(T message, byte[] data) {
+ using (var stream = new MemoryStream(data)) {
+ message.Deserialize(stream);
+ }
+
+ // Perform basic validation on message that the MessageSerializer would have normally performed.
+ var messageDescription = MessageDescriptions.Get(message);
+ var dictionary = messageDescription.GetDictionary(message);
+ messageDescription.EnsureMessagePartsPassBasicValidation(dictionary);
+ IMessage m = message;
+ m.EnsureValidMessage();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/AsymmetricCryptoKeyStoreWrapper.cs b/src/DotNetOpenAuth/Messaging/Bindings/AsymmetricCryptoKeyStoreWrapper.cs
new file mode 100644
index 0000000..0f2ac05
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/Bindings/AsymmetricCryptoKeyStoreWrapper.cs
@@ -0,0 +1,163 @@
+//-----------------------------------------------------------------------
+// <copyright file="AsymmetricCryptoKeyStoreWrapper.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging.Bindings {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// Provides RSA encryption of symmetric keys to protect them from a theft of
+ /// the persistent store.
+ /// </summary>
+ public class AsymmetricCryptoKeyStoreWrapper : ICryptoKeyStore {
+ /// <summary>
+ /// The persistent store for asymmetrically encrypted symmetric keys.
+ /// </summary>
+ private readonly ICryptoKeyStore dataStore;
+
+ /// <summary>
+ /// The memory cache of decrypted keys.
+ /// </summary>
+ private readonly MemoryCryptoKeyStore cache = new MemoryCryptoKeyStore();
+
+ /// <summary>
+ /// The asymmetric algorithm to use encrypting/decrypting the symmetric keys.
+ /// </summary>
+ private readonly RSACryptoServiceProvider asymmetricCrypto;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AsymmetricCryptoKeyStoreWrapper"/> class.
+ /// </summary>
+ /// <param name="dataStore">The data store.</param>
+ /// <param name="asymmetricCrypto">The asymmetric protection to apply to symmetric keys. Must include the private key.</param>
+ public AsymmetricCryptoKeyStoreWrapper(ICryptoKeyStore dataStore, RSACryptoServiceProvider asymmetricCrypto) {
+ Contract.Requires<ArgumentNullException>(dataStore != null);
+ Contract.Requires<ArgumentNullException>(asymmetricCrypto != null);
+ Contract.Requires<ArgumentException>(!asymmetricCrypto.PublicOnly);
+ this.dataStore = dataStore;
+ this.asymmetricCrypto = asymmetricCrypto;
+ }
+
+ /// <summary>
+ /// Gets the key in a given bucket and handle.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ /// <returns>
+ /// The cryptographic key, or <c>null</c> if no matching key was found.
+ /// </returns>
+ public CryptoKey GetKey(string bucket, string handle) {
+ var key = this.dataStore.GetKey(bucket, handle);
+ return this.Decrypt(bucket, handle, key);
+ }
+
+ /// <summary>
+ /// Gets a sequence of existing keys within a given bucket.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <returns>
+ /// A sequence of handles and keys, ordered by descending <see cref="CryptoKey.ExpiresUtc"/>.
+ /// </returns>
+ public IEnumerable<KeyValuePair<string, CryptoKey>> GetKeys(string bucket) {
+ return this.dataStore.GetKeys(bucket)
+ .Select(pair => new KeyValuePair<string, CryptoKey>(pair.Key, this.Decrypt(bucket, pair.Key, pair.Value)));
+ }
+
+ /// <summary>
+ /// Stores a cryptographic key.
+ /// </summary>
+ /// <param name="bucket">The name of the bucket to store the key in. Case sensitive.</param>
+ /// <param name="handle">The handle to the key, unique within the bucket. Case sensitive.</param>
+ /// <param name="decryptedCryptoKey">The key to store.</param>
+ [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "2#", Justification = "Helps readability because multiple keys are involved.")]
+ public void StoreKey(string bucket, string handle, CryptoKey decryptedCryptoKey) {
+ byte[] encryptedKey = this.asymmetricCrypto.Encrypt(decryptedCryptoKey.Key, true);
+ var encryptedCryptoKey = new CryptoKey(encryptedKey, decryptedCryptoKey.ExpiresUtc);
+ this.dataStore.StoreKey(bucket, handle, encryptedCryptoKey);
+
+ this.cache.StoreKey(bucket, handle, new CachedCryptoKey(encryptedCryptoKey, decryptedCryptoKey));
+ }
+
+ /// <summary>
+ /// Removes the key.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ public void RemoveKey(string bucket, string handle) {
+ this.dataStore.RemoveKey(bucket, handle);
+ this.cache.RemoveKey(bucket, handle);
+ }
+
+ /// <summary>
+ /// Decrypts the specified key.
+ /// </summary>
+ /// <param name="bucket">The bucket.</param>
+ /// <param name="handle">The handle.</param>
+ /// <param name="encryptedCryptoKey">The encrypted key.</param>
+ /// <returns>
+ /// The decrypted key.
+ /// </returns>
+ [SuppressMessage("Microsoft.Naming", "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "2#", Justification = "Helps readability because multiple keys are involved.")]
+ private CryptoKey Decrypt(string bucket, string handle, CryptoKey encryptedCryptoKey) {
+ if (encryptedCryptoKey == null) {
+ return null;
+ }
+
+ // Avoid the asymmetric decryption if possible by looking up whether we have that in our cache.
+ CachedCryptoKey cached = (CachedCryptoKey)this.cache.GetKey(bucket, handle);
+ if (cached != null && MessagingUtilities.AreEquivalent(cached.EncryptedKey, encryptedCryptoKey.Key)) {
+ return cached;
+ }
+
+ byte[] decryptedKey = this.asymmetricCrypto.Decrypt(encryptedCryptoKey.Key, true);
+ var decryptedCryptoKey = new CryptoKey(decryptedKey, encryptedCryptoKey.ExpiresUtc);
+
+ // Store the decrypted version in the cache to save time next time.
+ this.cache.StoreKey(bucket, handle, new CachedCryptoKey(encryptedCryptoKey, decryptedCryptoKey));
+
+ return decryptedCryptoKey;
+ }
+
+ /// <summary>
+ /// An encrypted key and its decrypted equivalent.
+ /// </summary>
+ private class CachedCryptoKey : CryptoKey {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CachedCryptoKey"/> class.
+ /// </summary>
+ /// <param name="encrypted">The encrypted key.</param>
+ /// <param name="decrypted">The decrypted key.</param>
+ internal CachedCryptoKey(CryptoKey encrypted, CryptoKey decrypted)
+ : base(decrypted.Key, decrypted.ExpiresUtc) {
+ Contract.Requires(encrypted != null);
+ Contract.Requires(decrypted != null);
+ Contract.Requires(encrypted.ExpiresUtc == decrypted.ExpiresUtc);
+
+ this.EncryptedKey = encrypted.Key;
+ }
+
+ /// <summary>
+ /// Gets the encrypted key.
+ /// </summary>
+ internal byte[] EncryptedKey { get; private set; }
+
+ /// <summary>
+ /// Invariant conditions.
+ /// </summary>
+ [ContractInvariantMethod]
+ [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")]
+ private void ObjectInvariant() {
+ Contract.Invariant(this.EncryptedKey != null);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/CryptoKey.cs b/src/DotNetOpenAuth/Messaging/Bindings/CryptoKey.cs
new file mode 100644
index 0000000..cd10199
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/Bindings/CryptoKey.cs
@@ -0,0 +1,93 @@
+//-----------------------------------------------------------------------
+// <copyright file="CryptoKey.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging.Bindings {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A cryptographic key and metadata concerning it.
+ /// </summary>
+ public class CryptoKey {
+ /// <summary>
+ /// Backing field for the <see cref="Key"/> property.
+ /// </summary>
+ private readonly byte[] key;
+
+ /// <summary>
+ /// Backing field for the <see cref="ExpiresUtc"/> property.
+ /// </summary>
+ private readonly DateTime expiresUtc;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CryptoKey"/> class.
+ /// </summary>
+ /// <param name="key">The cryptographic key.</param>
+ /// <param name="expiresUtc">The expires UTC.</param>
+ public CryptoKey(byte[] key, DateTime expiresUtc) {
+ Contract.Requires<ArgumentNullException>(key != null);
+ Contract.Requires<ArgumentException>(expiresUtc.Kind == DateTimeKind.Utc);
+ this.key = key;
+ this.expiresUtc = expiresUtc;
+ }
+
+ /// <summary>
+ /// Gets the key.
+ /// </summary>
+ [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It's a buffer")]
+ public byte[] Key {
+ get {
+ Contract.Ensures(Contract.Result<byte[]>() != null);
+ return this.key;
+ }
+ }
+
+ /// <summary>
+ /// Gets the expiration date of this key (UTC time).
+ /// </summary>
+ public DateTime ExpiresUtc {
+ get {
+ Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc);
+ return this.expiresUtc;
+ }
+ }
+
+ /// <summary>
+ /// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
+ /// </summary>
+ /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
+ /// <returns>
+ /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
+ /// </returns>
+ /// <exception cref="T:System.NullReferenceException">
+ /// The <paramref name="obj"/> parameter is null.
+ /// </exception>
+ public override bool Equals(object obj) {
+ var other = obj as CryptoKey;
+ if (other == null) {
+ return false;
+ }
+
+ return this.ExpiresUtc == other.ExpiresUtc
+ && MessagingUtilities.AreEquivalent(this.Key, other.Key);
+ }
+
+ /// <summary>
+ /// Returns a hash code for this instance.
+ /// </summary>
+ /// <returns>
+ /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
+ /// </returns>
+ public override int GetHashCode() {
+ return this.ExpiresUtc.GetHashCode();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/CryptoKeyCollisionException.cs b/src/DotNetOpenAuth/Messaging/Bindings/CryptoKeyCollisionException.cs
new file mode 100644
index 0000000..11634ac
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/Bindings/CryptoKeyCollisionException.cs
@@ -0,0 +1,68 @@
+//-----------------------------------------------------------------------
+// <copyright file="CryptoKeyCollisionException.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging.Bindings {
+ using System;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Security.Permissions;
+
+ /// <summary>
+ /// Thrown by a hosting application or web site when a cryptographic key is created with a
+ /// bucket and handle that conflicts with a previously stored and unexpired key.
+ /// </summary>
+ [SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "Specialized exception has no need of a message parameter.")]
+ [Serializable]
+ public class CryptoKeyCollisionException : ArgumentException {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CryptoKeyCollisionException"/> class.
+ /// </summary>
+ public CryptoKeyCollisionException() {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CryptoKeyCollisionException"/> class.
+ /// </summary>
+ /// <param name="inner">The inner exception to include.</param>
+ public CryptoKeyCollisionException(Exception inner) : base(null, inner) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CryptoKeyCollisionException"/> class.
+ /// </summary>
+ /// <param name="info">The <see cref="System.Runtime.Serialization.SerializationInfo"/>
+ /// that holds the serialized object data about the exception being thrown.</param>
+ /// <param name="context">The System.Runtime.Serialization.StreamingContext
+ /// that contains contextual information about the source or destination.</param>
+ protected CryptoKeyCollisionException(
+ System.Runtime.Serialization.SerializationInfo info,
+ System.Runtime.Serialization.StreamingContext context)
+ : base(info, context) {
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// When overridden in a derived class, sets the <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with information about the exception.
+ /// </summary>
+ /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
+ /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
+ /// <exception cref="T:System.ArgumentNullException">
+ /// The <paramref name="info"/> parameter is a null reference (Nothing in Visual Basic).
+ /// </exception>
+ /// <PermissionSet>
+ /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Read="*AllFiles*" PathDiscovery="*AllFiles*"/>
+ /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="SerializationFormatter"/>
+ /// </PermissionSet>
+#if CLR4
+ [SecurityCritical]
+#else
+ [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
+#endif
+ public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) {
+ base.GetObjectData(info, context);
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs b/src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs
index 73ce289..cfe7f6c 100644
--- a/src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs
+++ b/src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs
@@ -22,6 +22,7 @@ namespace DotNetOpenAuth.Messaging.Bindings {
public ExpiredMessageException(DateTime utcExpirationDate, IProtocolMessage faultedMessage)
: base(string.Format(CultureInfo.CurrentCulture, MessagingStrings.ExpiredMessage, utcExpirationDate.ToLocalTime(), DateTime.Now), faultedMessage) {
Contract.Requires<ArgumentException>(utcExpirationDate.Kind == DateTimeKind.Utc);
+ Contract.Requires<ArgumentNullException>(faultedMessage != null);
}
/// <summary>
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/ICryptoKeyStore.cs b/src/DotNetOpenAuth/Messaging/Bindings/ICryptoKeyStore.cs
new file mode 100644
index 0000000..815c488
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/Bindings/ICryptoKeyStore.cs
@@ -0,0 +1,118 @@
+//-----------------------------------------------------------------------
+// <copyright file="ICryptoKeyStore.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging.Bindings {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A persistent store for rotating symmetric cryptographic keys.
+ /// </summary>
+ /// <remarks>
+ /// Implementations should persist it in such a way that the keys are shared across all servers
+ /// on a web farm, where applicable.
+ /// The store should consider protecting the persistent store against theft resulting in the loss
+ /// of the confidentiality of the keys. One possible mitigation is to asymmetrically encrypt
+ /// each key using a certificate installed in the server's certificate store.
+ /// </remarks>
+ [ContractClass(typeof(ICryptoKeyStoreContract))]
+ public interface ICryptoKeyStore {
+ /// <summary>
+ /// Gets the key in a given bucket and handle.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ /// <returns>The cryptographic key, or <c>null</c> if no matching key was found.</returns>
+ CryptoKey GetKey(string bucket, string handle);
+
+ /// <summary>
+ /// Gets a sequence of existing keys within a given bucket.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <returns>A sequence of handles and keys, ordered by descending <see cref="CryptoKey.ExpiresUtc"/>.</returns>
+ [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Important for scalability")]
+ IEnumerable<KeyValuePair<string, CryptoKey>> GetKeys(string bucket);
+
+ /// <summary>
+ /// Stores a cryptographic key.
+ /// </summary>
+ /// <param name="bucket">The name of the bucket to store the key in. Case sensitive.</param>
+ /// <param name="handle">The handle to the key, unique within the bucket. Case sensitive.</param>
+ /// <param name="key">The key to store.</param>
+ /// <exception cref="CryptoKeyCollisionException">Thrown in the event of a conflict with an existing key in the same bucket and with the same handle.</exception>
+ void StoreKey(string bucket, string handle, CryptoKey key);
+
+ /// <summary>
+ /// Removes the key.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ void RemoveKey(string bucket, string handle);
+ }
+
+ /// <summary>
+ /// Code contract for the <see cref="ICryptoKeyStore"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(ICryptoKeyStore))]
+ internal abstract class ICryptoKeyStoreContract : ICryptoKeyStore {
+ /// <summary>
+ /// Gets the key in a given bucket and handle.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ /// <returns>
+ /// The cryptographic key, or <c>null</c> if no matching key was found.
+ /// </returns>
+ CryptoKey ICryptoKeyStore.GetKey(string bucket, string handle) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(bucket));
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(handle));
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Gets a sequence of existing keys within a given bucket.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <returns>
+ /// A sequence of handles and keys, ordered by descending <see cref="CryptoKey.ExpiresUtc"/>.
+ /// </returns>
+ IEnumerable<KeyValuePair<string, CryptoKey>> ICryptoKeyStore.GetKeys(string bucket) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(bucket));
+ Contract.Ensures(Contract.Result<IEnumerable<KeyValuePair<string, CryptoKey>>>() != null);
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Stores a cryptographic key.
+ /// </summary>
+ /// <param name="bucket">The name of the bucket to store the key in. Case sensitive.</param>
+ /// <param name="handle">The handle to the key, unique within the bucket. Case sensitive.</param>
+ /// <param name="key">The key to store.</param>
+ /// <exception cref="CryptoKeyCollisionException">Thrown in the event of a conflict with an existing key in the same bucket and with the same handle.</exception>
+ void ICryptoKeyStore.StoreKey(string bucket, string handle, CryptoKey key) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(bucket));
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(handle));
+ Contract.Requires<ArgumentNullException>(key != null);
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Removes the key.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ void ICryptoKeyStore.RemoveKey(string bucket, string handle) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(bucket));
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(handle));
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/MemoryCryptoKeyStore.cs b/src/DotNetOpenAuth/Messaging/Bindings/MemoryCryptoKeyStore.cs
new file mode 100644
index 0000000..63d1953
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/Bindings/MemoryCryptoKeyStore.cs
@@ -0,0 +1,156 @@
+//-----------------------------------------------------------------------
+// <copyright file="MemoryCryptoKeyStore.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging.Bindings {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+
+ /// <summary>
+ /// A in-memory store of crypto keys.
+ /// </summary>
+ internal class MemoryCryptoKeyStore : ICryptoKeyStore {
+ /// <summary>
+ /// How frequently to check for and remove expired secrets.
+ /// </summary>
+ private static readonly TimeSpan cleaningInterval = TimeSpan.FromMinutes(30);
+
+ /// <summary>
+ /// An in-memory cache of decrypted symmetric keys.
+ /// </summary>
+ /// <remarks>
+ /// The key is the bucket name. The value is a dictionary whose key is the handle and whose value is the cached key.
+ /// </remarks>
+ private readonly Dictionary<string, Dictionary<string, CryptoKey>> store = new Dictionary<string, Dictionary<string, CryptoKey>>(StringComparer.Ordinal);
+
+ /// <summary>
+ /// The last time the cache had expired keys removed from it.
+ /// </summary>
+ private DateTime lastCleaning = DateTime.UtcNow;
+
+ /// <summary>
+ /// Gets the key in a given bucket and handle.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ /// <returns>
+ /// The cryptographic key, or <c>null</c> if no matching key was found.
+ /// </returns>
+ public CryptoKey GetKey(string bucket, string handle) {
+ lock (this.store) {
+ Dictionary<string, CryptoKey> cacheBucket;
+ if (this.store.TryGetValue(bucket, out cacheBucket)) {
+ CryptoKey key;
+ if (cacheBucket.TryGetValue(handle, out key)) {
+ return key;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Gets a sequence of existing keys within a given bucket.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <returns>
+ /// A sequence of handles and keys, ordered by descending <see cref="CryptoKey.ExpiresUtc"/>.
+ /// </returns>
+ public IEnumerable<KeyValuePair<string, CryptoKey>> GetKeys(string bucket) {
+ lock (this.store) {
+ Dictionary<string, CryptoKey> cacheBucket;
+ if (this.store.TryGetValue(bucket, out cacheBucket)) {
+ return cacheBucket.ToList();
+ } else {
+ return Enumerable.Empty<KeyValuePair<string, CryptoKey>>();
+ }
+ }
+ }
+
+ /// <summary>
+ /// Stores a cryptographic key.
+ /// </summary>
+ /// <param name="bucket">The name of the bucket to store the key in. Case sensitive.</param>
+ /// <param name="handle">The handle to the key, unique within the bucket. Case sensitive.</param>
+ /// <param name="key">The key to store.</param>
+ /// <exception cref="CryptoKeyCollisionException">Thrown in the event of a conflict with an existing key in the same bucket and with the same handle.</exception>
+ public void StoreKey(string bucket, string handle, CryptoKey key) {
+ lock (this.store) {
+ Dictionary<string, CryptoKey> cacheBucket;
+ if (!this.store.TryGetValue(bucket, out cacheBucket)) {
+ this.store[bucket] = cacheBucket = new Dictionary<string, CryptoKey>(StringComparer.Ordinal);
+ }
+
+ if (cacheBucket.ContainsKey(handle)) {
+ throw new CryptoKeyCollisionException();
+ }
+
+ cacheBucket[handle] = key;
+
+ this.CleanExpiredKeysFromMemoryCacheIfAppropriate();
+ }
+ }
+
+ /// <summary>
+ /// Removes the key.
+ /// </summary>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ public void RemoveKey(string bucket, string handle) {
+ lock (this.store) {
+ Dictionary<string, CryptoKey> cacheBucket;
+ if (this.store.TryGetValue(bucket, out cacheBucket)) {
+ cacheBucket.Remove(handle);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Cleans the expired keys from memory cache if the cleaning interval has passed.
+ /// </summary>
+ private void CleanExpiredKeysFromMemoryCacheIfAppropriate() {
+ if (DateTime.UtcNow > this.lastCleaning + cleaningInterval) {
+ lock (this.store) {
+ if (DateTime.UtcNow > this.lastCleaning + cleaningInterval) {
+ this.ClearExpiredKeysFromMemoryCache();
+ }
+ }
+ }
+ }
+
+ /// <summary>
+ /// Weeds out expired keys from the in-memory cache.
+ /// </summary>
+ private void ClearExpiredKeysFromMemoryCache() {
+ lock (this.store) {
+ var emptyBuckets = new List<string>();
+ foreach (var bucketPair in this.store) {
+ var expiredKeys = new List<string>();
+ foreach (var handlePair in bucketPair.Value) {
+ if (handlePair.Value.ExpiresUtc < DateTime.UtcNow) {
+ expiredKeys.Add(handlePair.Key);
+ }
+ }
+
+ foreach (var expiredKey in expiredKeys) {
+ bucketPair.Value.Remove(expiredKey);
+ }
+
+ if (bucketPair.Value.Count == 0) {
+ emptyBuckets.Add(bucketPair.Key);
+ }
+ }
+
+ foreach (string emptyBucket in emptyBuckets) {
+ this.store.Remove(emptyBucket);
+ }
+
+ this.lastCleaning = DateTime.UtcNow;
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/Channel.cs b/src/DotNetOpenAuth/Messaging/Channel.cs
index 0abdcfa..bff395b 100644
--- a/src/DotNetOpenAuth/Messaging/Channel.cs
+++ b/src/DotNetOpenAuth/Messaging/Channel.cs
@@ -8,6 +8,7 @@ namespace DotNetOpenAuth.Messaging {
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
+ using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
@@ -17,9 +18,11 @@ namespace DotNetOpenAuth.Messaging {
using System.Net;
using System.Net.Cache;
using System.Net.Mime;
+ using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading;
using System.Web;
+ using System.Xml;
using DotNetOpenAuth.Messaging.Reflection;
/// <summary>
@@ -41,6 +44,22 @@ namespace DotNetOpenAuth.Messaging {
protected internal const string HttpFormUrlEncoded = "application/x-www-form-urlencoded";
/// <summary>
+ /// The content-type used for JSON serialized objects.
+ /// </summary>
+ protected internal const string JsonEncoded = "application/json";
+
+ /// <summary>
+ /// The "text/javascript" content-type that some servers return instead of the standard <see cref="JsonEncoded"/> one.
+ /// </summary>
+ protected internal const string JsonTextEncoded = "text/javascript";
+
+ /// <summary>
+ /// The content-type for plain text.
+ /// </summary>
+ [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "PlainText", Justification = "Not 'Plaintext' in the crypographic sense.")]
+ protected internal const string PlainTextEncoded = "text/plain";
+
+ /// <summary>
/// The content-type used on HTTP POST requests where the POST entity is a
/// URL-encoded series of key=value pairs.
/// This includes the <see cref="PostEntityEncoding"/> character encoding.
@@ -130,6 +149,13 @@ namespace DotNetOpenAuth.Messaging {
this.messageTypeProvider = messageTypeProvider;
this.WebRequestHandler = new StandardWebRequestHandler();
+ this.XmlDictionaryReaderQuotas = new XmlDictionaryReaderQuotas {
+ MaxArrayLength = 1,
+ MaxDepth = 2,
+ MaxBytesPerRead = 8 * 1024,
+ MaxStringContentLength = 16 * 1024,
+ };
+
this.outgoingBindingElements = new List<IChannelBindingElement>(ValidateAndPrepareBindingElements(bindingElements));
this.incomingBindingElements = new List<IChannelBindingElement>(this.outgoingBindingElements);
this.incomingBindingElements.Reverse();
@@ -175,7 +201,7 @@ namespace DotNetOpenAuth.Messaging {
/// <summary>
/// Gets or sets the message descriptions.
/// </summary>
- internal MessageDescriptionCollection MessageDescriptions {
+ internal virtual MessageDescriptionCollection MessageDescriptions {
get {
return this.messageDescriptions;
}
@@ -233,11 +259,12 @@ namespace DotNetOpenAuth.Messaging {
protected internal bool IsDisposed { get; set; }
/// <summary>
- /// Gets a tool that can figure out what kind of message is being received
+ /// Gets or sets a tool that can figure out what kind of message is being received
/// so it can be deserialized.
/// </summary>
- protected IMessageFactory MessageFactory {
+ protected virtual IMessageFactory MessageFactory {
get { return this.messageTypeProvider; }
+ set { this.messageTypeProvider = value; }
}
/// <summary>
@@ -256,6 +283,12 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Gets or sets the XML dictionary reader quotas.
+ /// </summary>
+ /// <value>The XML dictionary reader quotas.</value>
+ protected virtual XmlDictionaryReaderQuotas XmlDictionaryReaderQuotas { get; set; }
+
+ /// <summary>
/// Sends an indirect message (either a request or response)
/// or direct message response for transmission to a remote party
/// and ends execution on the current page or handler.
@@ -265,10 +298,26 @@ namespace DotNetOpenAuth.Messaging {
/// <remarks>
/// Requires an HttpContext.Current context.
/// </remarks>
+ [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use the Respond method instead, and prepare for execution to continue on this page beyond the call to Respond.")]
public void Send(IProtocolMessage message) {
Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired);
Contract.Requires<ArgumentNullException>(message != null);
- this.PrepareResponse(message).Send();
+ this.PrepareResponse(message).Respond(HttpContext.Current, true);
+ }
+
+ /// <summary>
+ /// Sends an indirect message (either a request or response)
+ /// or direct message response for transmission to a remote party
+ /// and skips most of the remaining ASP.NET request handling pipeline.
+ /// </summary>
+ /// <param name="message">The one-way message to send</param>
+ /// <remarks>
+ /// Requires an HttpContext.Current context.
+ /// </remarks>
+ public void Respond(IProtocolMessage message) {
+ Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired);
+ Contract.Requires<ArgumentNullException>(message != null);
+ this.PrepareResponse(message).Respond();
}
/// <summary>
@@ -694,7 +743,7 @@ namespace DotNetOpenAuth.Messaging {
try {
recipient = request.GetRecipient();
} catch (ArgumentException ex) {
- Logger.Messaging.WarnFormat("Unrecognized HTTP request: " + ex.ToString());
+ Logger.Messaging.WarnFormat("Unrecognized HTTP request: {0}", ex);
return null;
}
@@ -710,6 +759,7 @@ namespace DotNetOpenAuth.Messaging {
protected virtual IProtocolMessage Receive(Dictionary<string, string> fields, MessageReceivingEndpoint recipient) {
Contract.Requires<ArgumentNullException>(fields != null);
+ this.FilterReceivedFields(fields);
IProtocolMessage message = this.MessageFactory.GetNewRequestMessage(recipient, fields);
// If there was no data, or we couldn't recognize it as a message, abort.
@@ -736,6 +786,7 @@ namespace DotNetOpenAuth.Messaging {
protected virtual OutgoingWebResponse PrepareIndirectResponse(IDirectedProtocolMessage message) {
Contract.Requires<ArgumentNullException>(message != null);
Contract.Requires<ArgumentException>(message.Recipient != null, MessagingStrings.DirectedMessageMissingRecipient);
+ Contract.Requires<ArgumentException>((message.HttpMethods & (HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest)) != 0);
Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
Contract.Assert(message != null && message.Recipient != null);
@@ -743,10 +794,30 @@ namespace DotNetOpenAuth.Messaging {
Contract.Assert(message != null && message.Recipient != null);
var fields = messageAccessor.Serialize();
- // First try creating a 301 redirect, and fallback to a form POST
- // if the message is too big.
- OutgoingWebResponse response = this.Create301RedirectResponse(message, fields);
- if (response.Headers[HttpResponseHeader.Location].Length > this.MaximumIndirectMessageUrlLength) {
+ OutgoingWebResponse response = null;
+ bool tooLargeForGet = false;
+ if ((message.HttpMethods & HttpDeliveryMethods.GetRequest) == HttpDeliveryMethods.GetRequest) {
+ bool payloadInFragment = false;
+ var httpIndirect = message as IHttpIndirectResponse;
+ if (httpIndirect != null) {
+ payloadInFragment = httpIndirect.Include301RedirectPayloadInFragment;
+ }
+
+ // First try creating a 301 redirect, and fallback to a form POST
+ // if the message is too big.
+ response = this.Create301RedirectResponse(message, fields, payloadInFragment);
+ tooLargeForGet = response.Headers[HttpResponseHeader.Location].Length > this.MaximumIndirectMessageUrlLength;
+ }
+
+ // Make sure that if the message is too large for GET that POST is allowed.
+ if (tooLargeForGet) {
+ ErrorUtilities.VerifyProtocol(
+ (message.HttpMethods & HttpDeliveryMethods.PostRequest) == HttpDeliveryMethods.PostRequest,
+ "Message too large for a HTTP GET, and HTTP POST is not allowed for this message type.");
+ }
+
+ // If GET didn't work out, for whatever reason...
+ if (response == null || tooLargeForGet) {
response = this.CreateFormPostResponse(message, fields);
}
@@ -759,9 +830,10 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="message">The message to forward.</param>
/// <param name="fields">The pre-serialized fields from the message.</param>
+ /// <param name="payloadInFragment">if set to <c>true</c> the redirect will contain the message payload in the #fragment portion of the URL rather than the ?querystring.</param>
/// <returns>The encoded HTTP response.</returns>
[Pure]
- protected virtual OutgoingWebResponse Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields) {
+ protected virtual OutgoingWebResponse Create301RedirectResponse(IDirectedProtocolMessage message, IDictionary<string, string> fields, bool payloadInFragment = false) {
Contract.Requires<ArgumentNullException>(message != null);
Contract.Requires<ArgumentException>(message.Recipient != null, MessagingStrings.DirectedMessageMissingRecipient);
Contract.Requires<ArgumentNullException>(fields != null);
@@ -771,7 +843,12 @@ namespace DotNetOpenAuth.Messaging {
// such as WebSense.
WebHeaderCollection headers = new WebHeaderCollection();
UriBuilder builder = new UriBuilder(message.Recipient);
- MessagingUtilities.AppendQueryArgs(builder, fields);
+ if (payloadInFragment) {
+ builder.AppendFragmentArgs(fields);
+ } else {
+ builder.AppendQueryArgs(fields);
+ }
+
headers.Add(HttpResponseHeader.Location, builder.Uri.AbsoluteUri);
headers.Add(HttpResponseHeader.ContentType, "text/html; charset=utf-8");
Logger.Http.DebugFormat("Redirecting to {0}", builder.Uri.AbsoluteUri);
@@ -838,7 +915,7 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="request">The message to send.</param>
/// <returns>The <see cref="HttpWebRequest"/> prepared to send the request.</returns>
/// <remarks>
- /// This method must be overridden by a derived class, unless the <see cref="RequestCore"/> method
+ /// This method must be overridden by a derived class, unless the <see cref="Channel.RequestCore"/> method
/// is overridden and does not require this method.
/// </remarks>
protected virtual HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request) {
@@ -860,6 +937,42 @@ namespace DotNetOpenAuth.Messaging {
protected abstract OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response);
/// <summary>
+ /// Serializes the given message as a JSON string.
+ /// </summary>
+ /// <param name="message">The message to serialize.</param>
+ /// <returns>A JSON string.</returns>
+ [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "This Dispose is safe.")]
+ protected virtual string SerializeAsJson(IMessage message) {
+ Contract.Requires<ArgumentNullException>(message != null);
+
+ MessageDictionary messageDictionary = this.MessageDescriptions.GetAccessor(message);
+ using (var memoryStream = new MemoryStream()) {
+ using (var jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(memoryStream, Encoding.UTF8)) {
+ MessageSerializer.Serialize(messageDictionary, jsonWriter);
+ jsonWriter.Flush();
+ }
+
+ string json = Encoding.UTF8.GetString(memoryStream.ToArray());
+ return json;
+ }
+ }
+
+ /// <summary>
+ /// Deserializes from flat data from a JSON object.
+ /// </summary>
+ /// <param name="json">A JSON string.</param>
+ /// <returns>The simple "key":"value" pairs from a JSON-encoded object.</returns>
+ protected virtual IDictionary<string, string> DeserializeFromJson(string json) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(json));
+
+ var dictionary = new Dictionary<string, string>();
+ using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(json), this.XmlDictionaryReaderQuotas)) {
+ MessageSerializer.DeserializeJsonAsFlatDictionary(dictionary, jsonReader);
+ }
+ return dictionary;
+ }
+
+ /// <summary>
/// Prepares a message for transmit by applying signatures, nonces, etc.
/// </summary>
/// <param name="message">The message to prepare for sending.</param>
@@ -975,7 +1088,7 @@ namespace DotNetOpenAuth.Messaging {
var messageAccessor = this.MessageDescriptions.GetAccessor(requestMessage);
var fields = messageAccessor.Serialize();
- HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(requestMessage.Recipient);
+ var httpRequest = (HttpWebRequest)WebRequest.Create(requestMessage.Recipient);
httpRequest.CachePolicy = this.CachePolicy;
httpRequest.Method = "POST";
@@ -1145,6 +1258,14 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Allows preprocessing and validation of message data before an appropriate message type is
+ /// selected or deserialized.
+ /// </summary>
+ /// <param name="fields">The received message data.</param>
+ protected virtual void FilterReceivedFields(IDictionary<string, string> fields) {
+ }
+
+ /// <summary>
/// Customizes the binding element order for outgoing and incoming messages.
/// </summary>
/// <param name="outgoingOrder">The outgoing order.</param>
diff --git a/src/DotNetOpenAuth/Messaging/DataBag.cs b/src/DotNetOpenAuth/Messaging/DataBag.cs
new file mode 100644
index 0000000..17a7bda
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/DataBag.cs
@@ -0,0 +1,147 @@
+//-----------------------------------------------------------------------
+// <copyright file="DataBag.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+
+ /// <summary>
+ /// A collection of message parts that will be serialized into a single string,
+ /// to be set into a larger message.
+ /// </summary>
+ internal abstract class DataBag : IMessage {
+ /// <summary>
+ /// The default version for DataBags.
+ /// </summary>
+ private static readonly Version DefaultVersion = new Version(1, 0);
+
+ /// <summary>
+ /// The backing field for the <see cref="IMessage.Version"/> property.
+ /// </summary>
+ private Version version;
+
+ /// <summary>
+ /// A dictionary to contain extra message data.
+ /// </summary>
+ private Dictionary<string, string> extraData = new Dictionary<string, string>();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DataBag"/> class.
+ /// </summary>
+ protected DataBag()
+ : this(DefaultVersion) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DataBag"/> class.
+ /// </summary>
+ /// <param name="version">The DataBag version.</param>
+ protected DataBag(Version version) {
+ Contract.Requires(version != null);
+ this.version = version;
+ }
+
+ #region IMessage Properties
+
+ /// <summary>
+ /// Gets the version of the protocol or extension this message is prepared to implement.
+ /// </summary>
+ /// <remarks>
+ /// Implementations of this interface should ensure that this property never returns null.
+ /// </remarks>
+ Version IMessage.Version {
+ get { return this.version; }
+ }
+
+ /// <summary>
+ /// Gets the extra, non-standard Protocol parameters included in the message.
+ /// </summary>
+ /// <value></value>
+ /// <remarks>
+ /// Implementations of this interface should ensure that this property never returns null.
+ /// </remarks>
+ public IDictionary<string, string> ExtraData {
+ get { return this.extraData; }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets or sets the nonce.
+ /// </summary>
+ /// <value>The nonce.</value>
+ [MessagePart]
+ internal byte[] Nonce { get; set; }
+
+ /// <summary>
+ /// Gets or sets the UTC creation date of this token.
+ /// </summary>
+ /// <value>The UTC creation date.</value>
+ [MessagePart("ts", IsRequired = true, Encoder = typeof(TimestampEncoder))]
+ internal DateTime UtcCreationDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the signature.
+ /// </summary>
+ /// <value>The signature.</value>
+ internal byte[] Signature { get; set; }
+
+ /// <summary>
+ /// Gets or sets the message that delivered this DataBag instance to this host.
+ /// </summary>
+ protected internal IProtocolMessage ContainingMessage { get; set; }
+
+ /// <summary>
+ /// Gets the type of this instance.
+ /// </summary>
+ /// <value>The type of the bag.</value>
+ /// <remarks>
+ /// This ensures that one token cannot be misused as another kind of token.
+ /// </remarks>
+ [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Accessed by reflection")]
+ [MessagePart("t", IsRequired = true, AllowEmpty = false)]
+ private Type BagType {
+ get { return this.GetType(); }
+ }
+
+ #region IMessage Methods
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ void IMessage.EnsureValidMessage() {
+ this.EnsureValidMessage();
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ protected virtual void EnsureValidMessage() {
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/DataBagFormatterBase.cs b/src/DotNetOpenAuth/Messaging/DataBagFormatterBase.cs
new file mode 100644
index 0000000..9cb63e6
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/DataBagFormatterBase.cs
@@ -0,0 +1,354 @@
+//-----------------------------------------------------------------------
+// <copyright file="DataBagFormatterBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.IO;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using System.Web;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.Messaging.Reflection;
+
+ /// <summary>
+ /// A serializer for <see cref="DataBag"/>-derived types
+ /// </summary>
+ /// <typeparam name="T">The DataBag-derived type that is to be serialized/deserialized.</typeparam>
+ internal abstract class DataBagFormatterBase<T> : IDataBagFormatter<T> where T : DataBag, new() {
+ /// <summary>
+ /// The message description cache to use for data bag types.
+ /// </summary>
+ protected static readonly MessageDescriptionCollection MessageDescriptions = new MessageDescriptionCollection();
+
+ /// <summary>
+ /// The length of the nonce to include in tokens that can be decoded once only.
+ /// </summary>
+ private const int NonceLength = 6;
+
+ /// <summary>
+ /// The minimum allowable lifetime for the key used to encrypt/decrypt or sign this databag.
+ /// </summary>
+ private readonly TimeSpan minimumAge = TimeSpan.FromDays(1);
+
+ /// <summary>
+ /// The symmetric key store with the secret used for signing/encryption of verification codes and refresh tokens.
+ /// </summary>
+ private readonly ICryptoKeyStore cryptoKeyStore;
+
+ /// <summary>
+ /// The bucket for symmetric keys.
+ /// </summary>
+ private readonly string cryptoKeyBucket;
+
+ /// <summary>
+ /// The crypto to use for signing access tokens.
+ /// </summary>
+ private readonly RSACryptoServiceProvider asymmetricSigning;
+
+ /// <summary>
+ /// The crypto to use for encrypting access tokens.
+ /// </summary>
+ private readonly RSACryptoServiceProvider asymmetricEncrypting;
+
+ /// <summary>
+ /// A value indicating whether the data in this instance will be protected against tampering.
+ /// </summary>
+ private readonly bool signed;
+
+ /// <summary>
+ /// The nonce store to use to ensure that this instance is only decoded once.
+ /// </summary>
+ private readonly INonceStore decodeOnceOnly;
+
+ /// <summary>
+ /// The maximum age of a token that can be decoded; useful only when <see cref="decodeOnceOnly"/> is <c>true</c>.
+ /// </summary>
+ private readonly TimeSpan? maximumAge;
+
+ /// <summary>
+ /// A value indicating whether the data in this instance will be protected against eavesdropping.
+ /// </summary>
+ private readonly bool encrypted;
+
+ /// <summary>
+ /// A value indicating whether the data in this instance will be GZip'd.
+ /// </summary>
+ private readonly bool compressed;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DataBagFormatterBase&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="signingKey">The crypto service provider with the asymmetric key to use for signing or verifying the token.</param>
+ /// <param name="encryptingKey">The crypto service provider with the asymmetric key to use for encrypting or decrypting the token.</param>
+ /// <param name="compressed">A value indicating whether the data in this instance will be GZip'd.</param>
+ /// <param name="maximumAge">The maximum age of a token that can be decoded; useful only when <paramref name="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ protected DataBagFormatterBase(RSACryptoServiceProvider signingKey = null, RSACryptoServiceProvider encryptingKey = null, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : this(signingKey != null, encryptingKey != null, compressed, maximumAge, decodeOnceOnly) {
+ this.asymmetricSigning = signingKey;
+ this.asymmetricEncrypting = encryptingKey;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DataBagFormatterBase&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store used when signing or encrypting.</param>
+ /// <param name="bucket">The bucket in which symmetric keys are stored for signing/encrypting data.</param>
+ /// <param name="signed">A value indicating whether the data in this instance will be protected against tampering.</param>
+ /// <param name="encrypted">A value indicating whether the data in this instance will be protected against eavesdropping.</param>
+ /// <param name="compressed">A value indicating whether the data in this instance will be GZip'd.</param>
+ /// <param name="minimumAge">The required minimum lifespan within which this token must be decodable and verifiable; useful only when <paramref name="signed"/> and/or <paramref name="encrypted"/> is true.</param>
+ /// <param name="maximumAge">The maximum age of a token that can be decoded; useful only when <paramref name="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ protected DataBagFormatterBase(ICryptoKeyStore cryptoKeyStore = null, string bucket = null, bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? minimumAge = null, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : this(signed, encrypted, compressed, maximumAge, decodeOnceOnly) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(bucket) || cryptoKeyStore == null);
+ Contract.Requires<ArgumentException>(cryptoKeyStore != null || (!signed && !encrypted));
+
+ this.cryptoKeyStore = cryptoKeyStore;
+ this.cryptoKeyBucket = bucket;
+ if (minimumAge.HasValue) {
+ this.minimumAge = minimumAge.Value;
+ }
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DataBagFormatterBase&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="signed">A value indicating whether the data in this instance will be protected against tampering.</param>
+ /// <param name="encrypted">A value indicating whether the data in this instance will be protected against eavesdropping.</param>
+ /// <param name="compressed">A value indicating whether the data in this instance will be GZip'd.</param>
+ /// <param name="maximumAge">The maximum age of a token that can be decoded; useful only when <paramref name="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ private DataBagFormatterBase(bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null) {
+ Contract.Requires<ArgumentException>(signed || decodeOnceOnly == null);
+ Contract.Requires<ArgumentException>(maximumAge.HasValue || decodeOnceOnly == null);
+
+ this.signed = signed;
+ this.maximumAge = maximumAge;
+ this.decodeOnceOnly = decodeOnceOnly;
+ this.encrypted = encrypted;
+ this.compressed = compressed;
+ }
+
+ /// <summary>
+ /// Serializes the specified message, including compression, encryption, signing, and nonce handling where applicable.
+ /// </summary>
+ /// <param name="message">The message to serialize. Must not be null.</param>
+ /// <returns>A non-null, non-empty value.</returns>
+ public string Serialize(T message) {
+ message.UtcCreationDate = DateTime.UtcNow;
+
+ if (this.decodeOnceOnly != null) {
+ message.Nonce = MessagingUtilities.GetNonCryptoRandomData(NonceLength);
+ }
+
+ byte[] encoded = this.SerializeCore(message);
+
+ if (this.compressed) {
+ encoded = MessagingUtilities.Compress(encoded);
+ }
+
+ string symmetricSecretHandle = null;
+ if (this.encrypted) {
+ encoded = this.Encrypt(encoded, out symmetricSecretHandle);
+ }
+
+ if (this.signed) {
+ message.Signature = this.CalculateSignature(encoded, symmetricSecretHandle);
+ }
+
+ int capacity = this.signed ? 4 + message.Signature.Length + 4 + encoded.Length : encoded.Length;
+ using (var finalStream = new MemoryStream(capacity)) {
+ var writer = new BinaryWriter(finalStream);
+ if (this.signed) {
+ writer.WriteBuffer(message.Signature);
+ }
+
+ writer.WriteBuffer(encoded);
+ writer.Flush();
+
+ string payload = MessagingUtilities.ConvertToBase64WebSafeString(finalStream.ToArray());
+ string result = payload;
+ if (symmetricSecretHandle != null && (this.signed || this.encrypted)) {
+ result = MessagingUtilities.CombineKeyHandleAndPayload(symmetricSecretHandle, payload);
+ }
+
+ return result;
+ }
+ }
+
+ /// <summary>
+ /// Deserializes a <see cref="DataBag"/>, including decompression, decryption, signature and nonce validation where applicable.
+ /// </summary>
+ /// <param name="containingMessage">The message that contains the <see cref="DataBag"/> serialized value. Must not be nulll.</param>
+ /// <param name="value">The serialized form of the <see cref="DataBag"/> to deserialize. Must not be null or empty.</param>
+ /// <returns>The deserialized value. Never null.</returns>
+ public T Deserialize(IProtocolMessage containingMessage, string value) {
+ string symmetricSecretHandle = null;
+ if (this.encrypted && this.cryptoKeyStore != null) {
+ string valueWithoutHandle;
+ MessagingUtilities.ExtractKeyHandleAndPayload(containingMessage, "<TODO>", value, out symmetricSecretHandle, out valueWithoutHandle);
+ value = valueWithoutHandle;
+ }
+
+ var message = new T { ContainingMessage = containingMessage };
+ byte[] data = MessagingUtilities.FromBase64WebSafeString(value);
+
+ byte[] signature = null;
+ if (this.signed) {
+ using (var dataStream = new MemoryStream(data)) {
+ var dataReader = new BinaryReader(dataStream);
+ signature = dataReader.ReadBuffer();
+ data = dataReader.ReadBuffer();
+ }
+
+ // Verify that the verification code was issued by message authorization server.
+ ErrorUtilities.VerifyProtocol(this.IsSignatureValid(data, signature, symmetricSecretHandle), MessagingStrings.SignatureInvalid);
+ }
+
+ if (this.encrypted) {
+ data = this.Decrypt(data, symmetricSecretHandle);
+ }
+
+ if (this.compressed) {
+ data = MessagingUtilities.Decompress(data);
+ }
+
+ this.DeserializeCore(message, data);
+ message.Signature = signature; // TODO: we don't really need this any more, do we?
+
+ if (this.maximumAge.HasValue) {
+ // Has message verification code expired?
+ DateTime expirationDate = message.UtcCreationDate + this.maximumAge.Value;
+ if (expirationDate < DateTime.UtcNow) {
+ throw new ExpiredMessageException(expirationDate, containingMessage);
+ }
+ }
+
+ // Has message verification code already been used to obtain an access/refresh token?
+ if (this.decodeOnceOnly != null) {
+ ErrorUtilities.VerifyInternal(this.maximumAge.HasValue, "Oops! How can we validate a nonce without a maximum message age?");
+ string context = "{" + GetType().FullName + "}";
+ if (!this.decodeOnceOnly.StoreNonce(context, Convert.ToBase64String(message.Nonce), message.UtcCreationDate)) {
+ Logger.OpenId.ErrorFormat("Replayed nonce detected ({0} {1}). Rejecting message.", message.Nonce, message.UtcCreationDate);
+ throw new ReplayedMessageException(containingMessage);
+ }
+ }
+
+ ((IMessage)message).EnsureValidMessage();
+
+ return message;
+ }
+
+ /// <summary>
+ /// Serializes the <see cref="DataBag"/> instance to a buffer.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <returns>The buffer containing the serialized data.</returns>
+ protected abstract byte[] SerializeCore(T message);
+
+ /// <summary>
+ /// Deserializes the <see cref="DataBag"/> instance from a buffer.
+ /// </summary>
+ /// <param name="message">The message instance to initialize with data from the buffer.</param>
+ /// <param name="data">The data buffer.</param>
+ protected abstract void DeserializeCore(T message, byte[] data);
+
+ /// <summary>
+ /// Determines whether the signature on this instance is valid.
+ /// </summary>
+ /// <param name="signedData">The signed data.</param>
+ /// <param name="signature">The signature.</param>
+ /// <param name="symmetricSecretHandle">The symmetric secret handle. <c>null</c> when using an asymmetric algorithm.</param>
+ /// <returns>
+ /// <c>true</c> if the signature is valid; otherwise, <c>false</c>.
+ /// </returns>
+ private bool IsSignatureValid(byte[] signedData, byte[] signature, string symmetricSecretHandle) {
+ Contract.Requires<ArgumentNullException>(signedData != null);
+ Contract.Requires<ArgumentNullException>(signature != null);
+
+ if (this.asymmetricSigning != null) {
+ using (var hasher = new SHA1CryptoServiceProvider()) {
+ return this.asymmetricSigning.VerifyData(signedData, hasher, signature);
+ }
+ } else {
+ return MessagingUtilities.AreEquivalentConstantTime(signature, this.CalculateSignature(signedData, symmetricSecretHandle));
+ }
+ }
+
+ /// <summary>
+ /// Calculates the signature for the data in this verification code.
+ /// </summary>
+ /// <param name="bytesToSign">The bytes to sign.</param>
+ /// <param name="symmetricSecretHandle">The symmetric secret handle. <c>null</c> when using an asymmetric algorithm.</param>
+ /// <returns>
+ /// The calculated signature.
+ /// </returns>
+ private byte[] CalculateSignature(byte[] bytesToSign, string symmetricSecretHandle) {
+ Contract.Requires<ArgumentNullException>(bytesToSign != null);
+ Contract.Requires<InvalidOperationException>(this.asymmetricSigning != null || this.cryptoKeyStore != null);
+ Contract.Ensures(Contract.Result<byte[]>() != null);
+
+ if (this.asymmetricSigning != null) {
+ using (var hasher = new SHA1CryptoServiceProvider()) {
+ return this.asymmetricSigning.SignData(bytesToSign, hasher);
+ }
+ } else {
+ var key = this.cryptoKeyStore.GetKey(this.cryptoKeyBucket, symmetricSecretHandle);
+ ErrorUtilities.VerifyProtocol(key != null, "Missing decryption key.");
+ using (var symmetricHasher = new HMACSHA256(key.Key)) {
+ return symmetricHasher.ComputeHash(bytesToSign);
+ }
+ }
+ }
+
+ /// <summary>
+ /// Encrypts the specified value using either the symmetric or asymmetric encryption algorithm as appropriate.
+ /// </summary>
+ /// <param name="value">The value.</param>
+ /// <param name="symmetricSecretHandle">Receives the symmetric secret handle. <c>null</c> when using an asymmetric algorithm.</param>
+ /// <returns>
+ /// The encrypted value.
+ /// </returns>
+ private byte[] Encrypt(byte[] value, out string symmetricSecretHandle) {
+ Contract.Requires<InvalidOperationException>(this.asymmetricEncrypting != null || this.cryptoKeyStore != null);
+
+ if (this.asymmetricEncrypting != null) {
+ symmetricSecretHandle = null;
+ return this.asymmetricEncrypting.EncryptWithRandomSymmetricKey(value);
+ } else {
+ var cryptoKey = this.cryptoKeyStore.GetCurrentKey(this.cryptoKeyBucket, this.minimumAge);
+ symmetricSecretHandle = cryptoKey.Key;
+ return MessagingUtilities.Encrypt(value, cryptoKey.Value.Key);
+ }
+ }
+
+ /// <summary>
+ /// Decrypts the specified value using either the symmetric or asymmetric encryption algorithm as appropriate.
+ /// </summary>
+ /// <param name="value">The value.</param>
+ /// <param name="symmetricSecretHandle">The symmetric secret handle. <c>null</c> when using an asymmetric algorithm.</param>
+ /// <returns>
+ /// The decrypted value.
+ /// </returns>
+ private byte[] Decrypt(byte[] value, string symmetricSecretHandle) {
+ Contract.Requires<InvalidOperationException>(this.asymmetricEncrypting != null || symmetricSecretHandle != null);
+
+ if (this.asymmetricEncrypting != null) {
+ return this.asymmetricEncrypting.DecryptWithRandomSymmetricKey(value);
+ } else {
+ var key = this.cryptoKeyStore.GetKey(this.cryptoKeyBucket, symmetricSecretHandle);
+ ErrorUtilities.VerifyProtocol(key != null, "Missing decryption key.");
+ return MessagingUtilities.Decrypt(value, key.Key);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/EnumerableCache.cs b/src/DotNetOpenAuth/Messaging/EnumerableCache.cs
index 29ec533..be65bca 100644
--- a/src/DotNetOpenAuth/Messaging/EnumerableCache.cs
+++ b/src/DotNetOpenAuth/Messaging/EnumerableCache.cs
@@ -137,7 +137,7 @@ namespace DotNetOpenAuth.Messaging {
private int cachePosition = -1;
/// <summary>
- /// Initializes a new instance of the <see cref="EnumeratorCache"/> class.
+ /// Initializes a new instance of the EnumeratorCache class.
/// </summary>
/// <param name="parent">The parent cached enumerable whose GetEnumerator method is calling this constructor.</param>
internal EnumeratorCache(EnumerableCache<T> parent) {
diff --git a/src/DotNetOpenAuth/Messaging/IDataBagFormatter.cs b/src/DotNetOpenAuth/Messaging/IDataBagFormatter.cs
new file mode 100644
index 0000000..c7dcc42
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/IDataBagFormatter.cs
@@ -0,0 +1,75 @@
+//-----------------------------------------------------------------------
+// <copyright file="IDataBagFormatter.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Diagnostics.Contracts;
+
+ /// <summary>
+ /// A serializer for <see cref="DataBag"/>-derived types
+ /// </summary>
+ /// <typeparam name="T">The DataBag-derived type that is to be serialized/deserialized.</typeparam>
+ [ContractClass(typeof(IDataBagFormatterContract<>))]
+ internal interface IDataBagFormatter<T> where T : DataBag, new() {
+ /// <summary>
+ /// Serializes the specified message.
+ /// </summary>
+ /// <param name="message">The message to serialize. Must not be null.</param>
+ /// <returns>A non-null, non-empty value.</returns>
+ string Serialize(T message);
+
+ /// <summary>
+ /// Deserializes a <see cref="DataBag"/>.
+ /// </summary>
+ /// <param name="containingMessage">The message that contains the <see cref="DataBag"/> serialized value. Must not be nulll.</param>
+ /// <param name="data">The serialized form of the <see cref="DataBag"/> to deserialize. Must not be null or empty.</param>
+ /// <returns>The deserialized value. Never null.</returns>
+ T Deserialize(IProtocolMessage containingMessage, string data);
+ }
+
+ /// <summary>
+ /// Contract class for the IDataBagFormatter interface.
+ /// </summary>
+ /// <typeparam name="T">The type of DataBag to serialize.</typeparam>
+ [ContractClassFor(typeof(IDataBagFormatter<>))]
+ internal abstract class IDataBagFormatterContract<T> : IDataBagFormatter<T> where T : DataBag, new() {
+ /// <summary>
+ /// Prevents a default instance of the <see cref="IDataBagFormatterContract&lt;T&gt;"/> class from being created.
+ /// </summary>
+ private IDataBagFormatterContract() {
+ }
+
+ #region IDataBagFormatter<T> Members
+
+ /// <summary>
+ /// Serializes the specified message.
+ /// </summary>
+ /// <param name="message">The message to serialize. Must not be null.</param>
+ /// <returns>A non-null, non-empty value.</returns>
+ string IDataBagFormatter<T>.Serialize(T message) {
+ Contract.Requires<ArgumentNullException>(message != null);
+ Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
+
+ throw new System.NotImplementedException();
+ }
+
+ /// <summary>
+ /// Deserializes a <see cref="DataBag"/>.
+ /// </summary>
+ /// <param name="containingMessage">The message that contains the <see cref="DataBag"/> serialized value. Must not be nulll.</param>
+ /// <param name="data">The serialized form of the <see cref="DataBag"/> to deserialize. Must not be null or empty.</param>
+ /// <returns>The deserialized value. Never null.</returns>
+ T IDataBagFormatter<T>.Deserialize(IProtocolMessage containingMessage, string data) {
+ Contract.Requires<ArgumentNullException>(containingMessage != null);
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(data));
+ Contract.Ensures(Contract.Result<T>() != null);
+
+ throw new System.NotImplementedException();
+ }
+
+ #endregion
+ }
+} \ No newline at end of file
diff --git a/src/DotNetOpenAuth/Messaging/IDirectWebRequestHandler.cs.orig b/src/DotNetOpenAuth/Messaging/IDirectWebRequestHandler.cs.orig
new file mode 100644
index 0000000..a17b379
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/IDirectWebRequestHandler.cs.orig
@@ -0,0 +1,222 @@
+//-----------------------------------------------------------------------
+// <copyright file="IDirectWebRequestHandler.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System.Collections.Generic;
+ using System.IO;
+ using System.Net;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A contract for <see cref="HttpWebRequest"/> handling.
+ /// </summary>
+ /// <remarks>
+ /// Implementations of this interface must be thread safe.
+ /// </remarks>
+ public interface IDirectWebRequestHandler {
+ /// <summary>
+ /// Determines whether this instance can support the specified options.
+ /// </summary>
+ /// <param name="options">The set of options that might be given in a subsequent web request.</param>
+ /// <returns>
+ /// <c>true</c> if this instance can support the specified options; otherwise, <c>false</c>.
+ /// </returns>
+ bool CanSupport(DirectWebRequestOptions options);
+
+ /// <summary>
+ /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param>
+ /// <returns>
+ /// The stream the caller should write out the entity data to.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/>
+ /// and any other appropriate properties <i>before</i> calling this method.
+ /// Callers <i>must</i> close and dispose of the request stream when they are done
+ /// writing to it to avoid taking up the connection too long and causing long waits on
+ /// subsequent requests.</para>
+ /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch.</para>
+ /// </remarks>
+ Stream GetRequestStream(HttpWebRequest request);
+
+ /// <summary>
+ /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param>
+ /// <param name="options">The options to apply to this web request.</param>
+ /// <returns>
+ /// The stream the caller should write out the entity data to.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/>
+ /// and any other appropriate properties <i>before</i> calling this method.
+ /// Callers <i>must</i> close and dispose of the request stream when they are done
+ /// writing to it to avoid taking up the connection too long and causing long waits on
+ /// subsequent requests.</para>
+ /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch.</para>
+ /// </remarks>
+ Stream GetRequestStream(HttpWebRequest request, DirectWebRequestOptions options);
+
+ /// <summary>
+ /// Processes an <see cref="HttpWebRequest"/> and converts the
+ /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param>
+ /// <returns>An instance of <see cref="IncomingWebResponse"/> describing the response.</returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch. The <see cref="WebException.Response"/>
+ /// value, if set, should be Closed before throwing.</para>
+ /// </remarks>
+ IncomingWebResponse GetResponse(HttpWebRequest request);
+
+ /// <summary>
+ /// Processes an <see cref="HttpWebRequest"/> and converts the
+ /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param>
+ /// <param name="options">The options to apply to this web request.</param>
+ /// <returns>An instance of <see cref="IncomingWebResponse"/> describing the response.</returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch. The <see cref="WebException.Response"/>
+ /// value, if set, should be Closed before throwing.</para>
+ /// </remarks>
+ IncomingWebResponse GetResponse(HttpWebRequest request, DirectWebRequestOptions options);
+ }
+<<<<<<< HEAD
+=======
+
+ /// <summary>
+ /// Code contract for the <see cref="IDirectWebRequestHandler"/> type.
+ /// </summary>
+ [ContractClassFor(typeof(IDirectWebRequestHandler))]
+ internal abstract class IDirectWebRequestHandlerContract : IDirectWebRequestHandler {
+ #region IDirectWebRequestHandler Members
+
+ /// <summary>
+ /// Determines whether this instance can support the specified options.
+ /// </summary>
+ /// <param name="options">The set of options that might be given in a subsequent web request.</param>
+ /// <returns>
+ /// <c>true</c> if this instance can support the specified options; otherwise, <c>false</c>.
+ /// </returns>
+ bool IDirectWebRequestHandler.CanSupport(DirectWebRequestOptions options) {
+ throw new System.NotImplementedException();
+ }
+
+ /// <summary>
+ /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param>
+ /// <returns>
+ /// The stream the caller should write out the entity data to.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/>
+ /// and any other appropriate properties <i>before</i> calling this method.
+ /// Callers <i>must</i> close and dispose of the request stream when they are done
+ /// writing to it to avoid taking up the connection too long and causing long waits on
+ /// subsequent requests.</para>
+ /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch.</para>
+ /// </remarks>
+ Stream IDirectWebRequestHandler.GetRequestStream(HttpWebRequest request) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ throw new System.NotImplementedException();
+ }
+
+ /// <summary>
+ /// Prepares an <see cref="HttpWebRequest"/> that contains an POST entity for sending the entity.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> that should contain the entity.</param>
+ /// <param name="options">The options to apply to this web request.</param>
+ /// <returns>
+ /// The stream the caller should write out the entity data to.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// <para>The caller should have set the <see cref="HttpWebRequest.ContentLength"/>
+ /// and any other appropriate properties <i>before</i> calling this method.
+ /// Callers <i>must</i> close and dispose of the request stream when they are done
+ /// writing to it to avoid taking up the connection too long and causing long waits on
+ /// subsequent requests.</para>
+ /// <para>Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch.</para>
+ /// </remarks>
+ Stream IDirectWebRequestHandler.GetRequestStream(HttpWebRequest request, DirectWebRequestOptions options) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<NotSupportedException>(((IDirectWebRequestHandler)this).CanSupport(options), MessagingStrings.DirectWebRequestOptionsNotSupported);
+ ////ErrorUtilities.VerifySupported(((IDirectWebRequestHandler)this).CanSupport(options), string.Format(MessagingStrings.DirectWebRequestOptionsNotSupported, options, this.GetType().Name));
+ throw new System.NotImplementedException();
+ }
+
+ /// <summary>
+ /// Processes an <see cref="HttpWebRequest"/> and converts the
+ /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param>
+ /// <returns>
+ /// An instance of <see cref="IncomingWebResponse"/> describing the response.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch. The <see cref="WebException.Response"/>
+ /// value, if set, should be Closed before throwing.
+ /// </remarks>
+ IncomingWebResponse IDirectWebRequestHandler.GetResponse(HttpWebRequest request) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Ensures(Contract.Result<IncomingWebResponse>() != null);
+ Contract.Ensures(Contract.Result<IncomingWebResponse>().ResponseStream != null);
+ throw new System.NotImplementedException();
+ }
+
+ /// <summary>
+ /// Processes an <see cref="HttpWebRequest"/> and converts the
+ /// <see cref="HttpWebResponse"/> to a <see cref="IncomingWebResponse"/> instance.
+ /// </summary>
+ /// <param name="request">The <see cref="HttpWebRequest"/> to handle.</param>
+ /// <param name="options">The options to apply to this web request.</param>
+ /// <returns>
+ /// An instance of <see cref="IncomingWebResponse"/> describing the response.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown for any network error.</exception>
+ /// <remarks>
+ /// Implementations should catch <see cref="WebException"/> and wrap it in a
+ /// <see cref="ProtocolException"/> to abstract away the transport and provide
+ /// a single exception type for hosts to catch. The <see cref="WebException.Response"/>
+ /// value, if set, should be Closed before throwing.
+ /// </remarks>
+ IncomingWebResponse IDirectWebRequestHandler.GetResponse(HttpWebRequest request, DirectWebRequestOptions options) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<NotSupportedException>(((IDirectWebRequestHandler)this).CanSupport(options), MessagingStrings.DirectWebRequestOptionsNotSupported);
+ Contract.Ensures(Contract.Result<IncomingWebResponse>() != null);
+ Contract.Ensures(Contract.Result<IncomingWebResponse>().ResponseStream != null);
+
+ ////ErrorUtilities.VerifySupported(((IDirectWebRequestHandler)this).CanSupport(options), string.Format(MessagingStrings.DirectWebRequestOptionsNotSupported, options, this.GetType().Name));
+ throw new System.NotImplementedException();
+ }
+
+ #endregion
+ }
+>>>>>>> 884bcec... Fixed typo in comments.
+}
diff --git a/src/DotNetOpenAuth/Messaging/IHttpDirectResponse.cs b/src/DotNetOpenAuth/Messaging/IHttpDirectResponse.cs
index c0e7803..20c3d6f 100644
--- a/src/DotNetOpenAuth/Messaging/IHttpDirectResponse.cs
+++ b/src/DotNetOpenAuth/Messaging/IHttpDirectResponse.cs
@@ -5,16 +5,24 @@
//-----------------------------------------------------------------------
namespace DotNetOpenAuth.Messaging {
+ using System.Diagnostics.Contracts;
using System.Net;
/// <summary>
/// An interface that allows direct response messages to specify
/// HTTP transport specific properties.
/// </summary>
+ [ContractClass(typeof(IHttpDirectResponseContract))]
public interface IHttpDirectResponse {
/// <summary>
- /// Gets the HTTP status code that the direct respones should be sent with.
+ /// Gets the HTTP status code that the direct response should be sent with.
/// </summary>
HttpStatusCode HttpStatusCode { get; }
+
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ /// <value>May be an empty collection, but must not be <c>null</c>.</value>
+ WebHeaderCollection Headers { get; }
}
}
diff --git a/src/DotNetOpenAuth/Messaging/IHttpDirectResponseContract.cs b/src/DotNetOpenAuth/Messaging/IHttpDirectResponseContract.cs
new file mode 100644
index 0000000..b1ddba2
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/IHttpDirectResponseContract.cs
@@ -0,0 +1,43 @@
+//-----------------------------------------------------------------------
+// <copyright file="IHttpDirectResponseContract.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Net;
+ using System.Text;
+
+ /// <summary>
+ /// Contract class for the <see cref="IHttpDirectResponse"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IHttpDirectResponse))]
+ public abstract class IHttpDirectResponseContract : IHttpDirectResponse {
+ #region IHttpDirectResponse Members
+
+ /// <summary>
+ /// Gets the HTTP status code that the direct response should be sent with.
+ /// </summary>
+ /// <value></value>
+ HttpStatusCode IHttpDirectResponse.HttpStatusCode {
+ get { throw new NotImplementedException(); }
+ }
+
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ /// <value>May be an empty collection, but must not be <c>null</c>.</value>
+ WebHeaderCollection IHttpDirectResponse.Headers {
+ get {
+ Contract.Ensures(Contract.Result<WebHeaderCollection>() != null);
+ throw new NotImplementedException();
+ }
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/IHttpIndirectResponse.cs b/src/DotNetOpenAuth/Messaging/IHttpIndirectResponse.cs
new file mode 100644
index 0000000..7d0fe0c
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/IHttpIndirectResponse.cs
@@ -0,0 +1,22 @@
+//-----------------------------------------------------------------------
+// <copyright file="IHttpIndirectResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System.Diagnostics.Contracts;
+ using System.Net;
+
+ /// <summary>
+ /// An interface that allows indirect response messages to specify
+ /// HTTP transport specific properties.
+ /// </summary>
+ public interface IHttpIndirectResponse {
+ /// <summary>
+ /// Gets a value indicating whether the payload for the message should be included
+ /// in the redirect fragment instead of the query string or POST entity.
+ /// </summary>
+ bool Include301RedirectPayloadInFragment { get; }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/IStreamSerializingDataBag.cs b/src/DotNetOpenAuth/Messaging/IStreamSerializingDataBag.cs
new file mode 100644
index 0000000..2003f9e
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/IStreamSerializingDataBag.cs
@@ -0,0 +1,55 @@
+//-----------------------------------------------------------------------
+// <copyright file="IStreamSerializingDataBag.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Diagnostics.Contracts;
+ using System.IO;
+
+ /// <summary>
+ /// An interface implemented by <see cref="DataBag"/>-derived types that support binary serialization.
+ /// </summary>
+ [ContractClass(typeof(IStreamSerializingDataBaContract))]
+ internal interface IStreamSerializingDataBag {
+ /// <summary>
+ /// Serializes the instance to the specified stream.
+ /// </summary>
+ /// <param name="stream">The stream.</param>
+ void Serialize(Stream stream);
+
+ /// <summary>
+ /// Initializes the fields on this instance from the specified stream.
+ /// </summary>
+ /// <param name="stream">The stream.</param>
+ void Deserialize(Stream stream);
+ }
+
+ /// <summary>
+ /// Code Contract for the <see cref="IStreamSerializingDataBag"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IStreamSerializingDataBag))]
+ internal abstract class IStreamSerializingDataBaContract : IStreamSerializingDataBag {
+ /// <summary>
+ /// Serializes the instance to the specified stream.
+ /// </summary>
+ /// <param name="stream">The stream.</param>
+ void IStreamSerializingDataBag.Serialize(Stream stream) {
+ Contract.Requires(stream != null);
+ Contract.Requires(stream.CanWrite);
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Initializes the fields on this instance from the specified stream.
+ /// </summary>
+ /// <param name="stream">The stream.</param>
+ void IStreamSerializingDataBag.Deserialize(Stream stream) {
+ Contract.Requires(stream != null);
+ Contract.Requires(stream.CanRead);
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/MessageSerializer.cs b/src/DotNetOpenAuth/Messaging/MessageSerializer.cs
index e1625b9..77a206c 100644
--- a/src/DotNetOpenAuth/Messaging/MessageSerializer.cs
+++ b/src/DotNetOpenAuth/Messaging/MessageSerializer.cs
@@ -12,6 +12,7 @@ namespace DotNetOpenAuth.Messaging {
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Reflection;
+ using System.Xml;
using DotNetOpenAuth.Messaging.Reflection;
using DotNetOpenAuth.OAuth.ChannelElements;
@@ -53,6 +54,96 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Reads JSON as a flat dictionary into a message.
+ /// </summary>
+ /// <param name="messageDictionary">The message dictionary to fill with the JSON-deserialized data.</param>
+ /// <param name="reader">The JSON reader.</param>
+ internal static void DeserializeJsonAsFlatDictionary(IDictionary<string, string> messageDictionary, XmlDictionaryReader reader) {
+ Contract.Requires<ArgumentNullException>(messageDictionary != null);
+ Contract.Requires<ArgumentNullException>(reader != null);
+
+ reader.Read(); // one extra one to skip the root node.
+ while (reader.Read()) {
+ if (reader.NodeType == XmlNodeType.EndElement) {
+ // This is likely the closing </root> tag.
+ continue;
+ }
+
+ string key = reader.Name;
+ reader.Read();
+ string value = reader.ReadContentAsString();
+ messageDictionary[key] = value;
+ }
+ }
+
+ /// <summary>
+ /// Reads the data from a message instance and writes a XML/JSON encoding of it.
+ /// </summary>
+ /// <param name="messageDictionary">The message to be serialized.</param>
+ /// <param name="writer">The writer to use for the serialized form.</param>
+ /// <remarks>
+ /// Use <see cref="System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonWriter(System.IO.Stream)"/>
+ /// to create the <see cref="XmlDictionaryWriter"/> instance capable of emitting JSON.
+ /// </remarks>
+ [Pure]
+ internal static void Serialize(MessageDictionary messageDictionary, XmlDictionaryWriter writer) {
+ Contract.Requires<ArgumentNullException>(messageDictionary != null);
+ Contract.Requires<ArgumentNullException>(writer != null);
+
+ writer.WriteStartElement("root");
+ writer.WriteAttributeString("type", "object");
+ foreach (var pair in messageDictionary) {
+ bool include = false;
+ string type = "string";
+ MessagePart partDescription;
+ if (messageDictionary.Description.Mapping.TryGetValue(pair.Key, out partDescription)) {
+ Contract.Assume(partDescription != null);
+ if (partDescription.IsRequired || partDescription.IsNondefaultValueSet(messageDictionary.Message)) {
+ include = true;
+ if (IsNumeric(partDescription.MemberDeclaredType)) {
+ type = "number";
+ } else if (partDescription.MemberDeclaredType.IsAssignableFrom(typeof(bool))) {
+ type = "boolean";
+ }
+ }
+ } else {
+ // This is extra data. We always write it out.
+ include = true;
+ }
+
+ if (include) {
+ writer.WriteStartElement(pair.Key);
+ writer.WriteAttributeString("type", type);
+ writer.WriteString(pair.Value);
+ writer.WriteEndElement();
+ }
+ }
+
+ writer.WriteEndElement();
+ }
+
+ /// <summary>
+ /// Reads XML/JSON into a message dictionary.
+ /// </summary>
+ /// <param name="messageDictionary">The message to deserialize into.</param>
+ /// <param name="reader">The XML/JSON to read into the message.</param>
+ /// <exception cref="ProtocolException">Thrown when protocol rules are broken by the incoming message.</exception>
+ /// <remarks>
+ /// Use <see cref="System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(System.IO.Stream, System.Xml.XmlDictionaryReaderQuotas)"/>
+ /// to create the <see cref="XmlDictionaryReader"/> instance capable of reading JSON.
+ /// </remarks>
+ internal static void Deserialize(MessageDictionary messageDictionary, XmlDictionaryReader reader) {
+ Contract.Requires<ArgumentNullException>(messageDictionary != null);
+ Contract.Requires<ArgumentNullException>(reader != null);
+
+ DeserializeJsonAsFlatDictionary(messageDictionary, reader);
+
+ // Make sure all the required parts are present and valid.
+ messageDictionary.Description.EnsureMessagePartsPassBasicValidation(messageDictionary);
+ messageDictionary.Message.EnsureValidMessage();
+ }
+
+ /// <summary>
/// Reads the data from a message instance and returns a series of name=value pairs for the fields that must be included in the message.
/// </summary>
/// <param name="messageDictionary">The message to be serialized.</param>
@@ -66,7 +157,7 @@ namespace DotNetOpenAuth.Messaging {
// Rather than hand back the whole message dictionary (which
// includes keys with blank values), create a new dictionary
// that only has required keys, and optional keys whose
- // values are not empty.
+ // values are not empty (or default).
var result = new Dictionary<string, string>();
foreach (var pair in messageDictionary) {
MessagePart partDescription;
@@ -115,6 +206,24 @@ namespace DotNetOpenAuth.Messaging {
}
}
+ /// <summary>
+ /// Determines whether the specified type is numeric.
+ /// </summary>
+ /// <param name="type">The type to test.</param>
+ /// <returns>
+ /// <c>true</c> if the specified type is numeric; otherwise, <c>false</c>.
+ /// </returns>
+ private static bool IsNumeric(Type type) {
+ return type.IsAssignableFrom(typeof(double))
+ || type.IsAssignableFrom(typeof(float))
+ || type.IsAssignableFrom(typeof(short))
+ || type.IsAssignableFrom(typeof(int))
+ || type.IsAssignableFrom(typeof(long))
+ || type.IsAssignableFrom(typeof(ushort))
+ || type.IsAssignableFrom(typeof(uint))
+ || type.IsAssignableFrom(typeof(ulong));
+ }
+
#if CONTRACTS_FULL
/// <summary>
/// Verifies conditions that should be true for any valid state of this object.
diff --git a/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs b/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs
index e2638c9..11bd751 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs
+++ b/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs
@@ -133,6 +133,15 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Looks up a localized string similar to Unable to instantiate the message part encoder/decoder type {0}..
+ /// </summary>
+ internal static string EncoderInstantiationFailed {
+ get {
+ return ResourceManager.GetString("EncoderInstantiationFailed", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Looks up a localized string similar to Error while deserializing message {0}..
/// </summary>
internal static string ErrorDeserializingMessage {
@@ -367,6 +376,15 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Looks up a localized string similar to The following message parts had constant value requirements that were unsatisfied: {0}.
+ /// </summary>
+ internal static string RequiredMessagePartConstantIncorrect {
+ get {
+ return ResourceManager.GetString("RequiredMessagePartConstantIncorrect", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Looks up a localized string similar to The following required non-empty parameters were empty in the {0} message: {1}.
/// </summary>
internal static string RequiredNonEmptyParameterWasEmpty {
@@ -439,6 +457,15 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Looks up a localized string similar to This message factory does not support message type(s): {0}.
+ /// </summary>
+ internal static string StandardMessageFactoryUnsupportedMessageType {
+ get {
+ return ResourceManager.GetString("StandardMessageFactoryUnsupportedMessageType", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Looks up a localized string similar to The stream must have a known length..
/// </summary>
internal static string StreamMustHaveKnownLength {
@@ -601,6 +628,15 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Looks up a localized string similar to This blob is not a recognized encryption format..
+ /// </summary>
+ internal static string UnsupportedEncryptionAlgorithm {
+ get {
+ return ResourceManager.GetString("UnsupportedEncryptionAlgorithm", resourceCulture);
+ }
+ }
+
+ /// <summary>
/// Looks up a localized string similar to The HTTP verb &apos;{0}&apos; is unrecognized and unsupported..
/// </summary>
internal static string UnsupportedHttpVerb {
diff --git a/src/DotNetOpenAuth/Messaging/MessagingStrings.resx b/src/DotNetOpenAuth/Messaging/MessagingStrings.resx
index 30490c7..bd10b76 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingStrings.resx
+++ b/src/DotNetOpenAuth/Messaging/MessagingStrings.resx
@@ -303,9 +303,21 @@
<data name="SessionRequired" xml:space="preserve">
<value>An HttpContext.Current.Session object is required.</value>
</data>
+ <data name="StandardMessageFactoryUnsupportedMessageType" xml:space="preserve">
+ <value>This message factory does not support message type(s): {0}</value>
+ </data>
+ <data name="RequiredMessagePartConstantIncorrect" xml:space="preserve">
+ <value>The following message parts had constant value requirements that were unsatisfied: {0}</value>
+ </data>
+ <data name="EncoderInstantiationFailed" xml:space="preserve">
+ <value>Unable to instantiate the message part encoder/decoder type {0}.</value>
+ </data>
<data name="MessageTimestampInFuture" xml:space="preserve">
<value>This message has a timestamp of {0}, which is beyond the allowable clock skew for in the future.</value>
</data>
+ <data name="UnsupportedEncryptionAlgorithm" xml:space="preserve">
+ <value>This blob is not a recognized encryption format.</value>
+ </data>
<data name="ExtraParameterAddFailure" xml:space="preserve">
<value>Failed to add extra parameter '{0}' with value '{1}'.</value>
</data>
diff --git a/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs b/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs
index 4b20ab8..8fc691f 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs
+++ b/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs
@@ -12,6 +12,7 @@ namespace DotNetOpenAuth.Messaging {
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
+ using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Mime;
@@ -20,11 +21,13 @@ namespace DotNetOpenAuth.Messaging {
using System.Text;
using System.Web;
using System.Web.Mvc;
+ using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.Messaging.Reflection;
/// <summary>
/// A grab-bag of utility methods useful for the channel stack of the protocol.
/// </summary>
+ [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Utility class touches lots of surface area")]
public static class MessagingUtilities {
/// <summary>
/// The cryptographically strong random data generator used for creating secrets.
@@ -53,12 +56,57 @@ namespace DotNetOpenAuth.Messaging {
internal const string Digits = "0123456789";
/// <summary>
+ /// The set of digits and alphabetic letters (upper and lowercase).
+ /// </summary>
+ internal const string AlphaNumeric = UppercaseLetters + LowercaseLetters + Digits;
+
+ /// <summary>
+ /// All the characters that are allowed for use as a base64 encoding character.
+ /// </summary>
+ internal const string Base64Characters = AlphaNumeric + "+" + "/";
+
+ /// <summary>
+ /// All the characters that are allowed for use as a base64 encoding character
+ /// in the "web safe" context.
+ /// </summary>
+ internal const string Base64WebSafeCharacters = AlphaNumeric + "-" + "_";
+
+ /// <summary>
/// The set of digits, and alphabetic letters (upper and lowercase) that are clearly
/// visually distinguishable.
/// </summary>
internal const string AlphaNumericNoLookAlikes = "23456789abcdefghjkmnpqrstwxyzABCDEFGHJKMNPQRSTWXYZ";
/// <summary>
+ /// The length of private symmetric secret handles.
+ /// </summary>
+ /// <remarks>
+ /// This value needn't be high, as we only expect to have a small handful of unexpired secrets at a time,
+ /// and handle recycling is permissible.
+ /// </remarks>
+ private const int SymmetricSecretHandleLength = 4;
+
+ /// <summary>
+ /// The default lifetime of a private secret.
+ /// </summary>
+ private static readonly TimeSpan SymmetricSecretKeyLifespan = Configuration.DotNetOpenAuthSection.Configuration.Messaging.PrivateSecretMaximumAge;
+
+ /// <summary>
+ /// A character array containing just the = character.
+ /// </summary>
+ private static readonly char[] EqualsArray = new char[] { '=' };
+
+ /// <summary>
+ /// A character array containing just the , character.
+ /// </summary>
+ private static readonly char[] CommaArray = new char[] { ',' };
+
+ /// <summary>
+ /// A character array containing just the " character.
+ /// </summary>
+ private static readonly char[] QuoteArray = new char[] { '"' };
+
+ /// <summary>
/// The set of characters that are unreserved in RFC 2396 but are NOT unreserved in RFC 3986.
/// </summary>
private static readonly string[] UriRfc3986CharsToEscape = new[] { "!", "*", "'", "(", ")" };
@@ -193,6 +241,96 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Cuts off precision beyond a second on a DateTime value.
+ /// </summary>
+ /// <param name="value">The value.</param>
+ /// <returns>A DateTime with a 0 millisecond component.</returns>
+ public static DateTime CutToSecond(this DateTime value) {
+ return value - TimeSpan.FromMilliseconds(value.Millisecond);
+ }
+
+ /// <summary>
+ /// Adds a name-value pair to the end of a given URL
+ /// as part of the querystring piece. Prefixes a ? or &amp; before
+ /// first element as necessary.
+ /// </summary>
+ /// <param name="builder">The UriBuilder to add arguments to.</param>
+ /// <param name="name">The name of the parameter to add.</param>
+ /// <param name="value">The value of the argument.</param>
+ /// <remarks>
+ /// If the parameters to add match names of parameters that already are defined
+ /// in the query string, the existing ones are <i>not</i> replaced.
+ /// </remarks>
+ public static void AppendQueryArgument(this UriBuilder builder, string name, string value) {
+ AppendQueryArgs(builder, new[] { new KeyValuePair<string, string>(name, value) });
+ }
+
+ /// <summary>
+ /// Adds a set of values to a collection.
+ /// </summary>
+ /// <typeparam name="T">The type of value kept in the collection.</typeparam>
+ /// <param name="collection">The collection to add to.</param>
+ /// <param name="values">The values to add to the collection.</param>
+ public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> values) {
+ Contract.Requires<ArgumentNullException>(collection != null);
+ Contract.Requires<ArgumentNullException>(values != null);
+
+ foreach (var value in values) {
+ collection.Add(value);
+ }
+ }
+
+ /// <summary>
+ /// Tests whether two timespans are within reasonable approximation of each other.
+ /// </summary>
+ /// <param name="self">One TimeSpan.</param>
+ /// <param name="other">The other TimeSpan.</param>
+ /// <param name="marginOfError">The allowable margin of error.</param>
+ /// <returns><c>true</c> if the two TimeSpans are within <paramref name="marginOfError"/> of each other.</returns>
+ public static bool Equals(this TimeSpan self, TimeSpan other, TimeSpan marginOfError) {
+ return TimeSpan.FromMilliseconds(Math.Abs((self - other).TotalMilliseconds)) < marginOfError;
+ }
+
+ /// <summary>
+ /// Clears any existing elements in a collection and fills the collection with a given set of values.
+ /// </summary>
+ /// <typeparam name="T">The type of value kept in the collection.</typeparam>
+ /// <param name="collection">The collection to modify.</param>
+ /// <param name="values">The new values to fill the collection.</param>
+ internal static void ResetContents<T>(this ICollection<T> collection, IEnumerable<T> values) {
+ Contract.Requires<ArgumentNullException>(collection != null);
+
+ collection.Clear();
+ if (values != null) {
+ AddRange(collection, values);
+ }
+ }
+
+ /// <summary>
+ /// Strips any and all URI query parameters that serve as parts of a message.
+ /// </summary>
+ /// <param name="uri">The URI that may contain query parameters to remove.</param>
+ /// <param name="messageDescription">The message description whose parts should be removed from the URL.</param>
+ /// <returns>A cleaned URL.</returns>
+ internal static Uri StripMessagePartsFromQueryString(this Uri uri, MessageDescription messageDescription) {
+ Contract.Requires<ArgumentNullException>(uri != null);
+ Contract.Requires<ArgumentNullException>(messageDescription != null);
+
+ NameValueCollection queryArgs = HttpUtility.ParseQueryString(uri.Query);
+ var matchingKeys = queryArgs.Keys.OfType<string>().Where(key => messageDescription.Mapping.ContainsKey(key)).ToList();
+ if (matchingKeys.Count > 0) {
+ var builder = new UriBuilder(uri);
+ foreach (string key in matchingKeys) {
+ queryArgs.Remove(key);
+ }
+ builder.Query = CreateQueryString(queryArgs.ToDictionary());
+ return builder.Uri;
+ } else {
+ return uri;
+ }
+ }
+
+ /// <summary>
/// Sends a multipart HTTP POST request (useful for posting files) but doesn't call GetResponse on it.
/// </summary>
/// <param name="request">The HTTP request.</param>
@@ -246,6 +384,95 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Assembles the content of the HTTP Authorization or WWW-Authenticate header.
+ /// </summary>
+ /// <param name="scheme">The scheme.</param>
+ /// <param name="fields">The fields to include.</param>
+ /// <returns>A value prepared for an HTTP header.</returns>
+ internal static string AssembleAuthorizationHeader(string scheme, IEnumerable<KeyValuePair<string, string>> fields) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(scheme));
+ Contract.Requires<ArgumentNullException>(fields != null);
+
+ var authorization = new StringBuilder();
+ authorization.Append(scheme);
+ authorization.Append(" ");
+ foreach (var pair in fields) {
+ string key = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Key);
+ string value = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Value);
+ authorization.Append(key);
+ authorization.Append("=\"");
+ authorization.Append(value);
+ authorization.Append("\",");
+ }
+ authorization.Length--; // remove trailing comma
+ return authorization.ToString();
+ }
+
+ /// <summary>
+ /// Parses the authorization header.
+ /// </summary>
+ /// <param name="scheme">The scheme. Must not be null or empty.</param>
+ /// <param name="authorizationHeader">The authorization header. May be null or empty.</param>
+ /// <returns>A sequence of key=value pairs discovered in the header. Never null, but may be empty.</returns>
+ internal static IEnumerable<KeyValuePair<string, string>> ParseAuthorizationHeader(string scheme, string authorizationHeader) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(scheme));
+ Contract.Ensures(Contract.Result<IEnumerable<KeyValuePair<string, string>>>() != null);
+
+ string prefix = scheme + " ";
+ if (authorizationHeader != null) {
+ // The authorization header may have multiple sections. Look for the appropriate one.
+ string[] authorizationSections = new string[] { authorizationHeader }; // what is the right delimiter, if any?
+ foreach (string authorization in authorizationSections) {
+ string trimmedAuth = authorization.Trim();
+ if (trimmedAuth.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) { // RFC 2617 says this is case INsensitive
+ string data = trimmedAuth.Substring(prefix.Length);
+ return from element in data.Split(CommaArray)
+ let parts = element.Split(EqualsArray, 2)
+ let key = Uri.UnescapeDataString(parts[0])
+ let value = Uri.UnescapeDataString(parts[1].Trim(QuoteArray))
+ select new KeyValuePair<string, string>(key, value);
+ }
+ }
+ }
+
+ return Enumerable.Empty<KeyValuePair<string, string>>();
+ }
+
+ /// <summary>
+ /// Encodes a symmetric key handle and the blob that is encrypted/signed with that key into a single string
+ /// that can be decoded by <see cref="ExtractKeyHandleAndPayload"/>.
+ /// </summary>
+ /// <param name="handle">The cryptographic key handle.</param>
+ /// <param name="payload">The encrypted/signed blob.</param>
+ /// <returns>The combined encoded value.</returns>
+ internal static string CombineKeyHandleAndPayload(string handle, string payload) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(handle));
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(payload));
+ Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
+
+ return handle + "!" + payload;
+ }
+
+ /// <summary>
+ /// Extracts the key handle and encrypted blob from a string previously returned from <see cref="CombineKeyHandleAndPayload"/>.
+ /// </summary>
+ /// <param name="containingMessage">The containing message.</param>
+ /// <param name="messagePart">The message part.</param>
+ /// <param name="keyHandleAndBlob">The value previously returned from <see cref="CombineKeyHandleAndPayload"/>.</param>
+ /// <param name="handle">The crypto key handle.</param>
+ /// <param name="dataBlob">The encrypted/signed data.</param>
+ internal static void ExtractKeyHandleAndPayload(IProtocolMessage containingMessage, string messagePart, string keyHandleAndBlob, out string handle, out string dataBlob) {
+ Contract.Requires<ArgumentNullException>(containingMessage != null);
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(messagePart));
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(keyHandleAndBlob));
+
+ int privateHandleIndex = keyHandleAndBlob.IndexOf('!');
+ ErrorUtilities.VerifyProtocol(privateHandleIndex > 0, MessagingStrings.UnexpectedMessagePartValue, messagePart, keyHandleAndBlob);
+ handle = keyHandleAndBlob.Substring(0, privateHandleIndex);
+ dataBlob = keyHandleAndBlob.Substring(privateHandleIndex + 1);
+ }
+
+ /// <summary>
/// Gets a buffer of random data (not cryptographically strong).
/// </summary>
/// <param name="length">The length of the sequence to generate.</param>
@@ -298,6 +525,344 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Computes the hash of a string.
+ /// </summary>
+ /// <param name="algorithm">The hash algorithm to use.</param>
+ /// <param name="value">The value to hash.</param>
+ /// <param name="encoding">The encoding to use when converting the string to a byte array.</param>
+ /// <returns>A base64 encoded string.</returns>
+ internal static string ComputeHash(this HashAlgorithm algorithm, string value, Encoding encoding = null) {
+ Contract.Requires<ArgumentNullException>(algorithm != null);
+ Contract.Requires<ArgumentNullException>(value != null);
+ Contract.Ensures(Contract.Result<string>() != null);
+
+ encoding = encoding ?? Encoding.UTF8;
+ byte[] bytesToHash = encoding.GetBytes(value);
+ byte[] hash = algorithm.ComputeHash(bytesToHash);
+ string base64Hash = Convert.ToBase64String(hash);
+ return base64Hash;
+ }
+
+ /// <summary>
+ /// Computes the hash of a sequence of key=value pairs.
+ /// </summary>
+ /// <param name="algorithm">The hash algorithm to use.</param>
+ /// <param name="data">The data to hash.</param>
+ /// <param name="encoding">The encoding to use when converting the string to a byte array.</param>
+ /// <returns>A base64 encoded string.</returns>
+ internal static string ComputeHash(this HashAlgorithm algorithm, IDictionary<string, string> data, Encoding encoding = null) {
+ Contract.Requires<ArgumentNullException>(algorithm != null);
+ Contract.Requires<ArgumentNullException>(data != null);
+ Contract.Ensures(Contract.Result<string>() != null);
+
+ // Assemble the dictionary to sign, taking care to remove the signature itself
+ // in order to accurately reproduce the original signature (which of course didn't include
+ // the signature).
+ // Also we need to sort the dictionary's keys so that we sign in the same order as we did
+ // the last time.
+ var sortedData = new SortedDictionary<string, string>(data, StringComparer.OrdinalIgnoreCase);
+ return ComputeHash(algorithm, (IEnumerable<KeyValuePair<string, string>>)sortedData, encoding);
+ }
+
+ /// <summary>
+ /// Computes the hash of a sequence of key=value pairs.
+ /// </summary>
+ /// <param name="algorithm">The hash algorithm to use.</param>
+ /// <param name="sortedData">The data to hash.</param>
+ /// <param name="encoding">The encoding to use when converting the string to a byte array.</param>
+ /// <returns>A base64 encoded string.</returns>
+ internal static string ComputeHash(this HashAlgorithm algorithm, IEnumerable<KeyValuePair<string, string>> sortedData, Encoding encoding = null) {
+ Contract.Requires<ArgumentNullException>(algorithm != null);
+ Contract.Requires<ArgumentNullException>(sortedData != null);
+ Contract.Ensures(Contract.Result<string>() != null);
+
+ return ComputeHash(algorithm, CreateQueryString(sortedData), encoding);
+ }
+
+ /// <summary>
+ /// Encrypts a byte buffer.
+ /// </summary>
+ /// <param name="buffer">The buffer to encrypt.</param>
+ /// <param name="key">The symmetric secret to use to encrypt the buffer. Allowed values are 128, 192, or 256 bytes in length.</param>
+ /// <returns>The encrypted buffer</returns>
+ internal static byte[] Encrypt(byte[] buffer, byte[] key) {
+ using (SymmetricAlgorithm crypto = CreateSymmetricAlgorithm(key)) {
+ using (var ms = new MemoryStream()) {
+ var binaryWriter = new BinaryWriter(ms);
+ binaryWriter.Write((byte)1); // version of encryption algorithm
+ binaryWriter.Write(crypto.IV);
+ binaryWriter.Flush();
+
+ var cryptoStream = new CryptoStream(ms, crypto.CreateEncryptor(), CryptoStreamMode.Write);
+ cryptoStream.Write(buffer, 0, buffer.Length);
+ cryptoStream.FlushFinalBlock();
+
+ return ms.ToArray();
+ }
+ }
+ }
+
+ /// <summary>
+ /// Decrypts a byte buffer.
+ /// </summary>
+ /// <param name="buffer">The buffer to decrypt.</param>
+ /// <param name="key">The symmetric secret to use to decrypt the buffer. Allowed values are 128, 192, and 256.</param>
+ /// <returns>The encrypted buffer</returns>
+ [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "This Dispose is safe.")]
+ internal static byte[] Decrypt(byte[] buffer, byte[] key) {
+ using (SymmetricAlgorithm crypto = CreateSymmetricAlgorithm(key)) {
+ using (var ms = new MemoryStream(buffer)) {
+ var binaryReader = new BinaryReader(ms);
+ int algorithmVersion = binaryReader.ReadByte();
+ ErrorUtilities.VerifyProtocol(algorithmVersion == 1, MessagingStrings.UnsupportedEncryptionAlgorithm);
+ crypto.IV = binaryReader.ReadBytes(crypto.IV.Length);
+
+ // Allocate space for the decrypted buffer. We don't know how long it will be yet,
+ // but it will never be larger than the encrypted buffer.
+ var decryptedBuffer = new byte[buffer.Length];
+ int actualDecryptedLength;
+
+ using (var cryptoStream = new CryptoStream(ms, crypto.CreateDecryptor(), CryptoStreamMode.Read)) {
+ actualDecryptedLength = cryptoStream.Read(decryptedBuffer, 0, decryptedBuffer.Length);
+ }
+
+ // Create a new buffer with only the decrypted data.
+ var finalDecryptedBuffer = new byte[actualDecryptedLength];
+ Array.Copy(decryptedBuffer, finalDecryptedBuffer, actualDecryptedLength);
+ return finalDecryptedBuffer;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Encrypts a string.
+ /// </summary>
+ /// <param name="plainText">The text to encrypt.</param>
+ /// <param name="key">The symmetric secret to use to encrypt the buffer. Allowed values are 128, 192, and 256.</param>
+ /// <returns>The encrypted buffer</returns>
+ internal static string Encrypt(string plainText, byte[] key) {
+ byte[] buffer = Encoding.UTF8.GetBytes(plainText);
+ byte[] cipher = Encrypt(buffer, key);
+ return Convert.ToBase64String(cipher);
+ }
+
+ /// <summary>
+ /// Decrypts a string previously encrypted with <see cref="Encrypt(string, byte[])"/>.
+ /// </summary>
+ /// <param name="cipherText">The text to decrypt.</param>
+ /// <param name="key">The symmetric secret to use to decrypt the buffer. Allowed values are 128, 192, and 256.</param>
+ /// <returns>The encrypted buffer</returns>
+ internal static string Decrypt(string cipherText, byte[] key) {
+ byte[] cipher = Convert.FromBase64String(cipherText);
+ byte[] plainText = Decrypt(cipher, key);
+ return Encoding.UTF8.GetString(plainText);
+ }
+
+ /// <summary>
+ /// Performs asymmetric encryption of a given buffer.
+ /// </summary>
+ /// <param name="crypto">The asymmetric encryption provider to use for encryption.</param>
+ /// <param name="buffer">The buffer to encrypt.</param>
+ /// <returns>The encrypted data.</returns>
+ internal static byte[] EncryptWithRandomSymmetricKey(this RSACryptoServiceProvider crypto, byte[] buffer) {
+ Contract.Requires<ArgumentNullException>(crypto != null);
+ Contract.Requires<ArgumentNullException>(buffer != null);
+
+ using (var symmetricCrypto = new RijndaelManaged()) {
+ symmetricCrypto.Mode = CipherMode.CBC;
+
+ using (var encryptedStream = new MemoryStream()) {
+ var encryptedStreamWriter = new BinaryWriter(encryptedStream);
+
+ byte[] prequel = new byte[symmetricCrypto.Key.Length + symmetricCrypto.IV.Length];
+ Array.Copy(symmetricCrypto.Key, prequel, symmetricCrypto.Key.Length);
+ Array.Copy(symmetricCrypto.IV, 0, prequel, symmetricCrypto.Key.Length, symmetricCrypto.IV.Length);
+ byte[] encryptedPrequel = crypto.Encrypt(prequel, false);
+
+ encryptedStreamWriter.Write(encryptedPrequel.Length);
+ encryptedStreamWriter.Write(encryptedPrequel);
+ encryptedStreamWriter.Flush();
+
+ var cryptoStream = new CryptoStream(encryptedStream, symmetricCrypto.CreateEncryptor(), CryptoStreamMode.Write);
+ cryptoStream.Write(buffer, 0, buffer.Length);
+ cryptoStream.FlushFinalBlock();
+
+ return encryptedStream.ToArray();
+ }
+ }
+ }
+
+ /// <summary>
+ /// Performs asymmetric decryption of a given buffer.
+ /// </summary>
+ /// <param name="crypto">The asymmetric encryption provider to use for decryption.</param>
+ /// <param name="buffer">The buffer to decrypt.</param>
+ /// <returns>The decrypted data.</returns>
+ [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "This Dispose is safe.")]
+ internal static byte[] DecryptWithRandomSymmetricKey(this RSACryptoServiceProvider crypto, byte[] buffer) {
+ Contract.Requires<ArgumentNullException>(crypto != null);
+ Contract.Requires<ArgumentNullException>(buffer != null);
+
+ using (var encryptedStream = new MemoryStream(buffer)) {
+ var encryptedStreamReader = new BinaryReader(encryptedStream);
+
+ byte[] encryptedPrequel = encryptedStreamReader.ReadBytes(encryptedStreamReader.ReadInt32());
+ byte[] prequel = crypto.Decrypt(encryptedPrequel, false);
+
+ using (var symmetricCrypto = new RijndaelManaged()) {
+ symmetricCrypto.Mode = CipherMode.CBC;
+
+ byte[] symmetricKey = new byte[symmetricCrypto.Key.Length];
+ byte[] symmetricIV = new byte[symmetricCrypto.IV.Length];
+ Array.Copy(prequel, symmetricKey, symmetricKey.Length);
+ Array.Copy(prequel, symmetricKey.Length, symmetricIV, 0, symmetricIV.Length);
+ symmetricCrypto.Key = symmetricKey;
+ symmetricCrypto.IV = symmetricIV;
+
+ // Allocate space for the decrypted buffer. We don't know how long it will be yet,
+ // but it will never be larger than the encrypted buffer.
+ var decryptedBuffer = new byte[encryptedStream.Length - encryptedStream.Position];
+ int actualDecryptedLength;
+
+ using (var cryptoStream = new CryptoStream(encryptedStream, symmetricCrypto.CreateDecryptor(), CryptoStreamMode.Read)) {
+ actualDecryptedLength = cryptoStream.Read(decryptedBuffer, 0, decryptedBuffer.Length);
+ }
+
+ // Create a new buffer with only the decrypted data.
+ var finalDecryptedBuffer = new byte[actualDecryptedLength];
+ Array.Copy(decryptedBuffer, finalDecryptedBuffer, actualDecryptedLength);
+ return finalDecryptedBuffer;
+ }
+ }
+ }
+
+ /// <summary>
+ /// Gets a key from a given bucket with the longest remaining life, or creates a new one if necessary.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store.</param>
+ /// <param name="bucket">The bucket where the key should be found or stored.</param>
+ /// <param name="minimumRemainingLife">The minimum remaining life required on the returned key.</param>
+ /// <param name="keySize">The required size of the key, in bits.</param>
+ /// <returns>
+ /// A key-value pair whose key is the secret's handle and whose value is the cryptographic key.
+ /// </returns>
+ internal static KeyValuePair<string, CryptoKey> GetCurrentKey(this ICryptoKeyStore cryptoKeyStore, string bucket, TimeSpan minimumRemainingLife, int keySize = 256) {
+ Contract.Requires<ArgumentNullException>(cryptoKeyStore != null);
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(bucket));
+ Contract.Requires<ArgumentException>(keySize % 8 == 0);
+
+ var cryptoKeyPair = cryptoKeyStore.GetKeys(bucket).FirstOrDefault(pair => pair.Value.Key.Length == keySize / 8);
+ if (cryptoKeyPair.Value == null || cryptoKeyPair.Value.ExpiresUtc < DateTime.UtcNow + minimumRemainingLife) {
+ // No key exists with enough remaining life for the required purpose. Create a new key.
+ ErrorUtilities.VerifyHost(minimumRemainingLife <= SymmetricSecretKeyLifespan, "Unable to create a new symmetric key with the required lifespan of {0} because it is beyond the limit of {1}.", minimumRemainingLife, SymmetricSecretKeyLifespan);
+ byte[] secret = GetCryptoRandomData(keySize / 8);
+ DateTime expires = DateTime.UtcNow + SymmetricSecretKeyLifespan;
+ var cryptoKey = new CryptoKey(secret, expires);
+
+ // Store this key so we can find and use it later.
+ int failedAttempts = 0;
+ tryAgain:
+ try {
+ string handle = GetRandomString(SymmetricSecretHandleLength, Base64WebSafeCharacters);
+ cryptoKeyPair = new KeyValuePair<string, CryptoKey>(handle, cryptoKey);
+ cryptoKeyStore.StoreKey(bucket, handle, cryptoKey);
+ } catch (CryptoKeyCollisionException) {
+ ErrorUtilities.VerifyInternal(++failedAttempts < 3, "Unable to derive a unique handle to a private symmetric key.");
+ goto tryAgain;
+ }
+ }
+
+ return cryptoKeyPair;
+ }
+
+ /// <summary>
+ /// Compresses a given buffer.
+ /// </summary>
+ /// <param name="buffer">The buffer to compress.</param>
+ /// <returns>The compressed data.</returns>
+ [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "This Dispose is safe.")]
+ internal static byte[] Compress(byte[] buffer) {
+ Contract.Requires<ArgumentNullException>(buffer != null);
+ Contract.Ensures(Contract.Result<byte[]>() != null);
+
+ using (var ms = new MemoryStream()) {
+ using (var compressingStream = new DeflateStream(ms, CompressionMode.Compress, true)) {
+ compressingStream.Write(buffer, 0, buffer.Length);
+ }
+
+ return ms.ToArray();
+ }
+ }
+
+ /// <summary>
+ /// Decompresses a given buffer.
+ /// </summary>
+ /// <param name="buffer">The buffer to decompress.</param>
+ /// <returns>The decompressed data.</returns>
+ internal static byte[] Decompress(byte[] buffer) {
+ Contract.Requires<ArgumentNullException>(buffer != null);
+ Contract.Ensures(Contract.Result<byte[]>() != null);
+
+ using (var compressedDataStream = new MemoryStream(buffer)) {
+ using (var decompressedDataStream = new MemoryStream()) {
+ using (var decompressingStream = new DeflateStream(compressedDataStream, CompressionMode.Decompress, true)) {
+ decompressingStream.CopyTo(decompressedDataStream);
+ }
+
+ return decompressedDataStream.ToArray();
+ }
+ }
+ }
+
+ /// <summary>
+ /// Converts to data buffer to a base64-encoded string, using web safe characters and with the padding removed.
+ /// </summary>
+ /// <param name="data">The data buffer.</param>
+ /// <returns>A web-safe base64-encoded string without padding.</returns>
+ internal static string ConvertToBase64WebSafeString(byte[] data) {
+ var builder = new StringBuilder(Convert.ToBase64String(data));
+
+ // Swap out the URL-unsafe characters, and trim the padding characters.
+ builder.Replace('+', '-').Replace('/', '_');
+ while (builder[builder.Length - 1] == '=') { // should happen at most twice.
+ builder.Length -= 1;
+ }
+
+ return builder.ToString();
+ }
+
+ /// <summary>
+ /// Decodes a (web-safe) base64-string back to its binary buffer form.
+ /// </summary>
+ /// <param name="base64WebSafe">The base64-encoded string. May be web-safe encoded.</param>
+ /// <returns>A data buffer.</returns>
+ internal static byte[] FromBase64WebSafeString(string base64WebSafe) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(base64WebSafe));
+ Contract.Ensures(Contract.Result<byte[]>() != null);
+
+ // Restore the padding characters and original URL-unsafe characters.
+ int missingPaddingCharacters;
+ switch (base64WebSafe.Length % 4) {
+ case 3:
+ missingPaddingCharacters = 1;
+ break;
+ case 2:
+ missingPaddingCharacters = 2;
+ break;
+ case 0:
+ missingPaddingCharacters = 0;
+ break;
+ default:
+ throw ErrorUtilities.ThrowInternal("No more than two padding characters should be present for base64.");
+ }
+ var builder = new StringBuilder(base64WebSafe, base64WebSafe.Length + missingPaddingCharacters);
+ builder.Replace('-', '+').Replace('_', '/');
+ builder.Append('=', missingPaddingCharacters);
+
+ return Convert.FromBase64String(builder.ToString());
+ }
+
+ /// <summary>
/// Compares to string values for ordinal equality in such a way that its execution time does not depend on how much of the value matches.
/// </summary>
/// <param name="value1">The first value.</param>
@@ -553,6 +1118,31 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Tests whether two arrays are equal in contents and ordering,
+ /// guaranteeing roughly equivalent execution time regardless of where a signature mismatch may exist.
+ /// </summary>
+ /// <param name="first">The first array in the comparison. May not be null.</param>
+ /// <param name="second">The second array in the comparison. May not be null.</param>
+ /// <returns>True if the arrays equal; false otherwise.</returns>
+ /// <remarks>
+ /// Guaranteeing equal execution time is useful in mitigating against timing attacks on a signature
+ /// or other secret.
+ /// </remarks>
+ internal static bool AreEquivalentConstantTime(byte[] first, byte[] second) {
+ Contract.Requires<ArgumentNullException>(first != null);
+ Contract.Requires<ArgumentNullException>(second != null);
+ if (first.Length != second.Length) {
+ return false;
+ }
+
+ int result = 0;
+ for (int i = 0; i < first.Length; i++) {
+ result |= first[i] ^ second[i];
+ }
+ return result == 0;
+ }
+
+ /// <summary>
/// Tests two sequences for same contents and ordering.
/// </summary>
/// <typeparam name="T">The type of elements in the arrays.</typeparam>
@@ -693,6 +1283,35 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Adds a set of name-value pairs to the end of a given URL
+ /// as part of the fragment piece. Prefixes a # or &amp; before
+ /// first element as necessary.
+ /// </summary>
+ /// <param name="builder">The UriBuilder to add arguments to.</param>
+ /// <param name="args">
+ /// The arguments to add to the query.
+ /// If null, <paramref name="builder"/> is not changed.
+ /// </param>
+ /// <remarks>
+ /// If the parameters to add match names of parameters that already are defined
+ /// in the fragment, the existing ones are <i>not</i> replaced.
+ /// </remarks>
+ internal static void AppendFragmentArgs(this UriBuilder builder, IEnumerable<KeyValuePair<string, string>> args) {
+ Contract.Requires<ArgumentNullException>(builder != null);
+
+ if (args != null && args.Count() > 0) {
+ StringBuilder sb = new StringBuilder(50 + (args.Count() * 10));
+ if (!string.IsNullOrEmpty(builder.Fragment)) {
+ sb.Append(builder.Fragment);
+ sb.Append('&');
+ }
+ sb.Append(CreateQueryString(args));
+
+ builder.Fragment = sb.ToString();
+ }
+ }
+
+ /// <summary>
/// Adds parameters to a query string, replacing parameters that
/// match ones that already exist in the query string.
/// </summary>
@@ -789,6 +1408,18 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Collects a sequence of key=value pairs into a dictionary.
+ /// </summary>
+ /// <typeparam name="TKey">The type of the key.</typeparam>
+ /// <typeparam name="TValue">The type of the value.</typeparam>
+ /// <param name="sequence">The sequence.</param>
+ /// <returns>A dictionary.</returns>
+ internal static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> sequence) {
+ Contract.Requires<ArgumentNullException>(sequence != null);
+ return sequence.ToDictionary(pair => pair.Key, pair => pair.Value);
+ }
+
+ /// <summary>
/// Converts a <see cref="NameValueCollection"/> to an IDictionary&lt;string, string&gt;.
/// </summary>
/// <param name="nvc">The NameValueCollection to convert. May be null.</param>
@@ -892,6 +1523,31 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Writes a buffer, prefixed with its own length.
+ /// </summary>
+ /// <param name="writer">The binary writer.</param>
+ /// <param name="buffer">The buffer.</param>
+ internal static void WriteBuffer(this BinaryWriter writer, byte[] buffer) {
+ Contract.Requires<ArgumentNullException>(writer != null);
+ Contract.Requires<ArgumentNullException>(buffer != null);
+ writer.Write(buffer.Length);
+ writer.Write(buffer, 0, buffer.Length);
+ }
+
+ /// <summary>
+ /// Reads a buffer that is prefixed with its own length.
+ /// </summary>
+ /// <param name="reader">The binary reader positioned at the buffer length.</param>
+ /// <returns>The read buffer.</returns>
+ internal static byte[] ReadBuffer(this BinaryReader reader) {
+ Contract.Requires<ArgumentNullException>(reader != null);
+ int length = reader.ReadInt32();
+ byte[] buffer = new byte[length];
+ ErrorUtilities.VerifyProtocol(reader.Read(buffer, 0, length) == length, "Unexpected buffer length.");
+ return buffer;
+ }
+
+ /// <summary>
/// Constructs a Javascript expression that will create an object
/// on the user agent when assigned to a variable.
/// </summary>
@@ -994,6 +1650,28 @@ namespace DotNetOpenAuth.Messaging {
}
/// <summary>
+ /// Creates a symmetric algorithm for use in encryption/decryption.
+ /// </summary>
+ /// <param name="key">The symmetric key to use for encryption/decryption.</param>
+ /// <returns>A symmetric algorithm.</returns>
+ private static SymmetricAlgorithm CreateSymmetricAlgorithm(byte[] key) {
+ SymmetricAlgorithm result = null;
+ try {
+ result = new RijndaelManaged();
+ result.Mode = CipherMode.CBC;
+ result.Key = key;
+ return result;
+ } catch {
+ IDisposable disposableResult = result;
+ if (disposableResult != null) {
+ disposableResult.Dispose();
+ }
+
+ throw;
+ }
+ }
+
+ /// <summary>
/// A class to convert a <see cref="Comparison&lt;T&gt;"/> into an <see cref="IComparer&lt;T&gt;"/>.
/// </summary>
/// <typeparam name="T">The type of objects being compared.</typeparam>
diff --git a/src/DotNetOpenAuth/Messaging/OutgoingWebResponse.cs b/src/DotNetOpenAuth/Messaging/OutgoingWebResponse.cs
index cc655cf..b4bc22d 100644
--- a/src/DotNetOpenAuth/Messaging/OutgoingWebResponse.cs
+++ b/src/DotNetOpenAuth/Messaging/OutgoingWebResponse.cs
@@ -6,6 +6,7 @@
namespace DotNetOpenAuth.Messaging {
using System;
+ using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.IO;
@@ -125,6 +126,7 @@ namespace DotNetOpenAuth.Messaging {
/// <remarks>
/// Requires a current HttpContext.
/// </remarks>
+ [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use the Respond method instead, and prepare for execution to continue on this page beyond the call to Respond.")]
public virtual void Send() {
Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
@@ -138,27 +140,36 @@ namespace DotNetOpenAuth.Messaging {
/// <param name="context">The context of the HTTP request whose response should be set.
/// Typically this is <see cref="HttpContext.Current"/>.</param>
/// <exception cref="ThreadAbortException">Typically thrown by ASP.NET in order to prevent additional data from the page being sent to the client and corrupting the response.</exception>
+ [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use the Respond method instead, and prepare for execution to continue on this page beyond the call to Respond.")]
public virtual void Send(HttpContext context) {
- Contract.Requires<ArgumentNullException>(context != null);
+ this.Respond(context, true);
+ }
- context.Response.Clear();
- context.Response.StatusCode = (int)this.Status;
- MessagingUtilities.ApplyHeadersToResponse(this.Headers, context.Response);
- if (this.ResponseStream != null) {
- try {
- this.ResponseStream.CopyTo(context.Response.OutputStream);
- } catch (HttpException ex) {
- if (ex.ErrorCode == -2147467259 && context.Response.Output != null) {
- // Test scenarios can generate this, since the stream is being spoofed:
- // System.Web.HttpException: OutputStream is not available when a custom TextWriter is used.
- context.Response.Output.Write(this.Body);
- } else {
- throw;
- }
- }
- }
+ /// <summary>
+ /// Automatically sends the appropriate response to the user agent
+ /// and signals ASP.NET to short-circuit the page execution pipeline
+ /// now that the response has been completed.
+ /// </summary>
+ /// <remarks>
+ /// Requires a current HttpContext.
+ /// </remarks>
+ public virtual void Respond() {
+ Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
- context.Response.End();
+ this.Respond(HttpContext.Current);
+ }
+
+ /// <summary>
+ /// Automatically sends the appropriate response to the user agent
+ /// and signals ASP.NET to short-circuit the page execution pipeline
+ /// now that the response has been completed.
+ /// </summary>
+ /// <param name="context">The context of the HTTP request whose response should be set.
+ /// Typically this is <see cref="HttpContext.Current"/>.</param>
+ public virtual void Respond(HttpContext context) {
+ Contract.Requires<ArgumentNullException>(context != null);
+
+ this.Respond(context, false);
}
/// <summary>
@@ -232,5 +243,48 @@ namespace DotNetOpenAuth.Messaging {
writer.Flush();
this.ResponseStream.Seek(0, SeekOrigin.Begin);
}
+
+ /// <summary>
+ /// Automatically sends the appropriate response to the user agent
+ /// and signals ASP.NET to short-circuit the page execution pipeline
+ /// now that the response has been completed.
+ /// </summary>
+ /// <param name="context">The context of the HTTP request whose response should be set.
+ /// Typically this is <see cref="HttpContext.Current"/>.</param>
+ /// <param name="endRequest">If set to <c>false</c>, this method calls
+ /// <see cref="HttpApplication.CompleteRequest"/> rather than <see cref="HttpResponse.End"/>
+ /// to avoid a <see cref="ThreadAbortException"/>.</param>
+ protected internal virtual void Respond(HttpContext context, bool endRequest) {
+ Contract.Requires<ArgumentNullException>(context != null);
+
+ context.Response.Clear();
+ context.Response.StatusCode = (int)this.Status;
+ MessagingUtilities.ApplyHeadersToResponse(this.Headers, context.Response);
+ if (this.ResponseStream != null) {
+ try {
+ this.ResponseStream.CopyTo(context.Response.OutputStream);
+ } catch (HttpException ex) {
+ if (ex.ErrorCode == -2147467259 && context.Response.Output != null) {
+ // Test scenarios can generate this, since the stream is being spoofed:
+ // System.Web.HttpException: OutputStream is not available when a custom TextWriter is used.
+ context.Response.Output.Write(this.Body);
+ } else {
+ throw;
+ }
+ }
+ }
+
+ if (endRequest) {
+ // This approach throws an exception in order that
+ // no more code is executed in the calling page.
+ // Microsoft no longer recommends this approach.
+ context.Response.End();
+ } else if (context.ApplicationInstance != null) {
+ // This approach doesn't throw an exception, but
+ // still tells ASP.NET to short-circuit most of the
+ // request handling pipeline to speed things up.
+ context.ApplicationInstance.CompleteRequest();
+ }
+ }
}
}
diff --git a/src/DotNetOpenAuth/Messaging/OutgoingWebResponseActionResult.cs b/src/DotNetOpenAuth/Messaging/OutgoingWebResponseActionResult.cs
index 1cfc638..f2b31e9 100644
--- a/src/DotNetOpenAuth/Messaging/OutgoingWebResponseActionResult.cs
+++ b/src/DotNetOpenAuth/Messaging/OutgoingWebResponseActionResult.cs
@@ -34,7 +34,7 @@ namespace DotNetOpenAuth.Messaging {
/// </summary>
/// <param name="context">The context in which to set the response.</param>
public override void ExecuteResult(ControllerContext context) {
- this.response.Send();
+ this.response.Respond();
}
}
}
diff --git a/src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs b/src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs
index 3b41b35..7dbab80 100644
--- a/src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs
+++ b/src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs
@@ -19,16 +19,6 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// </summary>
internal class MessageDescription {
/// <summary>
- /// The type of message this instance was generated from.
- /// </summary>
- private Type messageType;
-
- /// <summary>
- /// The message version this instance was generated from.
- /// </summary>
- private Version messageVersion;
-
- /// <summary>
/// A mapping between the serialized key names and their
/// describing <see cref="MessagePart"/> instances.
/// </summary>
@@ -44,8 +34,8 @@ namespace DotNetOpenAuth.Messaging.Reflection {
Contract.Requires<ArgumentException>(typeof(IMessage).IsAssignableFrom(messageType));
Contract.Requires<ArgumentNullException>(messageVersion != null);
- this.messageType = messageType;
- this.messageVersion = messageVersion;
+ this.MessageType = messageType;
+ this.MessageVersion = messageVersion;
this.ReflectMessageType();
}
@@ -58,6 +48,32 @@ namespace DotNetOpenAuth.Messaging.Reflection {
}
/// <summary>
+ /// Gets the message version this instance was generated from.
+ /// </summary>
+ internal Version MessageVersion { get; private set; }
+
+ /// <summary>
+ /// Gets the type of message this instance was generated from.
+ /// </summary>
+ /// <value>The type of the described message.</value>
+ internal Type MessageType { get; private set; }
+
+ /// <summary>
+ /// Gets the constructors available on the message type.
+ /// </summary>
+ internal ConstructorInfo[] Constructors { get; private set; }
+
+ /// <summary>
+ /// Returns a <see cref="System.String"/> that represents this instance.
+ /// </summary>
+ /// <returns>
+ /// A <see cref="System.String"/> that represents this instance.
+ /// </returns>
+ public override string ToString() {
+ return this.MessageType.Name + " (" + this.MessageVersion + ")";
+ }
+
+ /// <summary>
/// Gets a dictionary that provides read/write access to a message.
/// </summary>
/// <param name="message">The message the dictionary should provide access to.</param>
@@ -83,51 +99,18 @@ namespace DotNetOpenAuth.Messaging.Reflection {
}
/// <summary>
- /// Reflects over some <see cref="IMessage"/>-implementing type
- /// and prepares to serialize/deserialize instances of that type.
- /// </summary>
- internal void ReflectMessageType() {
- this.mapping = new Dictionary<string, MessagePart>();
-
- Type currentType = this.messageType;
- do {
- foreach (MemberInfo member in currentType.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) {
- if (member is PropertyInfo || member is FieldInfo) {
- MessagePartAttribute partAttribute =
- (from a in member.GetCustomAttributes(typeof(MessagePartAttribute), true).OfType<MessagePartAttribute>()
- orderby a.MinVersionValue descending
- where a.MinVersionValue <= this.messageVersion
- where a.MaxVersionValue >= this.messageVersion
- select a).FirstOrDefault();
- if (partAttribute != null) {
- MessagePart part = new MessagePart(member, partAttribute);
- if (this.mapping.ContainsKey(part.Name)) {
- Logger.Messaging.WarnFormat(
- "Message type {0} has more than one message part named {1}. Inherited members will be hidden.",
- this.messageType.Name,
- part.Name);
- } else {
- this.mapping.Add(part.Name, part);
- }
- }
- }
- }
- currentType = currentType.BaseType;
- } while (currentType != null);
- }
-
- /// <summary>
/// Ensures the message parts pass basic validation.
/// </summary>
/// <param name="parts">The key/value pairs of the serialized message.</param>
internal void EnsureMessagePartsPassBasicValidation(IDictionary<string, string> parts) {
try {
- this.EnsureRequiredMessagePartsArePresent(parts.Keys);
- this.EnsureRequiredProtocolMessagePartsAreNotEmpty(parts);
+ this.CheckRequiredMessagePartsArePresent(parts.Keys, true);
+ this.CheckRequiredProtocolMessagePartsAreNotEmpty(parts, true);
+ this.CheckMessagePartsConstantValues(parts, true);
} catch (ProtocolException) {
Logger.Messaging.ErrorFormat(
"Error while performing basic validation of {0} with these message parts:{1}{2}",
- this.messageType.Name,
+ this.MessageType.Name,
Environment.NewLine,
parts.ToStringDeferred());
throw;
@@ -135,42 +118,168 @@ namespace DotNetOpenAuth.Messaging.Reflection {
}
/// <summary>
+ /// Tests whether all the required message parts pass basic validation for the given data.
+ /// </summary>
+ /// <param name="parts">The key/value pairs of the serialized message.</param>
+ /// <returns>A value indicating whether the provided data fits the message's basic requirements.</returns>
+ internal bool CheckMessagePartsPassBasicValidation(IDictionary<string, string> parts) {
+ Contract.Requires<ArgumentNullException>(parts != null);
+
+ return this.CheckRequiredMessagePartsArePresent(parts.Keys, false) &&
+ this.CheckRequiredProtocolMessagePartsAreNotEmpty(parts, false) &&
+ this.CheckMessagePartsConstantValues(parts, false);
+ }
+
+ /// <summary>
/// Verifies that a given set of keys include all the required parameters
/// for this message type or throws an exception.
/// </summary>
/// <param name="keys">The names of all parameters included in a message.</param>
- /// <exception cref="ProtocolException">Thrown when required parts of a message are not in <paramref name="keys"/></exception>
- private void EnsureRequiredMessagePartsArePresent(IEnumerable<string> keys) {
+ /// <param name="throwOnFailure">if set to <c>true</c> an exception is thrown on failure with details.</param>
+ /// <returns>A value indicating whether the provided data fits the message's basic requirements.</returns>
+ /// <exception cref="ProtocolException">
+ /// Thrown when required parts of a message are not in <paramref name="keys"/>
+ /// if <paramref name="throwOnFailure"/> is <c>true</c>.
+ /// </exception>
+ private bool CheckRequiredMessagePartsArePresent(IEnumerable<string> keys, bool throwOnFailure) {
+ Contract.Requires<ArgumentNullException>(keys != null);
+
var missingKeys = (from part in this.Mapping.Values
where part.IsRequired && !keys.Contains(part.Name)
select part.Name).ToArray();
if (missingKeys.Length > 0) {
- throw new ProtocolException(
- string.Format(
- CultureInfo.CurrentCulture,
+ if (throwOnFailure) {
+ ErrorUtilities.ThrowProtocol(
+ MessagingStrings.RequiredParametersMissing,
+ this.MessageType.FullName,
+ string.Join(", ", missingKeys));
+ } else {
+ Logger.Messaging.DebugFormat(
MessagingStrings.RequiredParametersMissing,
- this.messageType.FullName,
- string.Join(", ", missingKeys)));
+ this.MessageType.FullName,
+ missingKeys.ToStringDeferred());
+ return false;
+ }
}
+
+ return true;
}
/// <summary>
/// Ensures the protocol message parts that must not be empty are in fact not empty.
/// </summary>
/// <param name="partValues">A dictionary of key/value pairs that make up the serialized message.</param>
- private void EnsureRequiredProtocolMessagePartsAreNotEmpty(IDictionary<string, string> partValues) {
+ /// <param name="throwOnFailure">if set to <c>true</c> an exception is thrown on failure with details.</param>
+ /// <returns>A value indicating whether the provided data fits the message's basic requirements.</returns>
+ /// <exception cref="ProtocolException">
+ /// Thrown when required parts of a message are not in <paramref name="partValues"/>
+ /// if <paramref name="throwOnFailure"/> is <c>true</c>.
+ /// </exception>
+ private bool CheckRequiredProtocolMessagePartsAreNotEmpty(IDictionary<string, string> partValues, bool throwOnFailure) {
+ Contract.Requires<ArgumentNullException>(partValues != null);
+
string value;
var emptyValuedKeys = (from part in this.Mapping.Values
where !part.AllowEmpty && partValues.TryGetValue(part.Name, out value) && value != null && value.Length == 0
select part.Name).ToArray();
if (emptyValuedKeys.Length > 0) {
- throw new ProtocolException(
- string.Format(
- CultureInfo.CurrentCulture,
+ if (throwOnFailure) {
+ ErrorUtilities.ThrowProtocol(
MessagingStrings.RequiredNonEmptyParameterWasEmpty,
- this.messageType.FullName,
- string.Join(", ", emptyValuedKeys)));
+ this.MessageType.FullName,
+ string.Join(", ", emptyValuedKeys));
+ } else {
+ Logger.Messaging.DebugFormat(
+ MessagingStrings.RequiredNonEmptyParameterWasEmpty,
+ this.MessageType.FullName,
+ emptyValuedKeys.ToStringDeferred());
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Checks that a bunch of message part values meet the constant value requirements of this message description.
+ /// </summary>
+ /// <param name="partValues">The part values.</param>
+ /// <param name="throwOnFailure">if set to <c>true</c>, this method will throw on failure.</param>
+ /// <returns>A value indicating whether all the requirements are met.</returns>
+ private bool CheckMessagePartsConstantValues(IDictionary<string, string> partValues, bool throwOnFailure)
+ {
+ Contract.Requires<ArgumentNullException>(partValues != null);
+
+ var badConstantValues = (from part in this.Mapping.Values
+ where part.IsConstantValueAvailableStatically
+ where partValues.ContainsKey(part.Name)
+ where !string.Equals(partValues[part.Name], part.StaticConstantValue, StringComparison.Ordinal)
+ select part.Name).ToArray();
+ if (badConstantValues.Length > 0) {
+ if (throwOnFailure) {
+ ErrorUtilities.ThrowProtocol(
+ MessagingStrings.RequiredMessagePartConstantIncorrect,
+ this.MessageType.FullName,
+ string.Join(", ", badConstantValues));
+ } else {
+ Logger.Messaging.DebugFormat(
+ MessagingStrings.RequiredMessagePartConstantIncorrect,
+ this.MessageType.FullName,
+ badConstantValues.ToStringDeferred());
+ return false;
+ }
}
+
+ return true;
+ }
+
+ /// <summary>
+ /// Reflects over some <see cref="IMessage"/>-implementing type
+ /// and prepares to serialize/deserialize instances of that type.
+ /// </summary>
+ private void ReflectMessageType() {
+ this.mapping = new Dictionary<string, MessagePart>();
+
+ Type currentType = this.MessageType;
+ do {
+ foreach (MemberInfo member in currentType.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) {
+ if (member is PropertyInfo || member is FieldInfo) {
+ MessagePartAttribute partAttribute =
+ (from a in member.GetCustomAttributes(typeof(MessagePartAttribute), true).OfType<MessagePartAttribute>()
+ orderby a.MinVersionValue descending
+ where a.MinVersionValue <= this.MessageVersion
+ where a.MaxVersionValue >= this.MessageVersion
+ select a).FirstOrDefault();
+ if (partAttribute != null) {
+ MessagePart part = new MessagePart(member, partAttribute);
+ if (this.mapping.ContainsKey(part.Name)) {
+ Logger.Messaging.WarnFormat(
+ "Message type {0} has more than one message part named {1}. Inherited members will be hidden.",
+ this.MessageType.Name,
+ part.Name);
+ } else {
+ this.mapping.Add(part.Name, part);
+ }
+ }
+ }
+ }
+ currentType = currentType.BaseType;
+ } while (currentType != null);
+
+ BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
+ this.Constructors = this.MessageType.GetConstructors(flags);
+ }
+
+#if CONTRACTS_FULL
+ /// <summary>
+ /// Describes traits of this class that are always true.
+ /// </summary>
+ [ContractInvariantMethod]
+ private void Invariant() {
+ Contract.Invariant(this.MessageType != null);
+ Contract.Invariant(this.MessageVersion != null);
+ Contract.Invariant(this.Constructors != null);
}
+#endif
}
}
diff --git a/src/DotNetOpenAuth/Messaging/Reflection/MessageDescriptionCollection.cs b/src/DotNetOpenAuth/Messaging/Reflection/MessageDescriptionCollection.cs
index 26d088b..e332fc4 100644
--- a/src/DotNetOpenAuth/Messaging/Reflection/MessageDescriptionCollection.cs
+++ b/src/DotNetOpenAuth/Messaging/Reflection/MessageDescriptionCollection.cs
@@ -14,7 +14,7 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// A cache of <see cref="MessageDescription"/> instances.
/// </summary>
[ContractVerification(true)]
- internal class MessageDescriptionCollection {
+ internal class MessageDescriptionCollection : IEnumerable<MessageDescription> {
/// <summary>
/// A dictionary of reflected message types and the generated reflection information.
/// </summary>
@@ -23,9 +23,37 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// <summary>
/// Initializes a new instance of the <see cref="MessageDescriptionCollection"/> class.
/// </summary>
- public MessageDescriptionCollection() {
+ internal MessageDescriptionCollection() {
}
+ #region IEnumerable<MessageDescription> Members
+
+ /// <summary>
+ /// Returns an enumerator that iterates through a collection.
+ /// </summary>
+ /// <returns>
+ /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
+ /// </returns>
+ public IEnumerator<MessageDescription> GetEnumerator() {
+ return this.reflectedMessageTypes.Values.GetEnumerator();
+ }
+
+ #endregion
+
+ #region IEnumerable Members
+
+ /// <summary>
+ /// Returns an enumerator that iterates through a collection.
+ /// </summary>
+ /// <returns>
+ /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
+ /// </returns>
+ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
+ return this.reflectedMessageTypes.Values.GetEnumerator();
+ }
+
+ #endregion
+
/// <summary>
/// Gets a <see cref="MessageDescription"/> instance prepared for the
/// given message type.
diff --git a/src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs b/src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs
index 088aa05..e5cbff8 100644
--- a/src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs
+++ b/src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs
@@ -93,12 +93,14 @@ namespace DotNetOpenAuth.Messaging.Reflection {
};
Map<Uri>(uri => uri.AbsoluteUri, uri => uri.OriginalString, safeUri);
Map<DateTime>(dt => XmlConvert.ToString(dt, XmlDateTimeSerializationMode.Utc), null, str => XmlConvert.ToDateTime(str, XmlDateTimeSerializationMode.Utc));
+ Map<TimeSpan>(ts => ts.ToString(), null, str => TimeSpan.Parse(str));
Map<byte[]>(safeFromByteArray, null, safeToByteArray);
Map<Realm>(realm => realm.ToString(), realm => realm.OriginalString, safeRealm);
Map<Identifier>(id => id.SerializedString, id => id.OriginalString, safeIdentifier);
Map<bool>(value => value.ToString().ToLowerInvariant(), null, safeBool);
Map<CultureInfo>(c => c.Name, null, str => new CultureInfo(str));
Map<CultureInfo[]>(cs => string.Join(",", cs.Select(c => c.Name).ToArray()), null, str => str.Split(',').Select(s => new CultureInfo(s)).ToArray());
+ Map<Type>(t => t.FullName, null, str => Type.GetType(str));
}
/// <summary>
@@ -163,6 +165,7 @@ namespace DotNetOpenAuth.Messaging.Reflection {
(this.field.Attributes & FieldAttributes.InitOnly) == FieldAttributes.InitOnly ||
(this.field.Attributes & constAttributes) == constAttributes)) {
this.IsConstantValue = true;
+ this.IsConstantValueAvailableStatically = this.field.IsStatic;
} else if (this.property != null && !this.property.CanWrite) {
this.IsConstantValue = true;
}
@@ -198,6 +201,28 @@ namespace DotNetOpenAuth.Messaging.Reflection {
internal bool IsConstantValue { get; set; }
/// <summary>
+ /// Gets or sets a value indicating whether this part is defined as a constant field and can be read without a message instance.
+ /// </summary>
+ internal bool IsConstantValueAvailableStatically { get; set; }
+
+ /// <summary>
+ /// Gets the static constant value for this message part without a message instance.
+ /// </summary>
+ internal string StaticConstantValue {
+ get {
+ Contract.Requires<InvalidOperationException>(this.IsConstantValueAvailableStatically);
+ return this.ToString(this.field.GetValue(null), false);
+ }
+ }
+
+ /// <summary>
+ /// Gets the type of the declared member.
+ /// </summary>
+ internal Type MemberDeclaredType {
+ get { return this.memberDeclaredType; }
+ }
+
+ /// <summary>
/// Sets the member of a given message to some given value.
/// Used in deserialization.
/// </summary>
@@ -220,11 +245,7 @@ namespace DotNetOpenAuth.Messaging.Reflection {
value));
}
} else {
- if (this.property != null) {
- this.property.SetValue(message, this.ToValue(value), null);
- } else {
- this.field.SetValue(message, this.ToValue(value));
- }
+ this.SetValueAsObject(message, this.ToValue(value));
}
} catch (Exception ex) {
throw ErrorUtilities.Wrap(ex, MessagingStrings.MessagePartReadFailure, message.GetType(), this.Name, value);
@@ -297,8 +318,8 @@ namespace DotNetOpenAuth.Messaging.Reflection {
/// <param name="toValue">The function to convert a string to the custom type.</param>
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentNullException>(System.Boolean,System.String,System.String)", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "toString", Justification = "Code contracts"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "toValue", Justification = "Code contracts")]
private static void Map<T>(Func<T, string> toString, Func<T, string> toOriginalString, Func<string, T> toValue) {
- Contract.Requires<ArgumentNullException>(toString != null, "toString");
- Contract.Requires<ArgumentNullException>(toValue != null, "toValue");
+ Contract.Requires<ArgumentNullException>(toString != null);
+ Contract.Requires<ArgumentNullException>(toValue != null);
if (toOriginalString == null) {
toOriginalString = toString;
@@ -338,13 +359,43 @@ namespace DotNetOpenAuth.Messaging.Reflection {
IMessagePartEncoder encoder;
if (!encoders.TryGetValue(messagePartEncoder, out encoder)) {
- encoder = encoders[messagePartEncoder] = (IMessagePartEncoder)Activator.CreateInstance(messagePartEncoder);
+ try {
+ encoder = encoders[messagePartEncoder] = (IMessagePartEncoder)Activator.CreateInstance(messagePartEncoder);
+ } catch (MissingMethodException ex) {
+ throw ErrorUtilities.Wrap(ex, MessagingStrings.EncoderInstantiationFailed, messagePartEncoder.FullName);
+ }
}
return encoder;
}
/// <summary>
+ /// Gets the value of the message part, without converting it to/from a string.
+ /// </summary>
+ /// <param name="message">The message instance to read from.</param>
+ /// <returns>The value of the member.</returns>
+ private object GetValueAsObject(IMessage message) {
+ if (this.property != null) {
+ return this.property.GetValue(message, null);
+ } else {
+ return this.field.GetValue(message);
+ }
+ }
+
+ /// <summary>
+ /// Sets the value of a message part directly with a given value.
+ /// </summary>
+ /// <param name="message">The message instance to read from.</param>
+ /// <param name="value">The value to set on the this part.</param>
+ private void SetValueAsObject(IMessage message, object value) {
+ if (this.property != null) {
+ this.property.SetValue(message, value, null);
+ } else {
+ this.field.SetValue(message, value);
+ }
+ }
+
+ /// <summary>
/// Converts a string representation of the member's value to the appropriate type.
/// </summary>
/// <param name="value">The string representation of the member's value.</param>
@@ -368,19 +419,6 @@ namespace DotNetOpenAuth.Messaging.Reflection {
}
/// <summary>
- /// Gets the value of the message part, without converting it to/from a string.
- /// </summary>
- /// <param name="message">The message instance to read from.</param>
- /// <returns>The value of the member.</returns>
- private object GetValueAsObject(IMessage message) {
- if (this.property != null) {
- return this.property.GetValue(message, null);
- } else {
- return this.field.GetValue(message);
- }
- }
-
- /// <summary>
/// Validates that the message part and its attribute have agreeable settings.
/// </summary>
/// <exception cref="ArgumentException">
diff --git a/src/DotNetOpenAuth/Messaging/StandardMessageFactory.cs b/src/DotNetOpenAuth/Messaging/StandardMessageFactory.cs
new file mode 100644
index 0000000..b28ce74
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/StandardMessageFactory.cs
@@ -0,0 +1,298 @@
+//-----------------------------------------------------------------------
+// <copyright file="StandardMessageFactory.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Reflection;
+ using System.Text;
+ using DotNetOpenAuth.Messaging.Reflection;
+
+ /// <summary>
+ /// A message factory that automatically selects the message type based on the incoming data.
+ /// </summary>
+ internal class StandardMessageFactory : IMessageFactory {
+ /// <summary>
+ /// The request message types and their constructors to use for instantiating the messages.
+ /// </summary>
+ private readonly Dictionary<MessageDescription, ConstructorInfo> requestMessageTypes = new Dictionary<MessageDescription, ConstructorInfo>();
+
+ /// <summary>
+ /// The response message types and their constructors to use for instantiating the messages.
+ /// </summary>
+ /// <value>
+ /// The value is a dictionary, whose key is the type of the constructor's lone parameter.
+ /// </value>
+ private readonly Dictionary<MessageDescription, Dictionary<Type, ConstructorInfo>> responseMessageTypes = new Dictionary<MessageDescription, Dictionary<Type, ConstructorInfo>>();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StandardMessageFactory"/> class.
+ /// </summary>
+ internal StandardMessageFactory() {
+ }
+
+ /// <summary>
+ /// Adds message types to the set that this factory can create.
+ /// </summary>
+ /// <param name="messageTypes">The message types that this factory may instantiate.</param>
+ public virtual void AddMessageTypes(IEnumerable<MessageDescription> messageTypes) {
+ Contract.Requires<ArgumentNullException>(messageTypes != null);
+ Contract.Requires<ArgumentException>(messageTypes.All(msg => msg != null));
+
+ var unsupportedMessageTypes = new List<MessageDescription>(0);
+ foreach (MessageDescription messageDescription in messageTypes) {
+ bool supportedMessageType = false;
+
+ // First see whether this message fits the recognized pattern for request messages.
+ if (typeof(IDirectedProtocolMessage).IsAssignableFrom(messageDescription.MessageType)) {
+ foreach (ConstructorInfo ctor in messageDescription.Constructors) {
+ ParameterInfo[] parameters = ctor.GetParameters();
+ if (parameters.Length == 2 && parameters[0].ParameterType == typeof(Uri) && parameters[1].ParameterType == typeof(Version)) {
+ supportedMessageType = true;
+ this.requestMessageTypes.Add(messageDescription, ctor);
+ break;
+ }
+ }
+ }
+
+ // Also see if this message fits the recognized pattern for response messages.
+ if (typeof(IDirectResponseProtocolMessage).IsAssignableFrom(messageDescription.MessageType)) {
+ var responseCtors = new Dictionary<Type, ConstructorInfo>(messageDescription.Constructors.Length);
+ foreach (ConstructorInfo ctor in messageDescription.Constructors) {
+ ParameterInfo[] parameters = ctor.GetParameters();
+ if (parameters.Length == 1 && typeof(IDirectedProtocolMessage).IsAssignableFrom(parameters[0].ParameterType)) {
+ responseCtors.Add(parameters[0].ParameterType, ctor);
+ }
+ }
+
+ if (responseCtors.Count > 0) {
+ supportedMessageType = true;
+ this.responseMessageTypes.Add(messageDescription, responseCtors);
+ }
+ }
+
+ if (!supportedMessageType) {
+ unsupportedMessageTypes.Add(messageDescription);
+ }
+ }
+
+ ErrorUtilities.VerifySupported(
+ !unsupportedMessageTypes.Any(),
+ MessagingStrings.StandardMessageFactoryUnsupportedMessageType,
+ unsupportedMessageTypes.ToStringDeferred());
+ }
+
+ #region IMessageFactory Members
+
+ /// <summary>
+ /// Analyzes an incoming request message payload to discover what kind of
+ /// message is embedded in it and returns the type, or null if no match is found.
+ /// </summary>
+ /// <param name="recipient">The intended or actual recipient of the request message.</param>
+ /// <param name="fields">The name/value pairs that make up the message payload.</param>
+ /// <returns>
+ /// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can
+ /// deserialize to. Null if the request isn't recognized as a valid protocol message.
+ /// </returns>
+ public virtual IDirectedProtocolMessage GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary<string, string> fields) {
+ MessageDescription matchingType = this.GetMessageDescription(recipient, fields);
+ if (matchingType != null) {
+ return this.InstantiateAsRequest(matchingType, recipient);
+ } else {
+ return null;
+ }
+ }
+
+ /// <summary>
+ /// Analyzes an incoming request message payload to discover what kind of
+ /// message is embedded in it and returns the type, or null if no match is found.
+ /// </summary>
+ /// <param name="request">The message that was sent as a request that resulted in the response.</param>
+ /// <param name="fields">The name/value pairs that make up the message payload.</param>
+ /// <returns>
+ /// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can
+ /// deserialize to. Null if the request isn't recognized as a valid protocol message.
+ /// </returns>
+ public virtual IDirectResponseProtocolMessage GetNewResponseMessage(IDirectedProtocolMessage request, IDictionary<string, string> fields) {
+ MessageDescription matchingType = this.GetMessageDescription(request, fields);
+ if (matchingType != null) {
+ return this.InstantiateAsResponse(matchingType, request);
+ } else {
+ return null;
+ }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets the message type that best fits the given incoming request data.
+ /// </summary>
+ /// <param name="recipient">The recipient of the incoming data. Typically not used, but included just in case.</param>
+ /// <param name="fields">The data of the incoming message.</param>
+ /// <returns>
+ /// The message type that matches the incoming data; or <c>null</c> if no match.
+ /// </returns>
+ /// <exception cref="ProtocolException">May be thrown if the incoming data is ambiguous.</exception>
+ protected virtual MessageDescription GetMessageDescription(MessageReceivingEndpoint recipient, IDictionary<string, string> fields) {
+ Contract.Requires<ArgumentNullException>(recipient != null);
+ Contract.Requires<ArgumentNullException>(fields != null);
+
+ var matches = this.requestMessageTypes.Keys
+ .Where(message => message.CheckMessagePartsPassBasicValidation(fields))
+ .OrderByDescending(message => CountInCommon(message.Mapping.Keys, fields.Keys))
+ .ThenByDescending(message => message.Mapping.Count)
+ .CacheGeneratedResults();
+ var match = matches.FirstOrDefault();
+ if (match != null) {
+ if (Logger.Messaging.IsWarnEnabled && matches.Count() > 1) {
+ Logger.Messaging.WarnFormat(
+ "Multiple message types seemed to fit the incoming data: {0}",
+ matches.ToStringDeferred());
+ }
+
+ return match;
+ } else {
+ // No message type matches the incoming data.
+ return null;
+ }
+ }
+
+ /// <summary>
+ /// Gets the message type that best fits the given incoming direct response data.
+ /// </summary>
+ /// <param name="request">The request message that prompted the response data.</param>
+ /// <param name="fields">The data of the incoming message.</param>
+ /// <returns>
+ /// The message type that matches the incoming data; or <c>null</c> if no match.
+ /// </returns>
+ /// <exception cref="ProtocolException">May be thrown if the incoming data is ambiguous.</exception>
+ protected virtual MessageDescription GetMessageDescription(IDirectedProtocolMessage request, IDictionary<string, string> fields) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<ArgumentNullException>(fields != null);
+
+ var matches = (from responseMessageType in this.responseMessageTypes
+ let message = responseMessageType.Key
+ where message.CheckMessagePartsPassBasicValidation(fields)
+ let ctors = this.FindMatchingResponseConstructors(message, request.GetType())
+ where ctors.Any()
+ orderby GetDerivationDistance(ctors.First().GetParameters()[0].ParameterType, request.GetType()),
+ CountInCommon(message.Mapping.Keys, fields.Keys) descending,
+ message.Mapping.Count descending
+ select message).CacheGeneratedResults();
+ var match = matches.FirstOrDefault();
+ if (match != null) {
+ if (Logger.Messaging.IsWarnEnabled && matches.Count() > 1) {
+ Logger.Messaging.WarnFormat(
+ "Multiple message types seemed to fit the incoming data: {0}",
+ matches.ToStringDeferred());
+ }
+
+ return match;
+ } else {
+ // No message type matches the incoming data.
+ return null;
+ }
+ }
+
+ /// <summary>
+ /// Instantiates the given request message type.
+ /// </summary>
+ /// <param name="messageDescription">The message description.</param>
+ /// <param name="recipient">The recipient.</param>
+ /// <returns>The instantiated message. Never null.</returns>
+ protected virtual IDirectedProtocolMessage InstantiateAsRequest(MessageDescription messageDescription, MessageReceivingEndpoint recipient) {
+ Contract.Requires<ArgumentNullException>(messageDescription != null);
+ Contract.Requires<ArgumentNullException>(recipient != null);
+ Contract.Ensures(Contract.Result<IDirectedProtocolMessage>() != null);
+
+ ConstructorInfo ctor = this.requestMessageTypes[messageDescription];
+ return (IDirectedProtocolMessage)ctor.Invoke(new object[] { recipient.Location, messageDescription.MessageVersion });
+ }
+
+ /// <summary>
+ /// Instantiates the given request message type.
+ /// </summary>
+ /// <param name="messageDescription">The message description.</param>
+ /// <param name="request">The request that resulted in this response.</param>
+ /// <returns>The instantiated message. Never null.</returns>
+ protected virtual IDirectResponseProtocolMessage InstantiateAsResponse(MessageDescription messageDescription, IDirectedProtocolMessage request) {
+ Contract.Requires<ArgumentNullException>(messageDescription != null);
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Ensures(Contract.Result<IDirectResponseProtocolMessage>() != null);
+
+ Type requestType = request.GetType();
+ var ctors = this.FindMatchingResponseConstructors(messageDescription, requestType);
+ ConstructorInfo ctor = null;
+ try {
+ ctor = ctors.Single();
+ } catch (InvalidOperationException) {
+ if (ctors.Any()) {
+ ErrorUtilities.ThrowInternal("More than one matching constructor for request type " + requestType.Name + " and response type " + messageDescription.MessageType.Name);
+ } else {
+ ErrorUtilities.ThrowInternal("Unexpected request message type " + requestType.FullName + " for response type " + messageDescription.MessageType.Name);
+ }
+ }
+ return (IDirectResponseProtocolMessage)ctor.Invoke(new object[] { request });
+ }
+
+ /// <summary>
+ /// Gets the hierarchical distance between a type and a type it derives from or implements.
+ /// </summary>
+ /// <param name="assignableType">The base type or interface.</param>
+ /// <param name="derivedType">The concrete class that implements the <paramref name="assignableType"/>.</param>
+ /// <returns>The distance between the two types. 0 if the types are equivalent, 1 if the type immediately derives from or implements the base type, or progressively higher integers.</returns>
+ private static int GetDerivationDistance(Type assignableType, Type derivedType) {
+ Contract.Requires<ArgumentNullException>(assignableType != null);
+ Contract.Requires<ArgumentNullException>(derivedType != null);
+ Contract.Requires<ArgumentException>(assignableType.IsAssignableFrom(derivedType));
+
+ // If this is the two types are equivalent...
+ if (derivedType.IsAssignableFrom(assignableType))
+ {
+ return 0;
+ }
+
+ int steps;
+ derivedType = derivedType.BaseType;
+ for (steps = 1; assignableType.IsAssignableFrom(derivedType); steps++)
+ {
+ derivedType = derivedType.BaseType;
+ }
+
+ return steps;
+ }
+
+ /// <summary>
+ /// Counts how many strings are in the intersection of two collections.
+ /// </summary>
+ /// <param name="collection1">The first collection.</param>
+ /// <param name="collection2">The second collection.</param>
+ /// <param name="comparison">The string comparison method to use.</param>
+ /// <returns>A non-negative integer no greater than the count of elements in the smallest collection.</returns>
+ private static int CountInCommon(ICollection<string> collection1, ICollection<string> collection2, StringComparison comparison = StringComparison.Ordinal) {
+ Contract.Requires<ArgumentNullException>(collection1 != null);
+ Contract.Requires<ArgumentNullException>(collection2 != null);
+ Contract.Ensures(Contract.Result<int>() >= 0 && Contract.Result<int>() <= Math.Min(collection1.Count, collection2.Count));
+
+ return collection1.Count(value1 => collection2.Any(value2 => string.Equals(value1, value2, comparison)));
+ }
+
+ /// <summary>
+ /// Finds constructors for response messages that take a given request message type.
+ /// </summary>
+ /// <param name="messageDescription">The message description.</param>
+ /// <param name="requestType">Type of the request message.</param>
+ /// <returns>A sequence of matching constructors.</returns>
+ private IEnumerable<ConstructorInfo> FindMatchingResponseConstructors(MessageDescription messageDescription, Type requestType) {
+ Contract.Requires<ArgumentNullException>(messageDescription != null);
+ Contract.Requires<ArgumentNullException>(requestType != null);
+
+ return this.responseMessageTypes[messageDescription].Where(pair => pair.Key.IsAssignableFrom(requestType)).Select(pair => pair.Value);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/StandardMessageFactoryChannel.cs b/src/DotNetOpenAuth/Messaging/StandardMessageFactoryChannel.cs
new file mode 100644
index 0000000..1fc3608
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/StandardMessageFactoryChannel.cs
@@ -0,0 +1,111 @@
+//-----------------------------------------------------------------------
+// <copyright file="StandardMessageFactoryChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using Reflection;
+
+ /// <summary>
+ /// A channel that uses the standard message factory.
+ /// </summary>
+ public abstract class StandardMessageFactoryChannel : Channel {
+ /// <summary>
+ /// The message types receivable by this channel.
+ /// </summary>
+ private readonly ICollection<Type> messageTypes;
+
+ /// <summary>
+ /// The protocol versions supported by this channel.
+ /// </summary>
+ private readonly ICollection<Version> versions;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StandardMessageFactoryChannel"/> class.
+ /// </summary>
+ /// <param name="messageTypes">The message types that might be encountered.</param>
+ /// <param name="versions">All the possible message versions that might be encountered.</param>
+ /// <param name="bindingElements">The binding elements to apply to the channel.</param>
+ protected StandardMessageFactoryChannel(ICollection<Type> messageTypes, ICollection<Version> versions, params IChannelBindingElement[] bindingElements)
+ : base(new StandardMessageFactory(), bindingElements) {
+ Contract.Requires<ArgumentNullException>(messageTypes != null);
+ Contract.Requires<ArgumentNullException>(versions != null);
+
+ this.messageTypes = messageTypes;
+ this.versions = versions;
+ this.StandardMessageFactory.AddMessageTypes(GetMessageDescriptions(this.messageTypes, this.versions, this.MessageDescriptions));
+ }
+
+ /// <summary>
+ /// Gets or sets a tool that can figure out what kind of message is being received
+ /// so it can be deserialized.
+ /// </summary>
+ internal StandardMessageFactory StandardMessageFactory {
+ get { return (Messaging.StandardMessageFactory)this.MessageFactory; }
+ set { this.MessageFactory = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the message descriptions.
+ /// </summary>
+ internal sealed override MessageDescriptionCollection MessageDescriptions {
+ get {
+ return base.MessageDescriptions;
+ }
+
+ set {
+ base.MessageDescriptions = value;
+
+ // We must reinitialize the message factory so it can use the new message descriptions.
+ var factory = new StandardMessageFactory();
+ factory.AddMessageTypes(GetMessageDescriptions(this.messageTypes, this.versions, value));
+ this.MessageFactory = factory;
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets a tool that can figure out what kind of message is being received
+ /// so it can be deserialized.
+ /// </summary>
+ protected sealed override IMessageFactory MessageFactory {
+ get {
+ return (StandardMessageFactory)base.MessageFactory;
+ }
+
+ set {
+ StandardMessageFactory newValue = (StandardMessageFactory)value;
+ base.MessageFactory = newValue;
+ }
+ }
+
+ /// <summary>
+ /// Generates all the message descriptions for a given set of message types and versions.
+ /// </summary>
+ /// <param name="messageTypes">The message types.</param>
+ /// <param name="versions">The message versions.</param>
+ /// <param name="descriptionsCache">The cache to use when obtaining the message descriptions.</param>
+ /// <returns>The generated/retrieved message descriptions.</returns>
+ private static IEnumerable<MessageDescription> GetMessageDescriptions(ICollection<Type> messageTypes, ICollection<Version> versions, MessageDescriptionCollection descriptionsCache)
+ {
+ Contract.Requires<ArgumentNullException>(messageTypes != null);
+ Contract.Requires<ArgumentNullException>(descriptionsCache != null);
+ Contract.Ensures(Contract.Result<IEnumerable<MessageDescription>>() != null);
+
+ // Get all the MessageDescription objects through the standard cache,
+ // so that perhaps it will be a quick lookup, or at least it will be
+ // stored there for a quick lookup later.
+ var messageDescriptions = new List<MessageDescription>(messageTypes.Count * versions.Count);
+ messageDescriptions.AddRange(from version in versions
+ from messageType in messageTypes
+ select descriptionsCache.Get(messageType, version));
+
+ return messageDescriptions;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/StandardWebRequestHandler.cs b/src/DotNetOpenAuth/Messaging/StandardWebRequestHandler.cs
index 48cc6e6..a5725cd 100644
--- a/src/DotNetOpenAuth/Messaging/StandardWebRequestHandler.cs
+++ b/src/DotNetOpenAuth/Messaging/StandardWebRequestHandler.cs
@@ -6,6 +6,7 @@
namespace DotNetOpenAuth.Messaging {
using System;
+ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Net;
@@ -229,6 +230,14 @@ namespace DotNetOpenAuth.Messaging {
// Be careful to not try to change the HTTP headers that have already gone out.
if (preparingPost || request.Method == "GET") {
+ // Set/override a few properties of the request to apply our policies for requests.
+ if (Debugger.IsAttached) {
+ // Since a debugger is attached, requests may be MUCH slower,
+ // so give ourselves huge timeouts.
+ request.ReadWriteTimeout = (int)TimeSpan.FromHours(1).TotalMilliseconds;
+ request.Timeout = (int)TimeSpan.FromHours(1).TotalMilliseconds;
+ }
+
// Some sites, such as Technorati, return 403 Forbidden on identity
// pages unless a User-Agent header is included.
if (string.IsNullOrEmpty(request.UserAgent)) {
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/TimespanSecondsEncoder.cs b/src/DotNetOpenAuth/Messaging/TimespanSecondsEncoder.cs
index cc3f7cc..b28e5a8 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/TimespanSecondsEncoder.cs
+++ b/src/DotNetOpenAuth/Messaging/TimespanSecondsEncoder.cs
@@ -4,7 +4,7 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy {
+namespace DotNetOpenAuth.Messaging {
using System;
using System.Globalization;
using DotNetOpenAuth.Messaging.Reflection;
@@ -13,6 +13,13 @@ namespace DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy {
/// Encodes and decodes the <see cref="TimeSpan"/> as an integer of total seconds.
/// </summary>
internal class TimespanSecondsEncoder : IMessagePartEncoder {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TimespanSecondsEncoder"/> class.
+ /// </summary>
+ public TimespanSecondsEncoder() {
+ // Note that this constructor is public so it can be instantiated via Activator.
+ }
+
#region IMessagePartEncoder Members
/// <summary>
diff --git a/src/DotNetOpenAuth/Messaging/TimestampEncoder.cs b/src/DotNetOpenAuth/Messaging/TimestampEncoder.cs
new file mode 100644
index 0000000..b83a426
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/TimestampEncoder.cs
@@ -0,0 +1,61 @@
+//-----------------------------------------------------------------------
+// <copyright file="TimestampEncoder.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Globalization;
+ using DotNetOpenAuth.Messaging.Reflection;
+
+ /// <summary>
+ /// Translates between a <see cref="DateTime"/> and the number of seconds between it and 1/1/1970 12 AM
+ /// </summary>
+ internal class TimestampEncoder : IMessagePartEncoder {
+ /// <summary>
+ /// The reference date and time for calculating time stamps.
+ /// </summary>
+ internal static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="TimestampEncoder"/> class.
+ /// </summary>
+ public TimestampEncoder() {
+ }
+
+ /// <summary>
+ /// Encodes the specified value.
+ /// </summary>
+ /// <param name="value">The value. Guaranteed to never be null.</param>
+ /// <returns>
+ /// The <paramref name="value"/> in string form, ready for message transport.
+ /// </returns>
+ public string Encode(object value) {
+ if (value == null) {
+ return null;
+ }
+
+ var timestamp = (DateTime)value;
+ TimeSpan secondsSinceEpoch = timestamp - Epoch;
+ return ((int)secondsSinceEpoch.TotalSeconds).ToString(CultureInfo.InvariantCulture);
+ }
+
+ /// <summary>
+ /// Decodes the specified value.
+ /// </summary>
+ /// <param name="value">The string value carried by the transport. Guaranteed to never be null, although it may be empty.</param>
+ /// <returns>
+ /// The deserialized form of the given string.
+ /// </returns>
+ /// <exception cref="FormatException">Thrown when the string value given cannot be decoded into the required object type.</exception>
+ public object Decode(string value) {
+ if (value == null) {
+ return null;
+ }
+
+ var secondsSinceEpoch = int.Parse(value, CultureInfo.InvariantCulture);
+ return Epoch.AddSeconds(secondsSinceEpoch);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/UriStyleMessageFormatter.cs b/src/DotNetOpenAuth/Messaging/UriStyleMessageFormatter.cs
new file mode 100644
index 0000000..9bffc3d
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/UriStyleMessageFormatter.cs
@@ -0,0 +1,77 @@
+//-----------------------------------------------------------------------
+// <copyright file="UriStyleMessageFormatter.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Messaging {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using System.Web;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.Messaging.Reflection;
+
+ /// <summary>
+ /// A serializer for <see cref="DataBag"/>-derived types
+ /// </summary>
+ /// <typeparam name="T">The DataBag-derived type that is to be serialized/deserialized.</typeparam>
+ internal class UriStyleMessageFormatter<T> : DataBagFormatterBase<T> where T : DataBag, new() {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UriStyleMessageFormatter&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="signingKey">The crypto service provider with the asymmetric key to use for signing or verifying the token.</param>
+ /// <param name="encryptingKey">The crypto service provider with the asymmetric key to use for encrypting or decrypting the token.</param>
+ /// <param name="compressed">A value indicating whether the data in this instance will be GZip'd.</param>
+ /// <param name="maximumAge">The maximum age of a token that can be decoded; useful only when <paramref name="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ protected internal UriStyleMessageFormatter(RSACryptoServiceProvider signingKey = null, RSACryptoServiceProvider encryptingKey = null, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : base(signingKey, encryptingKey, compressed, maximumAge, decodeOnceOnly) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UriStyleMessageFormatter&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store used when signing or encrypting.</param>
+ /// <param name="bucket">The bucket in which symmetric keys are stored for signing/encrypting data.</param>
+ /// <param name="signed">A value indicating whether the data in this instance will be protected against tampering.</param>
+ /// <param name="encrypted">A value indicating whether the data in this instance will be protected against eavesdropping.</param>
+ /// <param name="compressed">A value indicating whether the data in this instance will be GZip'd.</param>
+ /// <param name="minimumAge">The minimum age.</param>
+ /// <param name="maximumAge">The maximum age of a token that can be decoded; useful only when <paramref name="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ protected internal UriStyleMessageFormatter(ICryptoKeyStore cryptoKeyStore = null, string bucket = null, bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? minimumAge = null, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : base(cryptoKeyStore, bucket, signed, encrypted, compressed, minimumAge, maximumAge, decodeOnceOnly) {
+ Contract.Requires<ArgumentException>((cryptoKeyStore != null && !String.IsNullOrEmpty(bucket)) || (!signed && !encrypted));
+ }
+
+ /// <summary>
+ /// Serializes the <see cref="DataBag"/> instance to a buffer.
+ /// </summary>
+ /// <param name="message">The message.</param>
+ /// <returns>The buffer containing the serialized data.</returns>
+ protected override byte[] SerializeCore(T message) {
+ var fields = MessageSerializer.Get(message.GetType()).Serialize(MessageDescriptions.GetAccessor(message));
+ string value = MessagingUtilities.CreateQueryString(fields);
+ return Encoding.UTF8.GetBytes(value);
+ }
+
+ /// <summary>
+ /// Deserializes the <see cref="DataBag"/> instance from a buffer.
+ /// </summary>
+ /// <param name="message">The message instance to initialize with data from the buffer.</param>
+ /// <param name="data">The data buffer.</param>
+ protected override void DeserializeCore(T message, byte[] data) {
+ string value = Encoding.UTF8.GetString(data);
+
+ // Deserialize into message newly created instance.
+ var serializer = MessageSerializer.Get(message.GetType());
+ var fields = MessageDescriptions.GetAccessor(message);
+ serializer.Deserialize(HttpUtility.ParseQueryString(value).ToDictionary(), fields);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs
index 2b1bea5..76b5149 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs
+++ b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs
@@ -42,7 +42,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
securitySettings,
new OAuthConsumerMessageFactory()) {
Contract.Requires<ArgumentNullException>(tokenManager != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null, "securitySettings");
+ Contract.Requires<ArgumentNullException>(securitySettings != null);
Contract.Requires<ArgumentNullException>(signingBindingElement != null);
Contract.Requires<ArgumentException>(signingBindingElement.SignatureCallback == null, OAuthStrings.SigningElementAlreadyAssociatedWithChannel);
}
@@ -63,7 +63,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
securitySettings,
new OAuthServiceProviderMessageFactory(tokenManager)) {
Contract.Requires<ArgumentNullException>(tokenManager != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null, "securitySettings");
+ Contract.Requires<ArgumentNullException>(securitySettings != null);
Contract.Requires<ArgumentNullException>(signingBindingElement != null);
Contract.Requires<ArgumentException>(signingBindingElement.SignatureCallback == null, OAuthStrings.SigningElementAlreadyAssociatedWithChannel);
}
@@ -82,7 +82,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
internal OAuthChannel(ITamperProtectionChannelBindingElement signingBindingElement, INonceStore store, ITokenManager tokenManager, SecuritySettings securitySettings, IMessageFactory messageTypeProvider)
: base(messageTypeProvider, InitializeBindingElements(signingBindingElement, store, tokenManager, securitySettings)) {
Contract.Requires<ArgumentNullException>(tokenManager != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null, "securitySettings");
+ Contract.Requires<ArgumentNullException>(securitySettings != null);
Contract.Requires<ArgumentNullException>(signingBindingElement != null);
Contract.Requires<ArgumentException>(signingBindingElement.SignatureCallback == null, OAuthStrings.SigningElementAlreadyAssociatedWithChannel);
@@ -132,36 +132,14 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <param name="request">The HTTP request to search.</param>
/// <returns>The deserialized message, if one is found. Null otherwise.</returns>
protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) {
- var fields = new Dictionary<string, string>();
-
// First search the Authorization header.
string authorization = request.Headers[HttpRequestHeader.Authorization];
- if (authorization != null) {
- string[] authorizationSections = authorization.Split(';'); // TODO: is this the right delimiter?
- string oauthPrefix = Protocol.AuthorizationHeaderScheme + " ";
-
- // The Authorization header may have multiple uses, and OAuth may be just one of them.
- // Go through each one looking for an OAuth one.
- foreach (string auth in authorizationSections) {
- string trimmedAuth = auth.Trim();
- if (trimmedAuth.StartsWith(oauthPrefix, StringComparison.Ordinal)) {
- // We found an Authorization: OAuth header.
- // Parse it according to the rules in section 5.4.1 of the V1.0 spec.
- foreach (string stringPair in trimmedAuth.Substring(oauthPrefix.Length).Split(',')) {
- string[] keyValueStringPair = stringPair.Trim().Split('=');
- string key = Uri.UnescapeDataString(keyValueStringPair[0]);
- string value = Uri.UnescapeDataString(keyValueStringPair[1].Trim('"'));
- fields.Add(key, value);
- }
- }
- }
-
- fields.Remove("realm"); // ignore the realm parameter, since we don't use it, and it must be omitted from signature base string.
- }
+ var fields = MessagingUtilities.ParseAuthorizationHeader(Protocol.AuthorizationHeaderScheme, authorization).ToDictionary();
+ fields.Remove("realm"); // ignore the realm parameter, since we don't use it, and it must be omitted from signature base string.
// Scrape the entity
if (!string.IsNullOrEmpty(request.Headers[HttpRequestHeader.ContentType])) {
- ContentType contentType = new ContentType(request.Headers[HttpRequestHeader.ContentType]);
+ var contentType = new ContentType(request.Headers[HttpRequestHeader.ContentType]);
if (string.Equals(contentType.MediaType, HttpFormUrlEncoded, StringComparison.Ordinal)) {
foreach (string key in request.Form) {
if (key != null) {
@@ -368,20 +346,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
httpRequest = (HttpWebRequest)WebRequest.Create(recipientBuilder.Uri);
httpRequest.Method = GetHttpMethod(requestMessage);
- StringBuilder authorization = new StringBuilder();
- authorization.Append(Protocol.AuthorizationHeaderScheme);
- authorization.Append(" ");
- foreach (var pair in fields) {
- string key = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Key);
- string value = MessagingUtilities.EscapeUriDataStringRfc3986(pair.Value);
- authorization.Append(key);
- authorization.Append("=\"");
- authorization.Append(value);
- authorization.Append("\",");
- }
- authorization.Length--; // remove trailing comma
-
- httpRequest.Headers.Add(HttpRequestHeader.Authorization, authorization.ToString());
+ httpRequest.Headers.Add(HttpRequestHeader.Authorization, MessagingUtilities.AssembleAuthorizationHeader(Protocol.AuthorizationHeaderScheme, fields));
if (hasEntity) {
// WARNING: We only set up the request stream for the caller if there is
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthPrincipal.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthPrincipal.cs
index 025ef09..82ecb0a 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthPrincipal.cs
+++ b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthPrincipal.cs
@@ -28,6 +28,15 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
/// <summary>
/// Initializes a new instance of the <see cref="OAuthPrincipal"/> class.
/// </summary>
+ /// <param name="userName">The username.</param>
+ /// <param name="roles">The roles this user belongs to.</param>
+ public OAuthPrincipal(string userName, string[] roles)
+ : this(new OAuthIdentity(userName), roles) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuthPrincipal"/> class.
+ /// </summary>
/// <param name="token">The access token.</param>
internal OAuthPrincipal(IServiceProviderAccessToken token)
: this(token.Username, token.Roles) {
@@ -47,15 +56,6 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
}
/// <summary>
- /// Initializes a new instance of the <see cref="OAuthPrincipal"/> class.
- /// </summary>
- /// <param name="username">The username.</param>
- /// <param name="roles">The roles this user belongs to.</param>
- internal OAuthPrincipal(string username, string[] roles)
- : this(new OAuthIdentity(username), roles) {
- }
-
- /// <summary>
/// Gets the access token used to create this principal.
/// </summary>
/// <value>A non-empty string.</value>
diff --git a/src/DotNetOpenAuth/OAuth/ChannelElements/TokenHandlingBindingElement.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/TokenHandlingBindingElement.cs
index bfebd8b..f53aa1b 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/TokenHandlingBindingElement.cs
+++ b/src/DotNetOpenAuth/OAuth/ChannelElements/TokenHandlingBindingElement.cs
@@ -38,7 +38,7 @@ namespace DotNetOpenAuth.OAuth.ChannelElements {
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Diagnostics.Contracts.__ContractsRuntime.Requires<System.ArgumentNullException>(System.Boolean,System.String,System.String)", Justification = "Code contract"), SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "securitySettings", Justification = "Code contracts")]
internal TokenHandlingBindingElement(IServiceProviderTokenManager tokenManager, ServiceProviderSecuritySettings securitySettings) {
Contract.Requires<ArgumentNullException>(tokenManager != null);
- Contract.Requires<ArgumentNullException>(securitySettings != null, "securitySettings");
+ Contract.Requires<ArgumentNullException>(securitySettings != null);
this.tokenManager = tokenManager;
this.securitySettings = securitySettings;
diff --git a/src/DotNetOpenAuth/OAuth/Protocol.cs b/src/DotNetOpenAuth/OAuth/Protocol.cs
index 6eecd8e..4418b5e 100644
--- a/src/DotNetOpenAuth/OAuth/Protocol.cs
+++ b/src/DotNetOpenAuth/OAuth/Protocol.cs
@@ -100,7 +100,7 @@ namespace DotNetOpenAuth.OAuth {
}
/// <summary>
- /// Gets the version used to represent OAuth 1.0a.
+ /// Gets the OAuth version this instance represents.
/// </summary>
internal Version Version { get; private set; }
diff --git a/src/DotNetOpenAuth/OAuth2/AuthorizationServer.cs b/src/DotNetOpenAuth/OAuth2/AuthorizationServer.cs
new file mode 100644
index 0000000..ad40fa5
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/AuthorizationServer.cs
@@ -0,0 +1,258 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationServer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// Authorization Server supporting the web server flow.
+ /// </summary>
+ public class AuthorizationServer {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationServer"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ public AuthorizationServer(IAuthorizationServer authorizationServer) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ this.OAuthChannel = new OAuth2AuthorizationServerChannel(authorizationServer);
+ }
+
+ /// <summary>
+ /// Gets the channel.
+ /// </summary>
+ /// <value>The channel.</value>
+ public Channel Channel {
+ get { return this.OAuthChannel; }
+ }
+
+ /// <summary>
+ /// Gets the authorization server.
+ /// </summary>
+ /// <value>The authorization server.</value>
+ public IAuthorizationServer AuthorizationServerServices {
+ get { return this.OAuthChannel.AuthorizationServer; }
+ }
+
+ /// <summary>
+ /// Gets the channel.
+ /// </summary>
+ internal OAuth2AuthorizationServerChannel OAuthChannel { get; private set; }
+
+ /// <summary>
+ /// Reads in a client's request for the Authorization Server to obtain permission from
+ /// the user to authorize the Client's access of some protected resource(s).
+ /// </summary>
+ /// <param name="request">The HTTP request to read from.</param>
+ /// <returns>The incoming request, or null if no OAuth message was attached.</returns>
+ /// <exception cref="ProtocolException">Thrown if an unexpected OAuth message is attached to the incoming request.</exception>
+ public EndUserAuthorizationRequest ReadAuthorizationRequest(HttpRequestInfo request = null) {
+ if (request == null) {
+ request = this.Channel.GetRequestFromContext();
+ }
+
+ EndUserAuthorizationRequest message;
+ if (this.Channel.TryReadFromRequest(request, out message)) {
+ if (message.ResponseType == EndUserAuthorizationResponseType.AuthorizationCode) {
+ // Clients with no secrets can only request implicit grant types.
+ var client = this.AuthorizationServerServices.GetClientOrThrow(message.ClientIdentifier);
+ ErrorUtilities.VerifyProtocol(!String.IsNullOrEmpty(client.Secret), Protocol.unauthorized_client);
+ }
+ }
+
+ return message;
+ }
+
+ /// <summary>
+ /// Approves an authorization request and sends an HTTP response to the user agent to redirect the user back to the Client.
+ /// </summary>
+ /// <param name="authorizationRequest">The authorization request to approve.</param>
+ /// <param name="userName">The username of the account that approved the request (or whose data will be accessed by the client).</param>
+ /// <param name="scopes">The scope of access the client should be granted. If <c>null</c>, all scopes in the original request will be granted.</param>
+ /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param>
+ public void ApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string userName, IEnumerable<string> scopes = null, Uri callback = null) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null);
+
+ var response = this.PrepareApproveAuthorizationRequest(authorizationRequest, userName, scopes, callback);
+ this.Channel.Respond(response);
+ }
+
+ /// <summary>
+ /// Rejects an authorization request and sends an HTTP response to the user agent to redirect the user back to the Client.
+ /// </summary>
+ /// <param name="authorizationRequest">The authorization request to disapprove.</param>
+ /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param>
+ public void RejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null);
+
+ var response = this.PrepareRejectAuthorizationRequest(authorizationRequest, callback);
+ this.Channel.Respond(response);
+ }
+
+ /// <summary>
+ /// Checks the incoming HTTP request for an access token request and prepares a response if the request message was found.
+ /// </summary>
+ /// <param name="response">The formulated response, or <c>null</c> if the request was not found..</param>
+ /// <returns>A value indicating whether any access token request was found in the HTTP request.</returns>
+ /// <remarks>
+ /// This method assumes that the authorization server and the resource server are the same and that they share a single
+ /// asymmetric key for signing and encrypting the access token. If this is not true, use the <see cref="ReadAccessTokenRequest"/> method instead.
+ /// </remarks>
+ public bool TryPrepareAccessTokenResponse(out IDirectResponseProtocolMessage response) {
+ return this.TryPrepareAccessTokenResponse(this.Channel.GetRequestFromContext(), out response);
+ }
+
+ /// <summary>
+ /// Checks the incoming HTTP request for an access token request and prepares a response if the request message was found.
+ /// </summary>
+ /// <param name="httpRequestInfo">The HTTP request info.</param>
+ /// <param name="response">The formulated response, or <c>null</c> if the request was not found..</param>
+ /// <returns>A value indicating whether any access token request was found in the HTTP request.</returns>
+ /// <remarks>
+ /// This method assumes that the authorization server and the resource server are the same and that they share a single
+ /// asymmetric key for signing and encrypting the access token. If this is not true, use the <see cref="ReadAccessTokenRequest"/> method instead.
+ /// </remarks>
+ public bool TryPrepareAccessTokenResponse(HttpRequestInfo httpRequestInfo, out IDirectResponseProtocolMessage response) {
+ Contract.Requires<ArgumentNullException>(httpRequestInfo != null);
+ Contract.Ensures(Contract.Result<bool>() == (Contract.ValueAtReturn<IDirectResponseProtocolMessage>(out response) != null));
+
+ var request = this.ReadAccessTokenRequest(httpRequestInfo);
+ if (request != null) {
+ response = this.PrepareAccessTokenResponse(request);
+ return true;
+ }
+
+ response = null;
+ return false;
+ }
+
+ /// <summary>
+ /// Reads the access token request.
+ /// </summary>
+ /// <param name="requestInfo">The request info.</param>
+ /// <returns>The Client's request for an access token; or <c>null</c> if no such message was found in the request.</returns>
+ public AccessTokenRequestBase ReadAccessTokenRequest(HttpRequestInfo requestInfo = null) {
+ if (requestInfo == null) {
+ requestInfo = this.Channel.GetRequestFromContext();
+ }
+
+ AccessTokenRequestBase request;
+ this.Channel.TryReadFromRequest(requestInfo, out request);
+ return request;
+ }
+
+ /// <summary>
+ /// Prepares a response to inform the Client that the user has rejected the Client's authorization request.
+ /// </summary>
+ /// <param name="authorizationRequest">The authorization request.</param>
+ /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param>
+ /// <returns>The authorization response message to send to the Client.</returns>
+ public EndUserAuthorizationFailedResponse PrepareRejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null);
+ Contract.Ensures(Contract.Result<EndUserAuthorizationFailedResponse>() != null);
+
+ if (callback == null) {
+ callback = this.GetCallback(authorizationRequest);
+ }
+
+ var response = new EndUserAuthorizationFailedResponse(callback, authorizationRequest);
+ return response;
+ }
+
+ /// <summary>
+ /// Approves an authorization request.
+ /// </summary>
+ /// <param name="authorizationRequest">The authorization request to approve.</param>
+ /// <param name="userName">The username of the account that approved the request (or whose data will be accessed by the client).</param>
+ /// <param name="scopes">The scope of access the client should be granted. If <c>null</c>, all scopes in the original request will be granted.</param>
+ /// <param name="callback">The Client callback URL to use when formulating the redirect to send the user agent back to the Client.</param>
+ /// <returns>The authorization response message to send to the Client.</returns>
+ public EndUserAuthorizationSuccessResponseBase PrepareApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string userName, IEnumerable<string> scopes = null, Uri callback = null) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null);
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(userName));
+ Contract.Ensures(Contract.Result<EndUserAuthorizationSuccessResponseBase>() != null);
+
+ if (callback == null) {
+ callback = this.GetCallback(authorizationRequest);
+ }
+
+ var client = this.AuthorizationServerServices.GetClientOrThrow(authorizationRequest.ClientIdentifier);
+ EndUserAuthorizationSuccessResponseBase response;
+ switch (authorizationRequest.ResponseType) {
+ case EndUserAuthorizationResponseType.AccessToken:
+ var accessTokenResponse = new EndUserAuthorizationSuccessAccessTokenResponse(callback, authorizationRequest);
+ accessTokenResponse.Lifetime = this.AuthorizationServerServices.GetAccessTokenLifetime(authorizationRequest);
+ response = accessTokenResponse;
+ break;
+ case EndUserAuthorizationResponseType.AuthorizationCode:
+ response = new EndUserAuthorizationSuccessAuthCodeResponse(callback, authorizationRequest);
+ break;
+ default:
+ throw ErrorUtilities.ThrowInternal("Unexpected response type.");
+ }
+
+ response.AuthorizingUsername = userName;
+
+ // Customize the approved scope if the authorization server has decided to do so.
+ if (scopes != null) {
+ response.Scope.ResetContents(scopes);
+ }
+
+ return response;
+ }
+
+ /// <summary>
+ /// Prepares the response to an access token request.
+ /// </summary>
+ /// <param name="request">The request for an access token.</param>
+ /// <param name="includeRefreshToken">If set to <c>true</c>, the response will include a long-lived refresh token.</param>
+ /// <returns>The response message to send to the client.</returns>
+ public virtual IDirectResponseProtocolMessage PrepareAccessTokenResponse(AccessTokenRequestBase request, bool includeRefreshToken = true) {
+ Contract.Requires<ArgumentNullException>(request != null);
+
+ var tokenRequest = (IAuthorizationCarryingRequest)request;
+ var response = new AccessTokenSuccessResponse(request) {
+ Lifetime = this.AuthorizationServerServices.GetAccessTokenLifetime(request),
+ HasRefreshToken = includeRefreshToken,
+ };
+ response.Scope.ResetContents(tokenRequest.AuthorizationDescription.Scope);
+ return response;
+ }
+
+ /// <summary>
+ /// Gets the redirect URL to use for a particular authorization request.
+ /// </summary>
+ /// <param name="authorizationRequest">The authorization request.</param>
+ /// <returns>The URL to redirect to. Never <c>null</c>.</returns>
+ /// <exception cref="ProtocolException">Thrown if no callback URL could be determined.</exception>
+ protected Uri GetCallback(EndUserAuthorizationRequest authorizationRequest) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null);
+ Contract.Ensures(Contract.Result<Uri>() != null);
+
+ var client = this.AuthorizationServerServices.GetClientOrThrow(authorizationRequest.ClientIdentifier);
+
+ // Prefer a request-specific callback to the pre-registered one (if any).
+ if (authorizationRequest.Callback != null) {
+ // The OAuth channel has already validated the callback parameter against
+ // the authorization server's whitelist for this client.
+ return authorizationRequest.Callback;
+ }
+
+ // Since the request didn't include a callback URL, look up the callback from
+ // the client's preregistration with this authorization server.
+ Uri defaultCallback = client.DefaultCallback;
+ ErrorUtilities.VerifyProtocol(defaultCallback != null, OAuthStrings.NoCallback);
+ return defaultCallback;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/AuthorizationServerDescription.cs b/src/DotNetOpenAuth/OAuth2/AuthorizationServerDescription.cs
new file mode 100644
index 0000000..bbad27c
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/AuthorizationServerDescription.cs
@@ -0,0 +1,62 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationServerDescription.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ /// <summary>
+ /// A description of an OAuth Authorization Server as seen by an OAuth Client.
+ /// </summary>
+ public class AuthorizationServerDescription {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationServerDescription"/> class.
+ /// </summary>
+ public AuthorizationServerDescription() {
+ this.ProtocolVersion = Protocol.Default.ProtocolVersion;
+ }
+
+ /// <summary>
+ /// Gets or sets the Authorization Server URL from which an Access Token is requested by the Client.
+ /// </summary>
+ /// <value>An HTTPS URL.</value>
+ /// <remarks>
+ /// <para>After obtaining authorization from the resource owner, clients request an access token from the authorization server's token endpoint.</para>
+ /// <para>The URI of the token endpoint can be found in the service documentation, or can be obtained by the client by making an unauthorized protected resource request (from the WWW-Authenticate response header token-uri (The 'authorization-uri' Attribute) attribute).</para>
+ /// <para>The token endpoint advertised by the resource server MAY include a query component as defined by [RFC3986] (Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January 2005.) section 3.</para>
+ /// <para>Since requests to the token endpoint result in the transmission of plain text credentials in the HTTP request and response, the authorization server MUST require the use of a transport-layer mechanism such as TLS/SSL (or a secure channel with equivalent protections) when sending requests to the token endpoints. </para>
+ /// </remarks>
+ public Uri TokenEndpoint { get; set; }
+
+ /// <summary>
+ /// Gets or sets the Authorization Server URL where the Client (re)directs the User
+ /// to make an authorization request.
+ /// </summary>
+ /// <value>An HTTPS URL.</value>
+ /// <remarks>
+ /// <para>Clients direct the resource owner to the authorization endpoint to approve their access request. Before granting access, the resource owner first authenticates with the authorization server. The way in which the authorization server authenticates the end-user (e.g. username and password login, OpenID, session cookies) and in which the authorization server obtains the end-user's authorization, including whether it uses a secure channel such as TLS/SSL, is beyond the scope of this specification. However, the authorization server MUST first verify the identity of the end-user.</para>
+ /// <para>The URI of the authorization endpoint can be found in the service documentation, or can be obtained by the client by making an unauthorized protected resource request (from the WWW-Authenticate response header auth-uri (The 'authorization-uri' Attribute) attribute).</para>
+ /// <para>The authorization endpoint advertised by the resource server MAY include a query component as defined by [RFC3986] (Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January 2005.) section 3.</para>
+ /// <para>Since requests to the authorization endpoint result in user authentication and the transmission of sensitive values, the authorization server SHOULD require the use of a transport-layer mechanism such as TLS/SSL (or a secure channel with equivalent protections) when sending requests to the authorization endpoints.</para>
+ /// </remarks>
+ public Uri AuthorizationEndpoint { get; set; }
+
+ /// <summary>
+ /// Gets or sets the OAuth version supported by the Authorization Server.
+ /// </summary>
+ public ProtocolVersion ProtocolVersion { get; set; }
+
+ /// <summary>
+ /// Gets the version of the OAuth protocol to use with this Authorization Server.
+ /// </summary>
+ /// <value>The version.</value>
+ internal Version Version {
+ get { return Protocol.Lookup(this.ProtocolVersion).Version; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/AuthorizationState.cs b/src/DotNetOpenAuth/OAuth2/AuthorizationState.cs
new file mode 100644
index 0000000..bfc33aa
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/AuthorizationState.cs
@@ -0,0 +1,93 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationState.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A simple in-memory copy of an authorization state.
+ /// </summary>
+ [Serializable]
+ public class AuthorizationState : IAuthorizationState {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationState"/> class.
+ /// </summary>
+ /// <param name="scopes">The scopes of access being requested or that was obtained.</param>
+ public AuthorizationState(IEnumerable<string> scopes = null) {
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ if (scopes != null) {
+ this.Scope.AddRange(scopes);
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the callback URL used to obtain authorization.
+ /// </summary>
+ /// <value>The callback URL.</value>
+ public Uri Callback { get; set; }
+
+ /// <summary>
+ /// Gets or sets the long-lived token used to renew the short-lived <see cref="AccessToken"/>.
+ /// </summary>
+ /// <value>The refresh token.</value>
+ public string RefreshToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ public string AccessToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token UTC expiration date.
+ /// </summary>
+ /// <value></value>
+ public DateTime? AccessTokenExpirationUtc { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token issue date UTC.
+ /// </summary>
+ /// <value>The access token issue date UTC.</value>
+ public DateTime? AccessTokenIssueDateUtc { get; set; }
+
+ /// <summary>
+ /// Gets the scope the token is (to be) authorized for.
+ /// </summary>
+ /// <value>The scope.</value>
+ public HashSet<string> Scope { get; private set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is deleted.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if this instance is deleted; otherwise, <c>false</c>.
+ /// </value>
+ public bool IsDeleted { get; set; }
+
+ /// <summary>
+ /// Deletes this authorization, including access token and refresh token where applicable.
+ /// </summary>
+ /// <remarks>
+ /// This method is invoked when an authorization attempt fails, is rejected, is revoked, or
+ /// expires and cannot be renewed.
+ /// </remarks>
+ public virtual void Delete() {
+ this.IsDeleted = true;
+ }
+
+ /// <summary>
+ /// Saves any changes made to this authorization object's properties.
+ /// </summary>
+ /// <remarks>
+ /// This method is invoked after DotNetOpenAuth changes any property.
+ /// </remarks>
+ public virtual void SaveChanges() {
+ }
+ }
+} \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/AccessRequestBindingElement.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AccessRequestBindingElement.cs
new file mode 100644
index 0000000..b86f5dd
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AccessRequestBindingElement.cs
@@ -0,0 +1,158 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessRequestBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Globalization;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// Decodes verification codes, refresh tokens and access tokens on incoming messages.
+ /// </summary>
+ /// <remarks>
+ /// This binding element also ensures that the code/token coming in is issued to
+ /// the same client that is sending the code/token and that the authorization has
+ /// not been revoked and that an access token has not expired.
+ /// </remarks>
+ internal class AccessRequestBindingElement : AuthServerBindingElementBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessRequestBindingElement"/> class.
+ /// </summary>
+ internal AccessRequestBindingElement() {
+ }
+
+ /// <summary>
+ /// Gets the protection commonly offered (if any) by this binding element.
+ /// </summary>
+ /// <value></value>
+ /// <remarks>
+ /// This value is used to assist in sorting binding elements in the channel stack.
+ /// </remarks>
+ public override MessageProtections Protection {
+ get { return MessageProtections.None; }
+ }
+
+ /// <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>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) {
+ var response = message as IAuthorizationCarryingRequest;
+ if (response != null) {
+ switch (response.CodeOrTokenType) {
+ case CodeOrTokenType.AuthorizationCode:
+ var codeFormatter = AuthorizationCode.CreateFormatter(this.AuthorizationServer);
+ var code = (AuthorizationCode)response.AuthorizationDescription;
+ response.CodeOrToken = codeFormatter.Serialize(code);
+ break;
+ case CodeOrTokenType.AccessToken:
+ var responseWithOriginatingRequest = (IDirectResponseProtocolMessage)message;
+ var request = (IAccessTokenRequest)responseWithOriginatingRequest.OriginatingRequest;
+
+ using (var resourceServerKey = this.AuthorizationServer.GetResourceServerEncryptionKey(request)) {
+ var tokenFormatter = AccessToken.CreateFormatter(this.AuthorizationServer.AccessTokenSigningKey, resourceServerKey);
+ var token = (AccessToken)response.AuthorizationDescription;
+ response.CodeOrToken = tokenFormatter.Serialize(token);
+ break;
+ }
+ default:
+ throw ErrorUtilities.ThrowInternal(string.Format(CultureInfo.CurrentCulture, "Unexpected outgoing code or token type: {0}", response.CodeOrTokenType));
+ }
+
+ return MessageProtections.None;
+ }
+
+ var accessTokenResponse = message as AccessTokenSuccessResponse;
+ if (accessTokenResponse != null) {
+ var directResponseMessage = (IDirectResponseProtocolMessage)accessTokenResponse;
+ var accessTokenRequest = (AccessTokenRequestBase)directResponseMessage.OriginatingRequest;
+ ErrorUtilities.VerifyProtocol(accessTokenRequest.GrantType != GrantType.ClientCredentials || accessTokenResponse.RefreshToken == null, OAuthStrings.NoGrantNoRefreshToken);
+ }
+
+ return null;
+ }
+
+ /// <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>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <exception cref="ProtocolException">
+ /// Thrown when the binding element rules indicate that this message is invalid and should
+ /// NOT be processed.
+ /// </exception>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public override MessageProtections? ProcessIncomingMessage(IProtocolMessage message) {
+ var tokenRequest = message as IAuthorizationCarryingRequest;
+ if (tokenRequest != null) {
+ try {
+ switch (tokenRequest.CodeOrTokenType) {
+ case CodeOrTokenType.AuthorizationCode:
+ var verificationCodeFormatter = AuthorizationCode.CreateFormatter(this.AuthorizationServer);
+ var verificationCode = verificationCodeFormatter.Deserialize(message, tokenRequest.CodeOrToken);
+ tokenRequest.AuthorizationDescription = verificationCode;
+ break;
+ case CodeOrTokenType.RefreshToken:
+ var refreshTokenFormatter = RefreshToken.CreateFormatter(this.AuthorizationServer.CryptoKeyStore);
+ var refreshToken = refreshTokenFormatter.Deserialize(message, tokenRequest.CodeOrToken);
+ tokenRequest.AuthorizationDescription = refreshToken;
+ break;
+ default:
+ throw ErrorUtilities.ThrowInternal("Unexpected value for CodeOrTokenType: " + tokenRequest.CodeOrTokenType);
+ }
+ } catch (ExpiredMessageException ex) {
+ throw ErrorUtilities.Wrap(ex, Protocol.authorization_expired);
+ }
+
+ var accessRequest = tokenRequest as AccessTokenRequestBase;
+ if (accessRequest != null) {
+ // Make sure the client sending us this token is the client we issued the token to.
+ ErrorUtilities.VerifyProtocol(string.Equals(accessRequest.ClientIdentifier, tokenRequest.AuthorizationDescription.ClientIdentifier, StringComparison.Ordinal), Protocol.incorrect_client_credentials);
+
+ // Check that the client secret is correct.
+ var client = this.AuthorizationServer.GetClientOrThrow(accessRequest.ClientIdentifier);
+ string secret = client.Secret;
+ ErrorUtilities.VerifyProtocol(!String.IsNullOrEmpty(secret), Protocol.unauthorized_client); // an empty secret is not allowed for client authenticated calls.
+ ErrorUtilities.VerifyProtocol(MessagingUtilities.EqualsConstantTime(secret, accessRequest.ClientSecret), Protocol.incorrect_client_credentials);
+
+ var scopedAccessRequest = accessRequest as ScopedAccessTokenRequest;
+ if (scopedAccessRequest != null) {
+ // Make sure the scope the client is requesting does not exceed the scope in the grant.
+ ErrorUtilities.VerifyProtocol(scopedAccessRequest.Scope.IsSubsetOf(tokenRequest.AuthorizationDescription.Scope), OAuthStrings.AccessScopeExceedsGrantScope, scopedAccessRequest.Scope, tokenRequest.AuthorizationDescription.Scope);
+ }
+ }
+
+ // Make sure the authorization this token represents hasn't already been revoked.
+ ErrorUtilities.VerifyProtocol(this.AuthorizationServer.IsAuthorizationValid(tokenRequest.AuthorizationDescription), Protocol.authorization_expired);
+
+ return MessageProtections.None;
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/AccessToken.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AccessToken.cs
new file mode 100644
index 0000000..6278828
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AccessToken.cs
@@ -0,0 +1,102 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessToken.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Security.Cryptography;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// A short-lived token that accompanies HTTP requests to protected data to authorize the request.
+ /// </summary>
+ internal class AccessToken : AuthorizationDataBag {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessToken"/> class.
+ /// </summary>
+ public AccessToken() {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessToken"/> class.
+ /// </summary>
+ /// <param name="authorization">The authorization to be described by the access token.</param>
+ /// <param name="lifetime">The lifetime of the access token.</param>
+ internal AccessToken(IAuthorizationDescription authorization, TimeSpan? lifetime) {
+ Contract.Requires<ArgumentNullException>(authorization != null);
+
+ this.ClientIdentifier = authorization.ClientIdentifier;
+ this.UtcCreationDate = authorization.UtcIssued;
+ this.User = authorization.User;
+ this.Scope.ResetContents(authorization.Scope);
+ this.Lifetime = lifetime;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessToken"/> class.
+ /// </summary>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <param name="scopes">The scopes.</param>
+ /// <param name="username">The username of the account that authorized this token.</param>
+ /// <param name="lifetime">The lifetime for this access token.</param>
+ internal AccessToken(string clientIdentifier, IEnumerable<string> scopes, string username, TimeSpan? lifetime) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(clientIdentifier));
+
+ this.ClientIdentifier = clientIdentifier;
+ this.Scope.ResetContents(scopes);
+ this.User = username;
+ this.Lifetime = lifetime;
+ this.UtcCreationDate = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Gets or sets the lifetime of the access token.
+ /// </summary>
+ /// <value>The lifetime.</value>
+ [MessagePart(Encoder = typeof(TimespanSecondsEncoder))]
+ internal TimeSpan? Lifetime { get; set; }
+
+ /// <summary>
+ /// Creates a formatter capable of serializing/deserializing an access token.
+ /// </summary>
+ /// <param name="signingKey">The crypto service provider with the authorization server's private key used to asymmetrically sign the access token.</param>
+ /// <param name="encryptingKey">The crypto service provider with the resource server's public key used to encrypt the access token.</param>
+ /// <returns>An access token serializer.</returns>
+ internal static IDataBagFormatter<AccessToken> CreateFormatter(RSACryptoServiceProvider signingKey, RSACryptoServiceProvider encryptingKey) {
+ Contract.Requires(signingKey != null || !signingKey.PublicOnly);
+ Contract.Requires(encryptingKey != null);
+ Contract.Ensures(Contract.Result<IDataBagFormatter<AccessToken>>() != null);
+
+ return new UriStyleMessageFormatter<AccessToken>(signingKey, encryptingKey);
+ }
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ protected override void EnsureValidMessage() {
+ base.EnsureValidMessage();
+
+ // Has this token expired?
+ if (this.Lifetime.HasValue) {
+ DateTime expirationDate = this.UtcCreationDate + this.Lifetime.Value;
+ if (expirationDate < DateTime.UtcNow) {
+ throw new ExpiredMessageException(expirationDate, this.ContainingMessage);
+ }
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/AccessTokenBindingElement.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AccessTokenBindingElement.cs
new file mode 100644
index 0000000..3a709b6
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AccessTokenBindingElement.cs
@@ -0,0 +1,93 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// Serializes access tokens inside an outgoing message.
+ /// </summary>
+ internal class AccessTokenBindingElement : AuthServerBindingElementBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenBindingElement"/> class.
+ /// </summary>
+ internal AccessTokenBindingElement() {
+ }
+
+ /// <summary>
+ /// Gets the protection commonly offered (if any) by this binding element.
+ /// </summary>
+ /// <value>Always <c>MessageProtections.None</c></value>
+ /// <remarks>
+ /// This value is used to assist in sorting binding elements in the channel stack.
+ /// </remarks>
+ public override MessageProtections Protection {
+ get { return MessageProtections.None; }
+ }
+
+ /// <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>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) {
+ var directResponse = message as IDirectResponseProtocolMessage;
+ IAccessTokenRequest request = directResponse != null ? directResponse.OriginatingRequest as IAccessTokenRequest : null;
+
+ var implicitGrantResponse = message as EndUserAuthorizationSuccessAccessTokenResponse;
+ if (implicitGrantResponse != null) {
+ IAuthorizationCarryingRequest tokenCarryingResponse = implicitGrantResponse;
+ tokenCarryingResponse.AuthorizationDescription = new AccessToken(request.ClientIdentifier, implicitGrantResponse.Scope, implicitGrantResponse.AuthorizingUsername, implicitGrantResponse.Lifetime);
+
+ return MessageProtections.None;
+ }
+
+ var accessTokenResponse = message as AccessTokenSuccessResponse;
+ if (accessTokenResponse != null) {
+ var authCarryingRequest = (IAuthorizationCarryingRequest)request;
+ var accessToken = new AccessToken(authCarryingRequest.AuthorizationDescription, accessTokenResponse.Lifetime);
+ using (var resourceServerEncryptionKey = this.AuthorizationServer.GetResourceServerEncryptionKey(request)) {
+ var accessTokenFormatter = AccessToken.CreateFormatter(this.AuthorizationServer.AccessTokenSigningKey, resourceServerEncryptionKey);
+ accessTokenResponse.AccessToken = accessTokenFormatter.Serialize(accessToken);
+ }
+
+ if (accessTokenResponse.HasRefreshToken) {
+ var refreshToken = new RefreshToken(authCarryingRequest.AuthorizationDescription);
+ var refreshTokenFormatter = RefreshToken.CreateFormatter(this.AuthorizationServer.CryptoKeyStore);
+ accessTokenResponse.RefreshToken = refreshTokenFormatter.Serialize(refreshToken);
+ }
+ }
+
+ return null;
+ }
+
+ /// <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>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <exception cref="ProtocolException">
+ /// Thrown when the binding element rules indicate that this message is invalid and should
+ /// NOT be processed.
+ /// </exception>
+ public override MessageProtections? ProcessIncomingMessage(IProtocolMessage message) {
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthServerAllFlowsBindingElement.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthServerAllFlowsBindingElement.cs
new file mode 100644
index 0000000..bc464e2
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthServerAllFlowsBindingElement.cs
@@ -0,0 +1,83 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthServerAllFlowsBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.OAuth2.Messages;
+ using Messaging;
+
+ /// <summary>
+ /// A binding element that should be applied for authorization server channels regardless of which flows
+ /// are supported.
+ /// </summary>
+ internal class AuthServerAllFlowsBindingElement : AuthServerBindingElementBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthServerAllFlowsBindingElement"/> class.
+ /// </summary>
+ internal AuthServerAllFlowsBindingElement() {
+ }
+
+ /// <summary>
+ /// Gets the protection commonly offered (if any) by this binding element.
+ /// </summary>
+ /// <remarks>
+ /// This value is used to assist in sorting binding elements in the channel stack.
+ /// </remarks>
+ public override MessageProtections Protection {
+ get { return MessageProtections.None; }
+ }
+
+ /// <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>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) {
+ return null;
+ }
+
+ /// <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>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <exception cref="ProtocolException">
+ /// Thrown when the binding element rules indicate that this message is invalid and should
+ /// NOT be processed.
+ /// </exception>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public override MessageProtections? ProcessIncomingMessage(IProtocolMessage message) {
+ var authorizationRequest = message as EndUserAuthorizationRequest;
+ if (authorizationRequest != null) {
+ var client = this.AuthorizationServer.GetClientOrThrow(authorizationRequest.ClientIdentifier);
+ ErrorUtilities.VerifyProtocol(authorizationRequest.Callback == null || client.IsCallbackAllowed(authorizationRequest.Callback), OAuthStrings.ClientCallbackDisallowed, authorizationRequest.Callback);
+ ErrorUtilities.VerifyProtocol(authorizationRequest.Callback != null || client.DefaultCallback != null, OAuthStrings.NoCallback);
+
+ return MessageProtections.None;
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthServerBindingElementBase.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthServerBindingElementBase.cs
new file mode 100644
index 0000000..9d3e78f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthServerBindingElementBase.cs
@@ -0,0 +1,92 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthServerBindingElementBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using Messaging;
+
+ /// <summary>
+ /// The base class for any authorization server channel binding element.
+ /// </summary>
+ internal abstract class AuthServerBindingElementBase : IChannelBindingElement {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthServerBindingElementBase"/> class.
+ /// </summary>
+ protected AuthServerBindingElementBase()
+ {
+ }
+
+ /// <summary>
+ /// Gets or sets the channel that this binding element belongs to.
+ /// </summary>
+ /// <remarks>
+ /// This property is set by the channel when it is first constructed.
+ /// </remarks>
+ public Channel Channel { get; set; }
+
+ /// <summary>
+ /// Gets the protection commonly offered (if any) by this binding element.
+ /// </summary>
+ /// <remarks>
+ /// This value is used to assist in sorting binding elements in the channel stack.
+ /// </remarks>
+ public abstract MessageProtections Protection { get; }
+
+ /// <summary>
+ /// Gets the channel that this binding element belongs to.
+ /// </summary>
+ /// <remarks>
+ /// This property is set by the channel when it is first constructed.
+ /// </remarks>
+ protected OAuth2AuthorizationServerChannel OAuthChannel {
+ get { return (OAuth2AuthorizationServerChannel)this.Channel; }
+ }
+
+ /// <summary>
+ /// Gets the authorization server hosting this channel.
+ /// </summary>
+ /// <value>The authorization server.</value>
+ protected IAuthorizationServer AuthorizationServer {
+ get { return this.OAuthChannel.AuthorizationServer; }
+ }
+
+ /// <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>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public abstract MessageProtections? ProcessOutgoingMessage(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>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <exception cref="ProtocolException">
+ /// Thrown when the binding element rules indicate that this message is invalid and should
+ /// NOT be processed.
+ /// </exception>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public abstract MessageProtections? ProcessIncomingMessage(IProtocolMessage message);
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCode.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCode.cs
new file mode 100644
index 0000000..03732bb
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCode.cs
@@ -0,0 +1,100 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationCode.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// Represents the authorization code created when a user approves authorization that
+ /// allows the client to request an access/refresh token.
+ /// </summary>
+ internal class AuthorizationCode : AuthorizationDataBag {
+ /// <summary>
+ /// The name of the bucket for symmetric keys used to sign authorization codes.
+ /// </summary>
+ internal const string AuthorizationCodeKeyBucket = "https://localhost/dnoa/oauth_authorization_code";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationCode"/> class.
+ /// </summary>
+ public AuthorizationCode() {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationCode"/> class.
+ /// </summary>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <param name="callback">The callback the client used to obtain authorization.</param>
+ /// <param name="scopes">The authorized scopes.</param>
+ /// <param name="username">The name on the account that authorized access.</param>
+ internal AuthorizationCode(string clientIdentifier, Uri callback, IEnumerable<string> scopes, string username) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(clientIdentifier));
+ Contract.Requires<ArgumentNullException>(callback != null);
+
+ this.ClientIdentifier = clientIdentifier;
+ this.CallbackHash = CalculateCallbackHash(callback);
+ this.Scope.ResetContents(scopes);
+ this.User = username;
+ this.UtcCreationDate = DateTime.UtcNow;
+ }
+
+ /// <summary>
+ /// Gets or sets the hash of the callback URL.
+ /// </summary>
+ [MessagePart("cb")]
+ private byte[] CallbackHash { get; set; }
+
+ /// <summary>
+ /// Creates a serializer/deserializer for this type.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server that will be serializing/deserializing this authorization code. Must not be null.</param>
+ /// <returns>A DataBag formatter.</returns>
+ internal static IDataBagFormatter<AuthorizationCode> CreateFormatter(IAuthorizationServer authorizationServer) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ Contract.Ensures(Contract.Result<IDataBagFormatter<AuthorizationCode>>() != null);
+
+ return new UriStyleMessageFormatter<AuthorizationCode>(
+ authorizationServer.CryptoKeyStore,
+ AuthorizationCodeKeyBucket,
+ signed: true,
+ encrypted: true,
+ compressed: false,
+ maximumAge: AuthorizationCodeBindingElement.MaximumMessageAge,
+ decodeOnceOnly: authorizationServer.VerificationCodeNonceStore);
+ }
+
+ /// <summary>
+ /// Verifies the the given callback URL matches the callback originally given in the authorization request.
+ /// </summary>
+ /// <param name="callback">The callback.</param>
+ /// <remarks>
+ /// This method serves to verify that the callback URL given in the original authorization request
+ /// and the callback URL given in the access token request match.
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown when the callback URLs do not match.</exception>
+ internal void VerifyCallback(Uri callback) {
+ ErrorUtilities.VerifyProtocol(MessagingUtilities.AreEquivalent(this.CallbackHash, CalculateCallbackHash(callback)), Protocol.redirect_uri_mismatch);
+ }
+
+ /// <summary>
+ /// Calculates the hash of the callback URL.
+ /// </summary>
+ /// <param name="callback">The callback whose hash should be calculated.</param>
+ /// <returns>
+ /// A base64 encoding of the hash of the URL.
+ /// </returns>
+ private static byte[] CalculateCallbackHash(Uri callback) {
+ using (var hasher = new SHA256Managed()) {
+ return hasher.ComputeHash(Encoding.UTF8.GetBytes(callback.AbsoluteUri));
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs
new file mode 100644
index 0000000..4569c93
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs
@@ -0,0 +1,101 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationCodeBindingElement.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using Messages;
+ using Messaging;
+ using Messaging.Bindings;
+
+ /// <summary>
+ /// A binding element for OAuth 2.0 authorization servers that create/verify
+ /// issued authorization codes as part of obtaining access/refresh tokens.
+ /// </summary>
+ internal class AuthorizationCodeBindingElement : AuthServerBindingElementBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationCodeBindingElement"/> class.
+ /// </summary>
+ internal AuthorizationCodeBindingElement() {
+ }
+
+ /// <summary>
+ /// Gets the protection commonly offered (if any) by this binding element.
+ /// </summary>
+ /// <value>Always <c>MessageProtections.None</c></value>
+ /// <remarks>
+ /// This value is used to assist in sorting binding elements in the channel stack.
+ /// </remarks>
+ public override MessageProtections Protection {
+ get { return MessageProtections.None; }
+ }
+
+ /// <summary>
+ /// Gets the maximum message age from the standard expiration binding element.
+ /// </summary>
+ /// <value>This interval need not account for clock skew because it is only compared within a single authorization server or farm of servers.</value>
+ internal static TimeSpan MaximumMessageAge {
+ get { return Configuration.DotNetOpenAuthSection.Configuration.Messaging.MaximumMessageLifetimeNoSkew; }
+ }
+
+ /// <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>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public override MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) {
+ var response = message as EndUserAuthorizationSuccessAuthCodeResponse;
+ if (response != null) {
+ var directResponse = (IDirectResponseProtocolMessage)response;
+ var request = (EndUserAuthorizationRequest)directResponse.OriginatingRequest;
+ IAuthorizationCarryingRequest tokenCarryingResponse = response;
+ tokenCarryingResponse.AuthorizationDescription = new AuthorizationCode(request.ClientIdentifier, request.Callback, response.Scope, response.AuthorizingUsername);
+
+ return MessageProtections.None;
+ }
+
+ return null;
+ }
+
+ /// <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>
+ /// <returns>
+ /// The protections (if any) that this binding element applied to the message.
+ /// Null if this binding element did not even apply to this binding element.
+ /// </returns>
+ /// <exception cref="ProtocolException">
+ /// Thrown when the binding element rules indicate that this message is invalid and should
+ /// NOT be processed.
+ /// </exception>
+ /// <remarks>
+ /// Implementations that provide message protection must honor the
+ /// <see cref="MessagePartAttribute.RequiredProtection"/> properties where applicable.
+ /// </remarks>
+ public override MessageProtections? ProcessIncomingMessage(IProtocolMessage message) {
+ var request = message as AccessTokenAuthorizationCodeRequest;
+ if (request != null) {
+ IAuthorizationCarryingRequest tokenRequest = request;
+ ((AuthorizationCode)tokenRequest.AuthorizationDescription).VerifyCallback(request.Callback);
+
+ return MessageProtections.None;
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationDataBag.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationDataBag.cs
new file mode 100644
index 0000000..8f1d983
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationDataBag.cs
@@ -0,0 +1,51 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationDataBag.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A data bag that stores authorization data.
+ /// </summary>
+ internal abstract class AuthorizationDataBag : DataBag, IAuthorizationDescription {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationDataBag"/> class.
+ /// </summary>
+ protected AuthorizationDataBag() {
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ }
+
+ /// <summary>
+ /// Gets or sets the identifier of the client authorized to access protected data.
+ /// </summary>
+ /// <value></value>
+ [MessagePart]
+ public string ClientIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets the date this authorization was established or the token was issued.
+ /// </summary>
+ /// <value>A date/time expressed in UTC.</value>
+ public DateTime UtcIssued {
+ get { return this.UtcCreationDate; }
+ }
+
+ /// <summary>
+ /// Gets or sets the name on the account whose data on the resource server is accessible using this authorization.
+ /// </summary>
+ [MessagePart]
+ public string User { get; set; }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ [MessagePart(Encoder = typeof(ScopeEncoder))]
+ public HashSet<string> Scope { get; private set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs
new file mode 100644
index 0000000..139025d
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs
@@ -0,0 +1,66 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationResponseTypeEncoder.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// Encodes/decodes the OAuth 2.0 response_type argument.
+ /// </summary>
+ internal class EndUserAuthorizationResponseTypeEncoder : IMessagePartEncoder {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationResponseTypeEncoder"/> class.
+ /// </summary>
+ public EndUserAuthorizationResponseTypeEncoder() {
+ }
+
+ #region IMessagePartEncoder Members
+
+ /// <summary>
+ /// Encodes the specified value.
+ /// </summary>
+ /// <param name="value">The value. Guaranteed to never be null.</param>
+ /// <returns>
+ /// The <paramref name="value"/> in string form, ready for message transport.
+ /// </returns>
+ public string Encode(object value) {
+ var responseType = (EndUserAuthorizationResponseType)value;
+ switch (responseType)
+ {
+ case EndUserAuthorizationResponseType.AccessToken:
+ return Protocol.ResponseTypes.Token;
+ case EndUserAuthorizationResponseType.AuthorizationCode:
+ return Protocol.ResponseTypes.Code;
+ default:
+ throw ErrorUtilities.ThrowFormat(MessagingStrings.UnexpectedMessagePartValue, Protocol.response_type, value);
+ }
+ }
+
+ /// <summary>
+ /// Decodes the specified value.
+ /// </summary>
+ /// <param name="value">The string value carried by the transport. Guaranteed to never be null, although it may be empty.</param>
+ /// <returns>
+ /// The deserialized form of the given string.
+ /// </returns>
+ /// <exception cref="FormatException">Thrown when the string value given cannot be decoded into the required object type.</exception>
+ public object Decode(string value) {
+ switch (value) {
+ case Protocol.ResponseTypes.Token:
+ return EndUserAuthorizationResponseType.AccessToken;
+ case Protocol.ResponseTypes.Code:
+ return EndUserAuthorizationResponseType.AuthorizationCode;
+ default:
+ throw ErrorUtilities.ThrowFormat(MessagingStrings.UnexpectedMessagePartValue, Protocol.response_type, value);
+ }
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/GrantTypeEncoder.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/GrantTypeEncoder.cs
new file mode 100644
index 0000000..78ed975
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/GrantTypeEncoder.cs
@@ -0,0 +1,78 @@
+//-----------------------------------------------------------------------
+// <copyright file="GrantTypeEncoder.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// Encodes/decodes the OAuth 2.0 grant_type argument.
+ /// </summary>
+ internal class GrantTypeEncoder : IMessagePartEncoder {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="GrantTypeEncoder"/> class.
+ /// </summary>
+ public GrantTypeEncoder() {
+ }
+
+ #region IMessagePartEncoder Members
+
+ /// <summary>
+ /// Encodes the specified value.
+ /// </summary>
+ /// <param name="value">The value. Guaranteed to never be null.</param>
+ /// <returns>
+ /// The <paramref name="value"/> in string form, ready for message transport.
+ /// </returns>
+ public string Encode(object value) {
+ var responseType = (GrantType)value;
+ switch (responseType)
+ {
+ case GrantType.ClientCredentials:
+ return Protocol.GrantTypes.ClientCredentials;
+ case GrantType.AuthorizationCode:
+ return Protocol.GrantTypes.AuthorizationCode;
+ case GrantType.RefreshToken:
+ return Protocol.GrantTypes.RefreshToken;
+ case GrantType.Password:
+ return Protocol.GrantTypes.Password;
+ case GrantType.Assertion:
+ return Protocol.GrantTypes.Assertion;
+ default:
+ throw ErrorUtilities.ThrowFormat(MessagingStrings.UnexpectedMessagePartValue, Protocol.grant_type, value);
+ }
+ }
+
+ /// <summary>
+ /// Decodes the specified value.
+ /// </summary>
+ /// <param name="value">The string value carried by the transport. Guaranteed to never be null, although it may be empty.</param>
+ /// <returns>
+ /// The deserialized form of the given string.
+ /// </returns>
+ /// <exception cref="FormatException">Thrown when the string value given cannot be decoded into the required object type.</exception>
+ public object Decode(string value) {
+ switch (value) {
+ case Protocol.GrantTypes.ClientCredentials:
+ return GrantType.ClientCredentials;
+ case Protocol.GrantTypes.Assertion:
+ return GrantType.Assertion;
+ case Protocol.GrantTypes.Password:
+ return GrantType.Password;
+ case Protocol.GrantTypes.RefreshToken:
+ return GrantType.RefreshToken;
+ case Protocol.GrantTypes.AuthorizationCode:
+ return GrantType.AuthorizationCode;
+ default:
+ throw ErrorUtilities.ThrowFormat(MessagingStrings.UnexpectedMessagePartValue, Protocol.grant_type, value);
+ }
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/IAuthorizationCarryingRequest.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/IAuthorizationCarryingRequest.cs
new file mode 100644
index 0000000..e450131
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/IAuthorizationCarryingRequest.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAuthorizationCarryingRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System.Security.Cryptography;
+
+ using Messaging;
+
+ /// <summary>
+ /// The various types of tokens created by the authorization server.
+ /// </summary>
+ internal enum CodeOrTokenType {
+ /// <summary>
+ /// The code issued to the client after the user has approved authorization.
+ /// </summary>
+ AuthorizationCode,
+
+ /// <summary>
+ /// The long-lived token issued to the client that enables it to obtain
+ /// short-lived access tokens later.
+ /// </summary>
+ RefreshToken,
+
+ /// <summary>
+ /// A (typically) short-lived token.
+ /// </summary>
+ AccessToken,
+ }
+
+ /// <summary>
+ /// A message that carries some kind of token from the client to the authorization or resource server.
+ /// </summary>
+ internal interface IAuthorizationCarryingRequest : IDirectedProtocolMessage {
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string CodeOrToken { get; set; }
+
+ /// <summary>
+ /// Gets the type of the code or token.
+ /// </summary>
+ /// <value>The type of the code or token.</value>
+ CodeOrTokenType CodeOrTokenType { get; }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription AuthorizationDescription { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/IAuthorizationDescription.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/IAuthorizationDescription.cs
new file mode 100644
index 0000000..2b3a9ce
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/IAuthorizationDescription.cs
@@ -0,0 +1,90 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAuthorizationDescription.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+
+ /// <summary>
+ /// Describes a delegated authorization between a resource server, a client, and a user.
+ /// </summary>
+ [ContractClass(typeof(IAuthorizationDescriptionContract))]
+ public interface IAuthorizationDescription {
+ /// <summary>
+ /// Gets the identifier of the client authorized to access protected data.
+ /// </summary>
+ string ClientIdentifier { get; }
+
+ /// <summary>
+ /// Gets the date this authorization was established or the token was issued.
+ /// </summary>
+ /// <value>A date/time expressed in UTC.</value>
+ DateTime UtcIssued { get; }
+
+ /// <summary>
+ /// Gets the name on the account whose data on the resource server is accessible using this authorization.
+ /// </summary>
+ string User { get; }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ HashSet<string> Scope { get; }
+ }
+
+ /// <summary>
+ /// Code contract for the <see cref="IAuthorizationDescription"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IAuthorizationDescription))]
+ internal abstract class IAuthorizationDescriptionContract : IAuthorizationDescription {
+ /// <summary>
+ /// Prevents a default instance of the <see cref="IAuthorizationDescriptionContract"/> class from being created.
+ /// </summary>
+ private IAuthorizationDescriptionContract() {
+ }
+
+ /// <summary>
+ /// Gets the identifier of the client authorized to access protected data.
+ /// </summary>
+ string IAuthorizationDescription.ClientIdentifier {
+ get {
+ Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
+ throw new NotImplementedException();
+ }
+ }
+
+ /// <summary>
+ /// Gets the date this authorization was established or the token was issued.
+ /// </summary>
+ /// <value>A date/time expressed in UTC.</value>
+ DateTime IAuthorizationDescription.UtcIssued {
+ get { throw new NotImplementedException(); }
+ }
+
+ /// <summary>
+ /// Gets the name on the account whose data on the resource server is accessible using this authorization.
+ /// </summary>
+ string IAuthorizationDescription.User {
+ get {
+ Contract.Ensures(!string.IsNullOrEmpty(Contract.Result<string>()));
+ throw new NotImplementedException();
+ }
+ }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ HashSet<string> IAuthorizationDescription.Scope {
+ get {
+ Contract.Ensures(Contract.Result<HashSet<string>>() != null);
+ throw new NotImplementedException();
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs
new file mode 100644
index 0000000..888830e
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs
@@ -0,0 +1,108 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuth2AuthorizationServerChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Net.Mime;
+ using System.Web;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// The channel for the OAuth protocol.
+ /// </summary>
+ internal class OAuth2AuthorizationServerChannel : OAuth2ChannelBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuth2AuthorizationServerChannel"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ protected internal OAuth2AuthorizationServerChannel(IAuthorizationServer authorizationServer)
+ : base(InitializeBindingElements(authorizationServer)) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ this.AuthorizationServer = authorizationServer;
+ }
+
+ /// <summary>
+ /// Gets the authorization server.
+ /// </summary>
+ /// <value>The authorization server.</value>
+ public IAuthorizationServer AuthorizationServer { get; private set; }
+
+ /// <summary>
+ /// Gets the protocol message that may be in the given HTTP response.
+ /// </summary>
+ /// <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 override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) {
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Queues a message for sending in the response stream.
+ /// </summary>
+ /// <param name="response">The message to send as a response.</param>
+ /// <returns>
+ /// The pending user agent redirect based message to be sent as an HttpResponse.
+ /// </returns>
+ /// <remarks>
+ /// This method implements spec OAuth V1.0 section 5.3.
+ /// </remarks>
+ protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) {
+ var webResponse = new OutgoingWebResponse();
+ string json = this.SerializeAsJson(response);
+ webResponse.SetResponse(json, new ContentType(JsonEncoded));
+ return webResponse;
+ }
+
+ /// <summary>
+ /// Gets the protocol message that may be embedded in the given HTTP request.
+ /// </summary>
+ /// <param name="request">The request to search for an embedded message.</param>
+ /// <returns>
+ /// The deserialized message, if one is found. Null otherwise.
+ /// </returns>
+ protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) {
+ if (!string.IsNullOrEmpty(request.Url.Fragment)) {
+ var fields = HttpUtility.ParseQueryString(request.Url.Fragment.Substring(1)).ToDictionary();
+
+ MessageReceivingEndpoint recipient;
+ try {
+ recipient = request.GetRecipient();
+ } catch (ArgumentException ex) {
+ Logger.Messaging.WarnFormat("Unrecognized HTTP request: " + ex.ToString());
+ return null;
+ }
+
+ return (IDirectedProtocolMessage)this.Receive(fields, recipient);
+ }
+
+ return base.ReadFromRequestCore(request);
+ }
+
+ /// <summary>
+ /// Initializes the binding elements for the OAuth channel.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ /// <returns>
+ /// An array of binding elements used to initialize the channel.
+ /// </returns>
+ private static IChannelBindingElement[] InitializeBindingElements(IAuthorizationServer authorizationServer) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ var bindingElements = new List<IChannelBindingElement>();
+
+ bindingElements.Add(new AuthServerAllFlowsBindingElement());
+ bindingElements.Add(new AuthorizationCodeBindingElement());
+ bindingElements.Add(new AccessTokenBindingElement());
+ bindingElements.Add(new AccessRequestBindingElement());
+
+ return bindingElements.ToArray();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ChannelBase.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ChannelBase.cs
new file mode 100644
index 0000000..a646f51
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ChannelBase.cs
@@ -0,0 +1,69 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuth2ChannelBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// The base messaging channel used by OAuth 2.0 parties.
+ /// </summary>
+ internal abstract class OAuth2ChannelBase : StandardMessageFactoryChannel {
+ /// <summary>
+ /// The messages receivable by this channel.
+ /// </summary>
+ private static readonly Type[] MessageTypes = new Type[] {
+ typeof(AccessTokenRefreshRequest),
+ typeof(AccessTokenAuthorizationCodeRequest),
+ typeof(AccessTokenResourceOwnerPasswordCredentialsRequest),
+ typeof(AccessTokenClientCredentialsRequest),
+ typeof(AccessTokenSuccessResponse),
+ typeof(AccessTokenFailedResponse),
+ typeof(EndUserAuthorizationRequest),
+ typeof(EndUserAuthorizationSuccessAuthCodeResponse),
+ typeof(EndUserAuthorizationSuccessAccessTokenResponse),
+ typeof(EndUserAuthorizationFailedResponse),
+ typeof(UnauthorizedResponse),
+ };
+
+ /// <summary>
+ /// The protocol versions supported by this channel.
+ /// </summary>
+ private static readonly Version[] Versions = Protocol.AllVersions.Select(v => v.Version).ToArray();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuth2ChannelBase"/> class.
+ /// </summary>
+ /// <param name="channelBindingElements">The channel binding elements.</param>
+ internal OAuth2ChannelBase(params IChannelBindingElement[] channelBindingElements)
+ : base(MessageTypes, Versions, channelBindingElements) {
+ }
+
+ /// <summary>
+ /// Allows preprocessing and validation of message data before an appropriate message type is
+ /// selected or deserialized.
+ /// </summary>
+ /// <param name="fields">The received message data.</param>
+ protected override void FilterReceivedFields(IDictionary<string, string> fields) {
+ base.FilterReceivedFields(fields);
+
+ // Apply the OAuth 2.0 section 2.1 requirement:
+ // Parameters sent without a value MUST be treated as if they were omitted from the request.
+ // The authorization server SHOULD ignore unrecognized request parameters.
+ var emptyKeys = from pair in fields
+ where String.IsNullOrEmpty(pair.Value)
+ select pair.Key;
+ foreach (string emptyKey in emptyKeys.ToList()) {
+ fields.Remove(emptyKey);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ClientChannel.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ClientChannel.cs
new file mode 100644
index 0000000..e4a9afd
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ClientChannel.cs
@@ -0,0 +1,122 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuth2ClientChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Collections.Specialized;
+ using System.Diagnostics.Contracts;
+ using System.Net;
+ using System.Web;
+
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// The messaging channel used by OAuth 2.0 Clients.
+ /// </summary>
+ internal class OAuth2ClientChannel : OAuth2ChannelBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuth2ClientChannel"/> class.
+ /// </summary>
+ internal OAuth2ClientChannel() {
+ }
+
+ /// <summary>
+ /// Prepares an HTTP request that carries a given message.
+ /// </summary>
+ /// <param name="request">The message to send.</param>
+ /// <returns>
+ /// The <see cref="HttpWebRequest"/> prepared to send the request.
+ /// </returns>
+ /// <remarks>
+ /// This method must be overridden by a derived class, unless the <see cref="Channel.RequestCore"/> method
+ /// is overridden and does not require this method.
+ /// </remarks>
+ protected override HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request) {
+ HttpWebRequest httpRequest;
+ if ((request.HttpMethods & HttpDeliveryMethods.GetRequest) != 0) {
+ httpRequest = InitializeRequestAsGet(request);
+ } else if ((request.HttpMethods & HttpDeliveryMethods.PostRequest) != 0) {
+ httpRequest = InitializeRequestAsPost(request);
+ } else {
+ throw new NotSupportedException();
+ }
+
+ return httpRequest;
+ }
+
+ /// <summary>
+ /// Gets the protocol message that may be in the given HTTP response.
+ /// </summary>
+ /// <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 override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) {
+ // The spec says direct responses should be JSON objects, but Facebook uses HttpFormUrlEncoded instead, calling it text/plain
+ // Others return text/javascript. Again bad.
+ string body = response.GetResponseReader().ReadToEnd();
+ if (response.ContentType.MediaType == JsonEncoded || response.ContentType.MediaType == JsonTextEncoded) {
+ return this.DeserializeFromJson(body);
+ } else if (response.ContentType.MediaType == HttpFormUrlEncoded || response.ContentType.MediaType == PlainTextEncoded) {
+ return HttpUtility.ParseQueryString(body).ToDictionary();
+ } else {
+ throw ErrorUtilities.ThrowProtocol("Unexpected response Content-Type {0}", response.ContentType.MediaType);
+ }
+ }
+
+ /// <summary>
+ /// Gets the protocol message that may be embedded in the given HTTP request.
+ /// </summary>
+ /// <param name="request">The request to search for an embedded message.</param>
+ /// <returns>
+ /// The deserialized message, if one is found. Null otherwise.
+ /// </returns>
+ protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) {
+ Logger.Channel.DebugFormat("Incoming HTTP request: {0} {1}", request.HttpMethod, request.UrlBeforeRewriting.AbsoluteUri);
+
+ var fields = request.QueryStringBeforeRewriting.ToDictionary();
+
+ // Also read parameters from the fragment, if it's available.
+ // Typically the fragment is not available because the browser doesn't send it to a web server
+ // but this request may have been fabricated by an installed desktop app, in which case
+ // the fragment is available.
+ string fragment = request.UrlBeforeRewriting.Fragment;
+ if (!string.IsNullOrEmpty(fragment)) {
+ foreach (var pair in HttpUtility.ParseQueryString(fragment.Substring(1)).ToDictionary()) {
+ fields.Add(pair.Key, pair.Value);
+ }
+ }
+
+ MessageReceivingEndpoint recipient;
+ try {
+ recipient = request.GetRecipient();
+ } catch (ArgumentException ex) {
+ Logger.Messaging.WarnFormat("Unrecognized HTTP request: ", ex);
+ return null;
+ }
+
+ return (IDirectedProtocolMessage)this.Receive(fields, recipient);
+ }
+
+ /// <summary>
+ /// Queues a message for sending in the response stream where the fields
+ /// are sent in the response stream in querystring style.
+ /// </summary>
+ /// <param name="response">The message to send as a response.</param>
+ /// <returns>
+ /// The pending user agent redirect based message to be sent as an HttpResponse.
+ /// </returns>
+ /// <remarks>
+ /// This method implements spec OAuth V1.0 section 5.3.
+ /// </remarks>
+ protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) {
+ // Clients don't ever send direct responses.
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs
new file mode 100644
index 0000000..94df1a8
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs
@@ -0,0 +1,153 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuth2ResourceServerChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Net;
+ using System.Net.Mime;
+ using System.Text;
+ using System.Web;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// The channel for the OAuth protocol.
+ /// </summary>
+ internal class OAuth2ResourceServerChannel : StandardMessageFactoryChannel {
+ /// <summary>
+ /// The messages receivable by this channel.
+ /// </summary>
+ private static readonly Type[] MessageTypes = new Type[] {
+ typeof(Messages.AccessProtectedResourceRequest),
+ };
+
+ /// <summary>
+ /// The protocol versions supported by this channel.
+ /// </summary>
+ private static readonly Version[] Versions = Protocol.AllVersions.Select(v => v.Version).ToArray();
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuth2ResourceServerChannel"/> class.
+ /// </summary>
+ protected internal OAuth2ResourceServerChannel()
+ : base(MessageTypes, Versions) {
+ // TODO: add signing (authenticated request) binding element.
+ }
+
+ /// <summary>
+ /// Gets the protocol message that may be embedded in the given HTTP request.
+ /// </summary>
+ /// <param name="request">The request to search for an embedded message.</param>
+ /// <returns>
+ /// The deserialized message, if one is found. Null otherwise.
+ /// </returns>
+ protected override IDirectedProtocolMessage ReadFromRequestCore(HttpRequestInfo request) {
+ var fields = new Dictionary<string, string>();
+ string accessToken;
+ if ((accessToken = SearchForBearerAccessTokenInRequest(request)) != null) {
+ fields["token_type"] = Protocol.AccessTokenTypes.Bearer;
+ fields["access_token"] = accessToken;
+ }
+
+ if (fields.Count > 0) {
+ MessageReceivingEndpoint recipient;
+ try {
+ recipient = request.GetRecipient();
+ } catch (ArgumentException ex) {
+ Logger.OAuth.WarnFormat("Unrecognized HTTP request: " + ex.ToString());
+ return null;
+ }
+
+ // Deserialize the message using all the data we've collected.
+ var message = (IDirectedProtocolMessage)this.Receive(fields, recipient);
+ return message;
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Gets the protocol message that may be in the given HTTP response.
+ /// </summary>
+ /// <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 override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) {
+ // We never expect resource servers to send out direct requests,
+ // and therefore won't have direct responses.
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Queues a message for sending in the response stream where the fields
+ /// are sent in the response stream in querystring style.
+ /// </summary>
+ /// <param name="response">The message to send as a response.</param>
+ /// <returns>
+ /// The pending user agent redirect based message to be sent as an HttpResponse.
+ /// </returns>
+ /// <remarks>
+ /// This method implements spec OAuth V1.0 section 5.3.
+ /// </remarks>
+ protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) {
+ var webResponse = new OutgoingWebResponse();
+
+ // The only direct response from a resource server is a 401 Unauthorized error.
+ var unauthorizedResponse = response as UnauthorizedResponse;
+ ErrorUtilities.VerifyInternal(unauthorizedResponse != null, "Only unauthorized responses are expected.");
+
+ // First initialize based on the specifics within the message.
+ var httpResponse = response as IHttpDirectResponse;
+ webResponse.Status = httpResponse != null ? httpResponse.HttpStatusCode : HttpStatusCode.Unauthorized;
+ foreach (string headerName in httpResponse.Headers) {
+ webResponse.Headers.Add(headerName, httpResponse.Headers[headerName]);
+ }
+
+ // Now serialize all the message parts into the WWW-Authenticate header.
+ var fields = this.MessageDescriptions.GetAccessor(response);
+ webResponse.Headers[HttpResponseHeader.WwwAuthenticate] = MessagingUtilities.AssembleAuthorizationHeader(Protocol.BearerHttpAuthorizationScheme, fields);
+ return webResponse;
+ }
+
+ /// <summary>
+ /// Searches for a bearer access token in the request.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ /// <returns>The bearer access token, if one exists. Otherwise <c>null</c>.</returns>
+ private static string SearchForBearerAccessTokenInRequest(HttpRequestInfo request) {
+ Contract.Requires<ArgumentNullException>(request != null, "request");
+
+ // First search the authorization header.
+ string authorizationHeader = request.Headers[HttpRequestHeader.Authorization];
+ if (!string.IsNullOrEmpty(authorizationHeader) && authorizationHeader.StartsWith(Protocol.BearerHttpAuthorizationSchemeWithTrailingSpace, StringComparison.OrdinalIgnoreCase)) {
+ return authorizationHeader.Substring(Protocol.BearerHttpAuthorizationSchemeWithTrailingSpace.Length);
+ }
+
+ // Failing that, scan the entity
+ if (!string.IsNullOrEmpty(request.Headers[HttpRequestHeader.ContentType])) {
+ var contentType = new ContentType(request.Headers[HttpRequestHeader.ContentType]);
+ if (string.Equals(contentType.MediaType, HttpFormUrlEncoded, StringComparison.Ordinal)) {
+ if (request.Form[Protocol.BearerTokenEncodedUrlParameterName] != null) {
+ return request.Form[Protocol.BearerTokenEncodedUrlParameterName];
+ }
+ }
+ }
+
+ // Finally, check the least desirable location: the query string
+ if (!String.IsNullOrEmpty(request.QueryStringBeforeRewriting[Protocol.BearerTokenEncodedUrlParameterName])) {
+ return request.QueryStringBeforeRewriting[Protocol.BearerTokenEncodedUrlParameterName];
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/RefreshToken.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/RefreshToken.cs
new file mode 100644
index 0000000..9fe54c5
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/RefreshToken.cs
@@ -0,0 +1,56 @@
+//-----------------------------------------------------------------------
+// <copyright file="RefreshToken.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// The refresh token issued to a client by an authorization server that allows the client
+ /// to periodically obtain new short-lived access tokens.
+ /// </summary>
+ internal class RefreshToken : AuthorizationDataBag {
+ /// <summary>
+ /// The name of the bucket for symmetric keys used to sign refresh tokens.
+ /// </summary>
+ internal const string RefreshTokenKeyBucket = "https://localhost/dnoa/oauth_refresh_token";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RefreshToken"/> class.
+ /// </summary>
+ public RefreshToken() {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RefreshToken"/> class.
+ /// </summary>
+ /// <param name="authorization">The authorization this refresh token should describe.</param>
+ internal RefreshToken(IAuthorizationDescription authorization) {
+ Contract.Requires<ArgumentNullException>(authorization != null);
+
+ this.ClientIdentifier = authorization.ClientIdentifier;
+ this.UtcCreationDate = authorization.UtcIssued;
+ this.User = authorization.User;
+ this.Scope.ResetContents(authorization.Scope);
+ }
+
+ /// <summary>
+ /// Creates a formatter capable of serializing/deserializing a refresh token.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store.</param>
+ /// <returns>
+ /// A DataBag formatter. Never null.
+ /// </returns>
+ internal static IDataBagFormatter<RefreshToken> CreateFormatter(ICryptoKeyStore cryptoKeyStore) {
+ Contract.Requires<ArgumentNullException>(cryptoKeyStore != null);
+ Contract.Ensures(Contract.Result<IDataBagFormatter<RefreshToken>>() != null);
+
+ return new UriStyleMessageFormatter<RefreshToken>(cryptoKeyStore, RefreshTokenKeyBucket, signed: true, encrypted: true);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/ScopeEncoder.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/ScopeEncoder.cs
new file mode 100644
index 0000000..7ae5fbf
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/ScopeEncoder.cs
@@ -0,0 +1,51 @@
+//-----------------------------------------------------------------------
+// <copyright file="ScopeEncoder.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Reflection;
+
+ /// <summary>
+ /// Encodes or decodes a set of scopes into the OAuth 2.0 scope message part.
+ /// </summary>
+ internal class ScopeEncoder : IMessagePartEncoder {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ScopeEncoder"/> class.
+ /// </summary>
+ public ScopeEncoder() {
+ }
+
+ /// <summary>
+ /// Encodes the specified value.
+ /// </summary>
+ /// <param name="value">The value. Guaranteed to never be null.</param>
+ /// <returns>
+ /// The <paramref name="value"/> in string form, ready for message transport.
+ /// </returns>
+ public string Encode(object value) {
+ var scopes = (IEnumerable<string>)value;
+ ErrorUtilities.VerifyProtocol(!scopes.Any(scope => scope.Contains(" ")), OAuthStrings.ScopesMayNotContainSpaces);
+ return (scopes != null && scopes.Any()) ? string.Join(" ", scopes.ToArray()) : null;
+ }
+
+ /// <summary>
+ /// Decodes the specified value.
+ /// </summary>
+ /// <param name="value">The string value carried by the transport. Guaranteed to never be null, although it may be empty.</param>
+ /// <returns>
+ /// The deserialized form of the given string.
+ /// </returns>
+ /// <exception cref="FormatException">Thrown when the string value given cannot be decoded into the required object type.</exception>
+ public object Decode(string value) {
+ return OAuthUtilities.SplitScopes(value);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ClientBase.cs b/src/DotNetOpenAuth/OAuth2/ClientBase.cs
new file mode 100644
index 0000000..f91b1f5
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ClientBase.cs
@@ -0,0 +1,233 @@
+//-----------------------------------------------------------------------
+// <copyright file="ClientBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Globalization;
+ using System.Linq;
+ using System.Net;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// A base class for common OAuth Client behaviors.
+ /// </summary>
+ public class ClientBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ClientBase"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The token issuer.</param>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <param name="clientSecret">The client secret.</param>
+ protected ClientBase(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, string clientSecret = null) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ this.AuthorizationServer = authorizationServer;
+ this.Channel = new OAuth2ClientChannel();
+ this.ClientIdentifier = clientIdentifier;
+ this.ClientSecret = clientSecret;
+ }
+
+ /// <summary>
+ /// Gets the token issuer.
+ /// </summary>
+ /// <value>The token issuer.</value>
+ public AuthorizationServerDescription AuthorizationServer { get; private set; }
+
+ /// <summary>
+ /// Gets the OAuth channel.
+ /// </summary>
+ /// <value>The channel.</value>
+ public Channel Channel { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the identifier by which this client is known to the Authorization Server.
+ /// </summary>
+ public string ClientIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets or sets the client secret shared with the Authorization Server.
+ /// </summary>
+ public string ClientSecret { get; set; }
+
+ /// <summary>
+ /// Adds the necessary HTTP Authorization header to an HTTP request for protected resources
+ /// so that the Service Provider will allow the request through.
+ /// </summary>
+ /// <param name="request">The request for protected resources from the service provider.</param>
+ /// <param name="accessToken">The access token previously obtained from the Authorization Server.</param>
+ public static void AuthorizeRequest(HttpWebRequest request, string accessToken) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(accessToken));
+
+ OAuthUtilities.AuthorizeWithBearerToken(request, accessToken);
+ }
+
+ /// <summary>
+ /// Adds the OAuth authorization token to an outgoing HTTP request, renewing a
+ /// (nearly) expired access token if necessary.
+ /// </summary>
+ /// <param name="request">The request for protected resources from the service provider.</param>
+ /// <param name="authorization">The authorization for this request previously obtained via OAuth.</param>
+ public void AuthorizeRequest(HttpWebRequest request, IAuthorizationState authorization) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<ArgumentNullException>(authorization != null);
+ Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(authorization.AccessToken));
+ Contract.Requires<ProtocolException>(!authorization.AccessTokenExpirationUtc.HasValue || authorization.AccessTokenExpirationUtc < DateTime.UtcNow || authorization.RefreshToken != null);
+
+ if (authorization.AccessTokenExpirationUtc.HasValue && authorization.AccessTokenExpirationUtc.Value < DateTime.UtcNow) {
+ ErrorUtilities.VerifyProtocol(authorization.RefreshToken != null, "Access token has expired and cannot be automatically refreshed.");
+ this.RefreshToken(authorization);
+ }
+
+ AuthorizeRequest(request, authorization.AccessToken);
+ }
+
+ /// <summary>
+ /// Refreshes a short-lived access token using a longer-lived refresh token.
+ /// </summary>
+ /// <param name="authorization">The authorization to update.</param>
+ /// <param name="skipIfUsefulLifeExceeds">If given, the access token will <em>not</em> be refreshed if its remaining lifetime exceeds this value.</param>
+ /// <returns>A value indicating whether the access token was actually renewed; <c>true</c> if it was renewed, or <c>false</c> if it still had useful life remaining.</returns>
+ public bool RefreshToken(IAuthorizationState authorization, TimeSpan? skipIfUsefulLifeExceeds = null) {
+ Contract.Requires<ArgumentNullException>(authorization != null);
+ Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(authorization.RefreshToken));
+
+ if (skipIfUsefulLifeExceeds.HasValue && authorization.AccessTokenExpirationUtc.HasValue) {
+ TimeSpan usefulLifeRemaining = authorization.AccessTokenExpirationUtc.Value - DateTime.UtcNow;
+ if (usefulLifeRemaining > skipIfUsefulLifeExceeds.Value) {
+ // There is useful life remaining in the access token. Don't refresh.
+ Logger.OAuth.DebugFormat("Skipping token refresh step because access token's remaining life is {0}, which exceeds {1}.", usefulLifeRemaining, skipIfUsefulLifeExceeds.Value);
+ return false;
+ }
+ }
+
+ var request = new AccessTokenRefreshRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ ClientSecret = this.ClientSecret,
+ RefreshToken = authorization.RefreshToken,
+ };
+
+ var response = this.Channel.Request<AccessTokenSuccessResponse>(request);
+ authorization.AccessToken = response.AccessToken;
+ authorization.AccessTokenExpirationUtc = DateTime.UtcNow + response.Lifetime;
+ authorization.AccessTokenIssueDateUtc = DateTime.UtcNow;
+
+ // Just in case the scope has changed...
+ if (response.Scope != null) {
+ authorization.Scope.ResetContents(response.Scope);
+ }
+
+ // The authorization server MAY choose to renew the refresh token itself.
+ if (response.RefreshToken != null) {
+ authorization.RefreshToken = response.RefreshToken;
+ }
+
+ authorization.SaveChanges();
+ return true;
+ }
+
+ /// <summary>
+ /// Updates the authorization state maintained by the client with the content of an outgoing response.
+ /// </summary>
+ /// <param name="authorizationState">The authorization state maintained by the client.</param>
+ /// <param name="accessTokenSuccess">The access token containing response message.</param>
+ internal static void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, AccessTokenSuccessResponse accessTokenSuccess) {
+ Contract.Requires<ArgumentNullException>(authorizationState != null);
+ Contract.Requires<ArgumentNullException>(accessTokenSuccess != null);
+
+ authorizationState.AccessToken = accessTokenSuccess.AccessToken;
+ authorizationState.RefreshToken = accessTokenSuccess.RefreshToken;
+ authorizationState.AccessTokenExpirationUtc = DateTime.UtcNow + accessTokenSuccess.Lifetime;
+ authorizationState.AccessTokenIssueDateUtc = DateTime.UtcNow;
+ if (accessTokenSuccess.Scope != null && accessTokenSuccess.Scope != authorizationState.Scope) {
+ if (authorizationState.Scope != null) {
+ Logger.OAuth.InfoFormat(
+ "Requested scope of \"{0}\" changed to \"{1}\" by authorization server.",
+ authorizationState.Scope,
+ accessTokenSuccess.Scope);
+ }
+
+ authorizationState.Scope.ResetContents(accessTokenSuccess.Scope);
+ }
+
+ authorizationState.SaveChanges();
+ }
+
+ /// <summary>
+ /// Updates the authorization state maintained by the client with the content of an outgoing response.
+ /// </summary>
+ /// <param name="authorizationState">The authorization state maintained by the client.</param>
+ /// <param name="accessTokenSuccess">The access token containing response message.</param>
+ internal static void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAccessTokenResponse accessTokenSuccess) {
+ Contract.Requires<ArgumentNullException>(authorizationState != null);
+ Contract.Requires<ArgumentNullException>(accessTokenSuccess != null);
+
+ authorizationState.AccessToken = accessTokenSuccess.AccessToken;
+ authorizationState.AccessTokenExpirationUtc = DateTime.UtcNow + accessTokenSuccess.Lifetime;
+ authorizationState.AccessTokenIssueDateUtc = DateTime.UtcNow;
+ if (accessTokenSuccess.Scope != null && accessTokenSuccess.Scope != authorizationState.Scope) {
+ if (authorizationState.Scope != null) {
+ Logger.OAuth.InfoFormat(
+ "Requested scope of \"{0}\" changed to \"{1}\" by authorization server.",
+ authorizationState.Scope,
+ accessTokenSuccess.Scope);
+ }
+
+ authorizationState.Scope.ResetContents(accessTokenSuccess.Scope);
+ }
+
+ authorizationState.SaveChanges();
+ }
+
+ /// <summary>
+ /// Updates authorization state with a success response from the Authorization Server.
+ /// </summary>
+ /// <param name="authorizationState">The authorization state to update.</param>
+ /// <param name="authorizationSuccess">The authorization success message obtained from the authorization server.</param>
+ internal void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAuthCodeResponse authorizationSuccess) {
+ Contract.Requires<ArgumentNullException>(authorizationState != null);
+ Contract.Requires<ArgumentNullException>(authorizationSuccess != null);
+
+ var accessTokenRequest = new AccessTokenAuthorizationCodeRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ ClientSecret = this.ClientSecret,
+ Callback = authorizationState.Callback,
+ AuthorizationCode = authorizationSuccess.AuthorizationCode,
+ };
+ IProtocolMessage accessTokenResponse = this.Channel.Request(accessTokenRequest);
+ var accessTokenSuccess = accessTokenResponse as AccessTokenSuccessResponse;
+ var failedAccessTokenResponse = accessTokenResponse as AccessTokenFailedResponse;
+ if (accessTokenSuccess != null) {
+ UpdateAuthorizationWithResponse(authorizationState, accessTokenSuccess);
+ } else {
+ authorizationState.Delete();
+ string error = failedAccessTokenResponse != null ? failedAccessTokenResponse.Error : "(unknown)";
+ ErrorUtilities.ThrowProtocol(OAuthStrings.CannotObtainAccessTokenWithReason, error);
+ }
+ }
+
+ /// <summary>
+ /// Calculates the fraction of life remaining in an access token.
+ /// </summary>
+ /// <param name="authorization">The authorization to measure.</param>
+ /// <returns>A fractional number no greater than 1. Could be negative if the access token has already expired.</returns>
+ private static double ProportionalLifeRemaining(IAuthorizationState authorization) {
+ Contract.Requires<ArgumentNullException>(authorization != null);
+ Contract.Requires<ArgumentException>(authorization.AccessTokenIssueDateUtc.HasValue);
+ Contract.Requires<ArgumentException>(authorization.AccessTokenExpirationUtc.HasValue);
+
+ // Calculate what % of the total life this access token has left.
+ TimeSpan totalLifetime = authorization.AccessTokenExpirationUtc.Value - authorization.AccessTokenIssueDateUtc.Value;
+ TimeSpan elapsedLifetime = DateTime.UtcNow - authorization.AccessTokenIssueDateUtc.Value;
+ double proportionLifetimeRemaining = 1 - (elapsedLifetime.TotalSeconds / totalLifetime.TotalSeconds);
+ return proportionLifetimeRemaining;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/IAccessTokenAnalyzer.cs b/src/DotNetOpenAuth/OAuth2/IAccessTokenAnalyzer.cs
new file mode 100644
index 0000000..74b8ebb
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/IAccessTokenAnalyzer.cs
@@ -0,0 +1,64 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAccessTokenAnalyzer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// An interface that resource server hosts should implement if they accept access tokens
+ /// issued by non-DotNetOpenAuth authorization servers.
+ /// </summary>
+ [ContractClass((typeof(IAccessTokenAnalyzerContract)))]
+ public interface IAccessTokenAnalyzer {
+ /// <summary>
+ /// Reads an access token to find out what data it authorizes access to.
+ /// </summary>
+ /// <param name="message">The message carrying the access token.</param>
+ /// <param name="accessToken">The access token.</param>
+ /// <param name="user">The user whose data is accessible with this access token.</param>
+ /// <param name="scope">The scope of access authorized by this access token.</param>
+ /// <returns>A value indicating whether this access token is valid.</returns>
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")]
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Try pattern")]
+ bool TryValidateAccessToken(IDirectedProtocolMessage message, string accessToken, out string user, out HashSet<string> scope);
+ }
+
+ /// <summary>
+ /// Code contract for the <see cref="IAccessTokenAnalyzer"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IAccessTokenAnalyzer))]
+ internal abstract class IAccessTokenAnalyzerContract : IAccessTokenAnalyzer {
+ /// <summary>
+ /// Prevents a default instance of the <see cref="IAccessTokenAnalyzerContract"/> class from being created.
+ /// </summary>
+ private IAccessTokenAnalyzerContract() {
+ }
+
+ /// <summary>
+ /// Reads an access token to find out what data it authorizes access to.
+ /// </summary>
+ /// <param name="message">The message carrying the access token.</param>
+ /// <param name="accessToken">The access token.</param>
+ /// <param name="user">The user whose data is accessible with this access token.</param>
+ /// <param name="scope">The scope of access authorized by this access token.</param>
+ /// <returns>
+ /// A value indicating whether this access token is valid.
+ /// </returns>
+ bool IAccessTokenAnalyzer.TryValidateAccessToken(IDirectedProtocolMessage message, string accessToken, out string user, out HashSet<string> scope) {
+ Contract.Requires<ArgumentNullException>(message != null);
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(accessToken));
+ Contract.Ensures(Contract.Result<bool>() == (Contract.ValueAtReturn<string>(out user) != null));
+
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/IAuthorizationServer.cs b/src/DotNetOpenAuth/OAuth2/IAuthorizationServer.cs
new file mode 100644
index 0000000..883f40c
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/IAuthorizationServer.cs
@@ -0,0 +1,238 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAuthorizationServer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// Provides host-specific authorization server services needed by this library.
+ /// </summary>
+ [ContractClass(typeof(IAuthorizationServerContract))]
+ public interface IAuthorizationServer {
+ /// <summary>
+ /// Gets the store for storeing crypto keys used to symmetrically encrypt and sign authorization codes and refresh tokens.
+ /// </summary>
+ /// <remarks>
+ /// This store should be kept strictly confidential in the authorization server(s)
+ /// and NOT shared with the resource server. Anyone with these secrets can mint
+ /// tokens to essentially grant themselves access to anything they want.
+ /// </remarks>
+ ICryptoKeyStore CryptoKeyStore { get; }
+
+ /// <summary>
+ /// Gets the authorization code nonce store to use to ensure that authorization codes can only be used once.
+ /// </summary>
+ /// <value>The authorization code nonce store.</value>
+ INonceStore VerificationCodeNonceStore { get; }
+
+ /// <summary>
+ /// Gets the crypto service provider with the asymmetric private key to use for signing access tokens.
+ /// </summary>
+ /// <returns>A crypto service provider instance that contains the private key.</returns>
+ /// <value>Must not be null, and must contain the private key.</value>
+ /// <remarks>
+ /// The public key in the private/public key pair will be used by the resource
+ /// servers to validate that the access token is minted by a trusted authorization server.
+ /// </remarks>
+ RSACryptoServiceProvider AccessTokenSigningKey { get; }
+
+ /// <summary>
+ /// Obtains the lifetime for a new access token.
+ /// </summary>
+ /// <param name="accessTokenRequestMessage">
+ /// Details regarding the resources that the access token will grant access to, and the identity of the client
+ /// that will receive that access.
+ /// Based on this information the receiving resource server can be determined and the lifetime of the access
+ /// token can be set based on the sensitivity of the resources.
+ /// </param>
+ /// <returns>
+ /// Receives the lifetime for this access token. Note that within this lifetime, authorization <i>may</i> not be revokable.
+ /// Short lifetimes are recommended (i.e. one hour), particularly when the client is not authenticated or
+ /// the resources to which access is being granted are sensitive.
+ /// </returns>
+ TimeSpan GetAccessTokenLifetime(IAccessTokenRequest accessTokenRequestMessage);
+
+ /// <summary>
+ /// Obtains the encryption key for an access token being created.
+ /// </summary>
+ /// <param name="accessTokenRequestMessage">
+ /// Details regarding the resources that the access token will grant access to, and the identity of the client
+ /// that will receive that access.
+ /// Based on this information the receiving resource server can be determined and the lifetime of the access
+ /// token can be set based on the sensitivity of the resources.
+ /// </param>
+ /// <returns>
+ /// The crypto service provider with the asymmetric public key to use for encrypting access tokens for a specific resource server.
+ /// The caller is responsible to dispose of this value.
+ /// </returns>
+ /// <remarks>
+ /// The caller is responsible to dispose of the returned value.
+ /// </remarks>
+ RSACryptoServiceProvider GetResourceServerEncryptionKey(IAccessTokenRequest accessTokenRequestMessage);
+
+ /// <summary>
+ /// Gets the client with a given identifier.
+ /// </summary>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <returns>The client registration. Never null.</returns>
+ /// <exception cref="ArgumentException">Thrown when no client with the given identifier is registered with this authorization server.</exception>
+ IConsumerDescription GetClient(string clientIdentifier);
+
+ /// <summary>
+ /// Determines whether a described authorization is (still) valid.
+ /// </summary>
+ /// <param name="authorization">The authorization.</param>
+ /// <returns>
+ /// <c>true</c> if the original authorization is still valid; otherwise, <c>false</c>.
+ /// </returns>
+ /// <remarks>
+ /// <para>When establishing that an authorization is still valid,
+ /// it's very important to only match on recorded authorizations that
+ /// meet these criteria:</para>
+ /// 1) The client identifier matches.
+ /// 2) The user account matches.
+ /// 3) The scope on the recorded authorization must include all scopes in the given authorization.
+ /// 4) The date the recorded authorization was issued must be <em>no later</em> that the date the given authorization was issued.
+ /// <para>One possible scenario is where the user authorized a client, later revoked authorization,
+ /// and even later reinstated authorization. This subsequent recorded authorization
+ /// would not satisfy requirement #4 in the above list. This is important because the revocation
+ /// the user went through should invalidate all previously issued tokens as a matter of
+ /// security in the event the user was revoking access in order to sever authorization on a stolen
+ /// account or piece of hardware in which the tokens were stored. </para>
+ /// </remarks>
+ bool IsAuthorizationValid(IAuthorizationDescription authorization);
+ }
+
+ /// <summary>
+ /// Code Contract for the <see cref="IAuthorizationServer"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IAuthorizationServer))]
+ internal abstract class IAuthorizationServerContract : IAuthorizationServer {
+ /// <summary>
+ /// Prevents a default instance of the <see cref="IAuthorizationServerContract"/> class from being created.
+ /// </summary>
+ private IAuthorizationServerContract() {
+ }
+
+ /// <summary>
+ /// Gets the store for storeing crypto keys used to symmetrically encrypt and sign authorization codes and refresh tokens.
+ /// </summary>
+ ICryptoKeyStore IAuthorizationServer.CryptoKeyStore {
+ get {
+ Contract.Ensures(Contract.Result<ICryptoKeyStore>() != null);
+ throw new NotImplementedException();
+ }
+ }
+
+ /// <summary>
+ /// Gets the authorization code nonce store to use to ensure that authorization codes can only be used once.
+ /// </summary>
+ /// <value>The authorization code nonce store.</value>
+ INonceStore IAuthorizationServer.VerificationCodeNonceStore {
+ get {
+ Contract.Ensures(Contract.Result<INonceStore>() != null);
+ throw new NotImplementedException();
+ }
+ }
+
+ /// <summary>
+ /// Gets the crypto service provider with the asymmetric private key to use for signing access tokens.
+ /// </summary>
+ /// <value>
+ /// Must not be null, and must contain the private key.
+ /// </value>
+ /// <returns>A crypto service provider instance that contains the private key.</returns>
+ RSACryptoServiceProvider IAuthorizationServer.AccessTokenSigningKey {
+ get {
+ Contract.Ensures(Contract.Result<RSACryptoServiceProvider>() != null);
+ Contract.Ensures(!Contract.Result<RSACryptoServiceProvider>().PublicOnly);
+ throw new NotImplementedException();
+ }
+ }
+
+ /// <summary>
+ /// Obtains the lifetime for a new access token.
+ /// </summary>
+ /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client
+ /// that will receive that access.
+ /// Based on this information the receiving resource server can be determined and the lifetime of the access
+ /// token can be set based on the sensitivity of the resources.</param>
+ /// <returns>
+ /// Receives the lifetime for this access token. Note that within this lifetime, authorization <i>may</i> not be revokable.
+ /// Short lifetimes are recommended (i.e. one hour), particularly when the client is not authenticated or
+ /// the resources to which access is being granted are sensitive.
+ /// </returns>
+ TimeSpan IAuthorizationServer.GetAccessTokenLifetime(IAccessTokenRequest accessTokenRequestMessage) {
+ Contract.Requires<ArgumentNullException>(accessTokenRequestMessage != null);
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Obtains the encryption key for an access token being created.
+ /// </summary>
+ /// <param name="accessTokenRequestMessage">Details regarding the resources that the access token will grant access to, and the identity of the client
+ /// that will receive that access.
+ /// Based on this information the receiving resource server can be determined and the lifetime of the access
+ /// token can be set based on the sensitivity of the resources.</param>
+ /// <returns>
+ /// The crypto service provider with the asymmetric public key to use for encrypting access tokens for a specific resource server.
+ /// The caller is responsible to dispose of this value.
+ /// </returns>
+ RSACryptoServiceProvider IAuthorizationServer.GetResourceServerEncryptionKey(IAccessTokenRequest accessTokenRequestMessage) {
+ Contract.Requires<ArgumentNullException>(accessTokenRequestMessage != null);
+ Contract.Ensures(Contract.Result<RSACryptoServiceProvider>() != null);
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Gets the client with a given identifier.
+ /// </summary>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <returns>The client registration. Never null.</returns>
+ /// <exception cref="ArgumentException">Thrown when no client with the given identifier is registered with this authorization server.</exception>
+ IConsumerDescription IAuthorizationServer.GetClient(string clientIdentifier) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(clientIdentifier));
+ Contract.Ensures(Contract.Result<IConsumerDescription>() != null);
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Determines whether a described authorization is (still) valid.
+ /// </summary>
+ /// <param name="authorization">The authorization.</param>
+ /// <returns>
+ /// <c>true</c> if the original authorization is still valid; otherwise, <c>false</c>.
+ /// </returns>
+ /// <remarks>
+ /// <para>When establishing that an authorization is still valid,
+ /// it's very important to only match on recorded authorizations that
+ /// meet these criteria:</para>
+ /// 1) The client identifier matches.
+ /// 2) The user account matches.
+ /// 3) The scope on the recorded authorization must include all scopes in the given authorization.
+ /// 4) The date the recorded authorization was issued must be <em>no later</em> that the date the given authorization was issued.
+ /// <para>One possible scenario is where the user authorized a client, later revoked authorization,
+ /// and even later reinstated authorization. This subsequent recorded authorization
+ /// would not satisfy requirement #4 in the above list. This is important because the revocation
+ /// the user went through should invalidate all previously issued tokens as a matter of
+ /// security in the event the user was revoking access in order to sever authorization on a stolen
+ /// account or piece of hardware in which the tokens were stored. </para>
+ /// </remarks>
+ bool IAuthorizationServer.IsAuthorizationValid(IAuthorizationDescription authorization) {
+ Contract.Requires<ArgumentNullException>(authorization != null);
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/IAuthorizationState.cs b/src/DotNetOpenAuth/OAuth2/IAuthorizationState.cs
new file mode 100644
index 0000000..39437ac
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/IAuthorizationState.cs
@@ -0,0 +1,67 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAuthorizationState.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+
+ /// <summary>
+ /// Provides access to a persistent object that tracks the state of an authorization.
+ /// </summary>
+ public interface IAuthorizationState {
+ /// <summary>
+ /// Gets or sets the callback URL used to obtain authorization.
+ /// </summary>
+ /// <value>The callback URL.</value>
+ Uri Callback { get; set; }
+
+ /// <summary>
+ /// Gets or sets the long-lived token used to renew the short-lived <see cref="AccessToken"/>.
+ /// </summary>
+ /// <value>The refresh token.</value>
+ string RefreshToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ string AccessToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token issue date UTC.
+ /// </summary>
+ /// <value>The access token issue date UTC.</value>
+ DateTime? AccessTokenIssueDateUtc { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token UTC expiration date.
+ /// </summary>
+ DateTime? AccessTokenExpirationUtc { get; set; }
+
+ /// <summary>
+ /// Gets the scope the token is (to be) authorized for.
+ /// </summary>
+ /// <value>The scope.</value>
+ HashSet<string> Scope { get; }
+
+ /// <summary>
+ /// Deletes this authorization, including access token and refresh token where applicable.
+ /// </summary>
+ /// <remarks>
+ /// This method is invoked when an authorization attempt fails, is rejected, is revoked, or
+ /// expires and cannot be renewed.
+ /// </remarks>
+ void Delete();
+
+ /// <summary>
+ /// Saves any changes made to this authorization object's properties.
+ /// </summary>
+ /// <remarks>
+ /// This method is invoked after DotNetOpenAuth changes any property.
+ /// </remarks>
+ void SaveChanges();
+ }
+} \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OAuth2/IClientAuthorizationTracker.cs b/src/DotNetOpenAuth/OAuth2/IClientAuthorizationTracker.cs
new file mode 100644
index 0000000..97294e6
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/IClientAuthorizationTracker.cs
@@ -0,0 +1,53 @@
+//-----------------------------------------------------------------------
+// <copyright file="IClientAuthorizationTracker.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Diagnostics.Contracts;
+
+ /// <summary>
+ /// A token manager implemented by some clients to assist in tracking authorization state.
+ /// </summary>
+ [ContractClass(typeof(IClientAuthorizationTrackerContract))]
+ public interface IClientAuthorizationTracker {
+ /// <summary>
+ /// Gets the state of the authorization for a given callback URL and client state.
+ /// </summary>
+ /// <param name="callbackUrl">The callback URL.</param>
+ /// <param name="clientState">State of the client stored at the beginning of an authorization request.</param>
+ /// <returns>The authorization state; may be <c>null</c> if no authorization state matches.</returns>
+ IAuthorizationState GetAuthorizationState(Uri callbackUrl, string clientState);
+ }
+
+ /// <summary>
+ /// Contract class for the <see cref="IClientAuthorizationTracker"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IClientAuthorizationTracker))]
+ internal abstract class IClientAuthorizationTrackerContract : IClientAuthorizationTracker {
+ /// <summary>
+ /// Prevents a default instance of the <see cref="IClientAuthorizationTrackerContract"/> class from being created.
+ /// </summary>
+ private IClientAuthorizationTrackerContract() {
+ }
+
+ #region IClientTokenManager Members
+
+ /// <summary>
+ /// Gets the state of the authorization for a given callback URL and client state.
+ /// </summary>
+ /// <param name="callbackUrl">The callback URL.</param>
+ /// <param name="clientState">State of the client stored at the beginning of an authorization request.</param>
+ /// <returns>
+ /// The authorization state; may be <c>null</c> if no authorization state matches.
+ /// </returns>
+ IAuthorizationState IClientAuthorizationTracker.GetAuthorizationState(Uri callbackUrl, string clientState) {
+ Contract.Requires<ArgumentNullException>(callbackUrl != null);
+ throw new NotImplementedException();
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/IConsumerDescription.cs b/src/DotNetOpenAuth/OAuth2/IConsumerDescription.cs
new file mode 100644
index 0000000..14f3523
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/IConsumerDescription.cs
@@ -0,0 +1,101 @@
+//-----------------------------------------------------------------------
+// <copyright file="IConsumerDescription.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+
+ /// <summary>
+ /// A description of a client from an Authorization Server's point of view.
+ /// </summary>
+ [ContractClass(typeof(IConsumerDescriptionContract))]
+ public interface IConsumerDescription {
+ /// <summary>
+ /// Gets the client secret.
+ /// </summary>
+ string Secret { get; }
+
+ /// <summary>
+ /// Gets the callback to use when an individual authorization request
+ /// does not include an explicit callback URI.
+ /// </summary>
+ /// <value>An absolute URL; or <c>null</c> if none is registered.</value>
+ Uri DefaultCallback { get; }
+
+ /// <summary>
+ /// Determines whether a callback URI included in a client's authorization request
+ /// is among those allowed callbacks for the registered client.
+ /// </summary>
+ /// <param name="callback">The absolute URI the client has requested the authorization result be received at.</param>
+ /// <returns>
+ /// <c>true</c> if the callback URL is allowable for this client; otherwise, <c>false</c>.
+ /// </returns>
+ /// <remarks>
+ /// <para>
+ /// At the point this method is invoked, the identity of the client has <em>not</em>
+ /// been confirmed. To avoid open redirector attacks, the alleged client's identity
+ /// is used to lookup a list of allowable callback URLs to make sure that the callback URL
+ /// the actual client is requesting is one of the expected ones.
+ /// </para>
+ /// <para>
+ /// From OAuth 2.0 section 2.1:
+ /// The authorization server SHOULD require the client to pre-register
+ /// their redirection URI or at least certain components such as the
+ /// scheme, host, port and path. If a redirection URI was registered,
+ /// the authorization server MUST compare any redirection URI received at
+ /// the authorization endpoint with the registered URI.
+ /// </para>
+ /// </remarks>
+ bool IsCallbackAllowed(Uri callback);
+ }
+
+ /// <summary>
+ /// Contract class for the <see cref="IConsumerDescription"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IConsumerDescription))]
+ internal abstract class IConsumerDescriptionContract : IConsumerDescription {
+ #region IConsumerDescription Members
+
+ /// <summary>
+ /// Gets the client secret.
+ /// </summary>
+ /// <value></value>
+ string IConsumerDescription.Secret {
+ get { throw new NotImplementedException(); }
+ }
+
+ /// <summary>
+ /// Gets the callback to use when an individual authorization request
+ /// does not include an explicit callback URI.
+ /// </summary>
+ /// <value>
+ /// An absolute URL; or <c>null</c> if none is registered.
+ /// </value>
+ Uri IConsumerDescription.DefaultCallback {
+ get {
+ Contract.Ensures(Contract.Result<Uri>() == null || Contract.Result<Uri>().IsAbsoluteUri);
+ throw new NotImplementedException();
+ }
+ }
+
+ /// <summary>
+ /// Determines whether a callback URI included in a client's authorization request
+ /// is among those allowed callbacks for the registered client.
+ /// </summary>
+ /// <param name="callback">The requested callback URI.</param>
+ /// <returns>
+ /// <c>true</c> if the callback is allowed; otherwise, <c>false</c>.
+ /// </returns>
+ bool IConsumerDescription.IsCallbackAllowed(Uri callback) {
+ Contract.Requires<ArgumentNullException>(callback != null);
+ Contract.Requires<ArgumentException>(callback.IsAbsoluteUri);
+ throw new NotImplementedException();
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessProtectedResourceRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessProtectedResourceRequest.cs
new file mode 100644
index 0000000..2e94156
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessProtectedResourceRequest.cs
@@ -0,0 +1,73 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessProtectedResourceRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using ChannelElements;
+ using Messaging;
+
+ /// <summary>
+ /// A message that accompanies an HTTP request to a resource server that provides authorization.
+ /// </summary>
+ /// <remarks>
+ /// In its current form, this class only accepts bearer access tokens.
+ /// When support for additional access token types is added, this class should probably be refactored
+ /// into derived types, where each derived type supports a particular access token type.
+ /// </remarks>
+ internal class AccessProtectedResourceRequest : MessageBase, IAuthorizationCarryingRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessProtectedResourceRequest"/> class.
+ /// </summary>
+ /// <param name="recipient">The recipient.</param>
+ /// <param name="version">The version.</param>
+ internal AccessProtectedResourceRequest(Uri recipient, Version version)
+ : base(version, MessageTransport.Direct, recipient) {
+ }
+
+ /// <summary>
+ /// Gets the type of the code or token.
+ /// </summary>
+ /// <value>The type of the code or token.</value>
+ CodeOrTokenType IAuthorizationCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AccessToken; }
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string IAuthorizationCarryingRequest.CodeOrToken {
+ get { return this.AccessToken; }
+ set { this.AccessToken = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get; set; }
+
+ /// <summary>
+ /// Gets the type of the access token.
+ /// </summary>
+ /// <value>
+ /// Always "bearer".
+ /// </value>
+ [MessagePart("token_type", IsRequired = true)]
+ internal string TokenType {
+ get { return Protocol.AccessTokenTypes.Bearer; }
+ }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ [MessagePart("access_token", IsRequired = true)]
+ internal string AccessToken { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs
new file mode 100644
index 0000000..22dad1d
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs
@@ -0,0 +1,94 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenAuthorizationCodeRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// A request from a Client to an Authorization Server to exchange an authorization code for an access token,
+ /// and (at the authorization server's option) a refresh token.
+ /// </summary>
+ internal class AccessTokenAuthorizationCodeRequest : AccessTokenRequestBase, IAuthorizationCarryingRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenAuthorizationCodeRequest"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The Authorization Server's access token endpoint URL.</param>
+ /// <param name="version">The version.</param>
+ internal AccessTokenAuthorizationCodeRequest(Uri tokenEndpoint, Version version)
+ : base(tokenEndpoint, version) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenAuthorizationCodeRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ internal AccessTokenAuthorizationCodeRequest(AuthorizationServerDescription authorizationServer)
+ : this(authorizationServer.TokenEndpoint, authorizationServer.Version) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ }
+
+ /// <summary>
+ /// Gets the type of the code or token.
+ /// </summary>
+ /// <value>The type of the code or token.</value>
+ CodeOrTokenType IAuthorizationCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AuthorizationCode; }
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string IAuthorizationCarryingRequest.CodeOrToken {
+ get { return this.AuthorizationCode; }
+ set { this.AuthorizationCode = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get; set; }
+
+ /// <summary>
+ /// Gets the type of the grant.
+ /// </summary>
+ /// <value>The type of the grant.</value>
+ internal override GrantType GrantType {
+ get { return Messages.GrantType.AuthorizationCode; }
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code previously communicated to the Client
+ /// in <see cref="EndUserAuthorizationSuccessAuthCodeResponse.AuthorizationCode"/>.
+ /// </summary>
+ /// <value>The verification code received from the authorization server.</value>
+ [MessagePart(Protocol.code, IsRequired = true)]
+ internal string AuthorizationCode { get; set; }
+
+ /// <summary>
+ /// Gets or sets the callback URL used in <see cref="EndUserAuthorizationRequest.Callback"/>
+ /// </summary>
+ /// <value>
+ /// The Callback URL used to obtain the Verification Code.
+ /// </value>
+ [MessagePart(Protocol.redirect_uri, IsRequired = true)]
+ internal Uri Callback { get; set; }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ protected override HashSet<string> RequestedScope {
+ get { return ((IAuthorizationCarryingRequest)this).AuthorizationDescription.Scope; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs
new file mode 100644
index 0000000..01e1633
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs
@@ -0,0 +1,41 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenClientCredentialsRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// A request for an access token for a client application that has its
+ /// own (non-user affiliated) client name and password.
+ /// </summary>
+ /// <remarks>
+ /// This is somewhat analogous to 2-legged OAuth.
+ /// </remarks>
+ internal class AccessTokenClientCredentialsRequest : ScopedAccessTokenRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenClientCredentialsRequest"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The authorization server.</param>
+ /// <param name="version">The version.</param>
+ internal AccessTokenClientCredentialsRequest(Uri tokenEndpoint, Version version)
+ : base(tokenEndpoint, version) {
+ this.HttpMethods = HttpDeliveryMethods.PostRequest;
+ }
+
+ /// <summary>
+ /// Gets the type of the grant.
+ /// </summary>
+ /// <value>The type of the grant.</value>
+ internal override GrantType GrantType {
+ get { return Messages.GrantType.ClientCredentials; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenFailedResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenFailedResponse.cs
new file mode 100644
index 0000000..82de341
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenFailedResponse.cs
@@ -0,0 +1,86 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenFailedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Net;
+
+ using Messaging;
+
+ /// <summary>
+ /// A response from the Authorization Server to the Client to indicate that a
+ /// request for an access token renewal failed, probably due to an invalid
+ /// refresh token.
+ /// </summary>
+ /// <remarks>
+ /// This message type is shared by the Web App, Rich App, and Username/Password profiles.
+ /// </remarks>
+ internal class AccessTokenFailedResponse : MessageBase, IHttpDirectResponse {
+ /// <summary>
+ /// A value indicating whether this error response is in result to a request that had invalid client credentials which were supplied in the HTTP Authorization header.
+ /// </summary>
+ private readonly bool invalidClientCredentialsInAuthorizationHeader;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenFailedResponse"/> class.
+ /// </summary>
+ /// <param name="request">The faulty request.</param>
+ internal AccessTokenFailedResponse(AccessTokenRequestBase request)
+ : base(request) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenFailedResponse"/> class.
+ /// </summary>
+ /// <param name="request">The faulty request.</param>
+ /// <param name="invalidClientCredentialsInAuthorizationHeader">A value indicating whether this error response is in result to a request that had invalid client credentials which were supplied in the HTTP Authorization header.</param>
+ internal AccessTokenFailedResponse(AccessTokenRequestBase request, bool invalidClientCredentialsInAuthorizationHeader)
+ : base(request)
+ {
+ this.invalidClientCredentialsInAuthorizationHeader = invalidClientCredentialsInAuthorizationHeader;
+ }
+
+ #region IHttpDirectResponse Members
+
+ /// <summary>
+ /// Gets the HTTP status code that the direct response should be sent with.
+ /// </summary>
+ HttpStatusCode IHttpDirectResponse.HttpStatusCode {
+ get { return this.invalidClientCredentialsInAuthorizationHeader ? HttpStatusCode.Unauthorized : HttpStatusCode.BadRequest; }
+ }
+
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ /// <value>May be an empty collection, but must not be <c>null</c>.</value>
+ WebHeaderCollection IHttpDirectResponse.Headers {
+ get { return new WebHeaderCollection(); }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets or sets the error.
+ /// </summary>
+ /// <value>One of the values given in <see cref="Protocol.AccessTokenRequestErrorCodes"/>.</value>
+ [MessagePart(Protocol.error, IsRequired = true)]
+ internal string Error { get; set; }
+
+ /// <summary>
+ /// Gets or sets a human readable description of the error.
+ /// </summary>
+ /// <value>Human-readable text providing additional information, used to assist in the understanding and resolution of the error that occurred.</value>
+ [MessagePart(Protocol.error_description, IsRequired = false)]
+ internal string ErrorDescription { get; set; }
+
+ /// <summary>
+ /// Gets or sets the location of the web page that describes the error and possible resolution.
+ /// </summary>
+ /// <value>A URI identifying a human-readable web page with information about the error, used to provide the end-user with additional information about the error.</value>
+ [MessagePart(Protocol.error_uri, IsRequired = false)]
+ internal Uri ErrorUri { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRefreshRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRefreshRequest.cs
new file mode 100644
index 0000000..22354e4
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRefreshRequest.cs
@@ -0,0 +1,75 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenRefreshRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// A request from the client to the token endpoint for a new access token
+ /// in exchange for a refresh token that the client has previously obtained.
+ /// </summary>
+ internal class AccessTokenRefreshRequest : ScopedAccessTokenRequest, IAuthorizationCarryingRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenRefreshRequest"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The token endpoint.</param>
+ /// <param name="version">The version.</param>
+ internal AccessTokenRefreshRequest(Uri tokenEndpoint, Version version)
+ : base(tokenEndpoint, version) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenRefreshRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ internal AccessTokenRefreshRequest(AuthorizationServerDescription authorizationServer)
+ : this(authorizationServer.TokenEndpoint, authorizationServer.Version) {
+ }
+
+ /// <summary>
+ /// Gets the type of the code or token.
+ /// </summary>
+ /// <value>The type of the code or token.</value>
+ CodeOrTokenType IAuthorizationCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.RefreshToken; }
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string IAuthorizationCarryingRequest.CodeOrToken {
+ get { return this.RefreshToken; }
+ set { this.RefreshToken = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get; set; }
+
+ /// <summary>
+ /// Gets or sets the refresh token.
+ /// </summary>
+ /// <value>The refresh token.</value>
+ /// <remarks>
+ /// REQUIRED. The refresh token associated with the access token to be refreshed.
+ /// </remarks>
+ [MessagePart(Protocol.refresh_token, IsRequired = true)]
+ internal string RefreshToken { get; set; }
+
+ /// <summary>
+ /// Gets the type of the grant.
+ /// </summary>
+ /// <value>The type of the grant.</value>
+ internal override GrantType GrantType {
+ get { return Messages.GrantType.RefreshToken; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRequestBase.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRequestBase.cs
new file mode 100644
index 0000000..10dc231
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRequestBase.cs
@@ -0,0 +1,78 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenRequestBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Configuration;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// A message sent from the client to the authorization server to exchange a previously obtained grant for an access token.
+ /// </summary>
+ public abstract class AccessTokenRequestBase : AuthenticatedClientRequestBase, IAccessTokenRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenRequestBase"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The Authorization Server's access token endpoint URL.</param>
+ /// <param name="version">The version.</param>
+ protected AccessTokenRequestBase(Uri tokenEndpoint, Version version)
+ : base(tokenEndpoint, version) {
+ this.HttpMethods = HttpDeliveryMethods.PostRequest;
+ }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ HashSet<string> IAccessTokenRequest.Scope {
+ get { return this.RequestedScope; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether the client requesting the access token has authenticated itself.
+ /// </summary>
+ /// <value>
+ /// Always true, because of our base class.
+ /// </value>
+ bool IAccessTokenRequest.ClientAuthenticated {
+ get { return true; }
+ }
+
+ /// <summary>
+ /// Gets the type of the grant.
+ /// </summary>
+ /// <value>The type of the grant.</value>
+ [MessagePart(Protocol.grant_type, IsRequired = true, Encoder = typeof(GrantTypeEncoder))]
+ internal abstract GrantType GrantType { get; }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ protected abstract HashSet<string> RequestedScope { get; }
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ protected override void EnsureValidMessage() {
+ base.EnsureValidMessage();
+ ErrorUtilities.VerifyProtocol(
+ DotNetOpenAuthSection.Configuration.Messaging.RelaxSslRequirements || this.Recipient.IsTransportSecure(),
+ OAuthStrings.HttpsRequired);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs
new file mode 100644
index 0000000..82febe9
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs
@@ -0,0 +1,50 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenResourceOwnerPasswordCredentialsRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A request from a Client to an Authorization Server to exchange the user's username and password for an access token.
+ /// </summary>
+ internal class AccessTokenResourceOwnerPasswordCredentialsRequest : ScopedAccessTokenRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenResourceOwnerPasswordCredentialsRequest"/> class.
+ /// </summary>
+ /// <param name="accessTokenEndpoint">The access token endpoint.</param>
+ /// <param name="version">The protocol version.</param>
+ internal AccessTokenResourceOwnerPasswordCredentialsRequest(Uri accessTokenEndpoint, Version version)
+ : base(accessTokenEndpoint, version) {
+ }
+
+ /// <summary>
+ /// Gets the type of the grant.
+ /// </summary>
+ /// <value>The type of the grant.</value>
+ internal override GrantType GrantType {
+ get { return Messages.GrantType.Password; }
+ }
+
+ /// <summary>
+ /// Gets or sets the user's account username.
+ /// </summary>
+ /// <value>The username on the user's account.</value>
+ [MessagePart(Protocol.username, IsRequired = true)]
+ internal string UserName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user's password.
+ /// </summary>
+ /// <value>The password.</value>
+ [MessagePart(Protocol.password, IsRequired = true)]
+ internal string Password { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenSuccessResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenSuccessResponse.cs
new file mode 100644
index 0000000..5682bf7
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenSuccessResponse.cs
@@ -0,0 +1,99 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenSuccessResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Net;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// A response from the Authorization Server to the Client containing a delegation code
+ /// that the Client should use to obtain an access token.
+ /// </summary>
+ /// <remarks>
+ /// This message type is shared by the Web App, Rich App, and Username/Password profiles.
+ /// </remarks>
+ internal class AccessTokenSuccessResponse : MessageBase, IHttpDirectResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenSuccessResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal AccessTokenSuccessResponse(AccessTokenRequestBase request)
+ : base(request) {
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ this.TokenType = Protocol.AccessTokenTypes.Bearer;
+ }
+
+ /// <summary>
+ /// Gets the HTTP status code that the direct response should be sent with.
+ /// </summary>
+ /// <value>Always HttpStatusCode.OK</value>
+ HttpStatusCode IHttpDirectResponse.HttpStatusCode {
+ get { return HttpStatusCode.OK; }
+ }
+
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ /// <value>May be an empty collection, but must not be <c>null</c>.</value>
+ WebHeaderCollection IHttpDirectResponse.Headers {
+ get {
+ return new WebHeaderCollection
+ {
+ { HttpResponseHeader.CacheControl, "no-store" },
+ };
+ }
+ }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ [MessagePart(Protocol.access_token, IsRequired = true)]
+ public string AccessToken { get; internal set; }
+
+ /// <summary>
+ /// Gets or sets the token type.
+ /// </summary>
+ /// <value>Usually "bearer".</value>
+ /// <remarks>
+ /// Described in OAuth 2.0 section 7.1.
+ /// </remarks>
+ [MessagePart(Protocol.token_type, IsRequired = true)]
+ public string TokenType { get; internal set; }
+
+ /// <summary>
+ /// Gets or sets the lifetime of the access token.
+ /// </summary>
+ /// <value>The lifetime.</value>
+ [MessagePart(Protocol.expires_in, IsRequired = false, Encoder = typeof(TimespanSecondsEncoder))]
+ public TimeSpan? Lifetime { get; internal set; }
+
+ /// <summary>
+ /// Gets or sets the refresh token.
+ /// </summary>
+ /// <value>The refresh token.</value>
+ /// <remarks>
+ /// OPTIONAL. The refresh token used to obtain new access tokens using the same end-user access grant as described in Section 6 (Refreshing an Access Token).
+ /// </remarks>
+ [MessagePart(Protocol.refresh_token, IsRequired = false)]
+ public string RefreshToken { get; internal set; }
+
+ /// <summary>
+ /// Gets the scope of access being requested.
+ /// </summary>
+ /// <value>The scope of the access request expressed as a list of space-delimited strings. The value of the scope parameter is defined by the authorization server. If the value contains multiple space-delimited strings, their order does not matter, and each string adds an additional access range to the requested scope.</value>
+ [MessagePart(Protocol.scope, IsRequired = false, Encoder = typeof(ScopeEncoder))]
+ public HashSet<string> Scope { get; private set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether a refresh token is or should be included in the response.
+ /// </summary>
+ internal bool HasRefreshToken { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AuthenticatedClientRequestBase.cs b/src/DotNetOpenAuth/OAuth2/Messages/AuthenticatedClientRequestBase.cs
new file mode 100644
index 0000000..22f7461
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AuthenticatedClientRequestBase.cs
@@ -0,0 +1,42 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthenticatedClientRequestBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A direct message from the client to the authorization server that includes the client's credentials.
+ /// </summary>
+ public abstract class AuthenticatedClientRequestBase : MessageBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthenticatedClientRequestBase"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The Authorization Server's access token endpoint URL.</param>
+ /// <param name="version">The version.</param>
+ protected AuthenticatedClientRequestBase(Uri tokenEndpoint, Version version)
+ : base(version, MessageTransport.Direct, tokenEndpoint) {
+ }
+
+ /// <summary>
+ /// Gets the client identifier previously obtained from the Authorization Server.
+ /// </summary>
+ /// <value>The client identifier.</value>
+ [MessagePart(Protocol.client_id, IsRequired = true)]
+ public string ClientIdentifier { get; internal set; }
+
+ /// <summary>
+ /// Gets the client secret.
+ /// </summary>
+ /// <value>The client secret.</value>
+ /// <remarks>
+ /// REQUIRED. The client secret as described in Section 2.1 (Client Credentials). OPTIONAL if no client secret was issued.
+ /// </remarks>
+ [MessagePart(Protocol.client_secret, IsRequired = false)]
+ public string ClientSecret { get; internal set; }
+ }
+} \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs
new file mode 100644
index 0000000..5497e1b
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs
@@ -0,0 +1,81 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationFailedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Runtime.Remoting.Messaging;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// The message that an Authorization Server responds to a Client with when the user denies a user authorization request.
+ /// </summary>
+ public class EndUserAuthorizationFailedResponse : MessageBase, IMessageWithClientState {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationFailedResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="version">The protocol version.</param>
+ internal EndUserAuthorizationFailedResponse(Uri clientCallback, Version version)
+ : base(version, MessageTransport.Indirect, clientCallback) {
+ Contract.Requires<ArgumentNullException>(version != null);
+ Contract.Requires<ArgumentNullException>(clientCallback != null);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationFailedResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="request">The authorization request from the user agent on behalf of the client.</param>
+ internal EndUserAuthorizationFailedResponse(Uri clientCallback, EndUserAuthorizationRequest request)
+ : base(((IProtocolMessage)request).Version, MessageTransport.Indirect, clientCallback) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ }
+
+ /// <summary>
+ /// Gets or sets the error.
+ /// </summary>
+ /// <value>
+ /// One of the values given in <see cref="Protocol.EndUserAuthorizationRequestErrorCodes"/>.
+ /// OR a numerical HTTP status code from the 4xx or 5xx
+ /// range, with the exception of the 400 (Bad Request) and
+ /// 401 (Unauthorized) status codes. For example, if the
+ /// service is temporarily unavailable, the authorization
+ /// server MAY return an error response with "error" set to
+ /// "503".
+ /// </value>
+ [MessagePart(Protocol.error, IsRequired = true)]
+ public string Error { get; set; }
+
+ /// <summary>
+ /// Gets or sets a human readable description of the error.
+ /// </summary>
+ /// <value>Human-readable text providing additional information, used to assist in the understanding and resolution of the error that occurred.</value>
+ [MessagePart(Protocol.error_description, IsRequired = false)]
+ public string ErrorDescription { get; set; }
+
+ /// <summary>
+ /// Gets or sets the location of the web page that describes the error and possible resolution.
+ /// </summary>
+ /// <value>A URI identifying a human-readable web page with information about the error, used to provide the end-user with additional information about the error.</value>
+ [MessagePart(Protocol.error_uri, IsRequired = false)]
+ public Uri ErrorUri { get; set; }
+
+ /// <summary>
+ /// Gets or sets some state as provided by the client in the authorization request.
+ /// </summary>
+ /// <value>An opaque value defined by the client.</value>
+ /// <remarks>
+ /// REQUIRED if the Client sent the value in the <see cref="EndUserAuthorizationRequest"/>.
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false)]
+ string IMessageWithClientState.ClientState { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationRequest.cs
new file mode 100644
index 0000000..856fe22
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationRequest.cs
@@ -0,0 +1,118 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Configuration;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// A message sent by a web application Client to the AuthorizationServer
+ /// via the user agent to obtain authorization from the user and prepare
+ /// to issue an access token to the Consumer if permission is granted.
+ /// </summary>
+ [Serializable]
+ public class EndUserAuthorizationRequest : MessageBase, IAccessTokenRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationEndpoint">The Authorization Server's user authorization URL to direct the user to.</param>
+ /// <param name="version">The protocol version.</param>
+ internal EndUserAuthorizationRequest(Uri authorizationEndpoint, Version version)
+ : base(version, MessageTransport.Indirect, authorizationEndpoint) {
+ Contract.Requires<ArgumentNullException>(authorizationEndpoint != null);
+ Contract.Requires<ArgumentNullException>(version != null);
+ this.HttpMethods = HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest;
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ this.ResponseType = EndUserAuthorizationResponseType.AuthorizationCode;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ internal EndUserAuthorizationRequest(AuthorizationServerDescription authorizationServer)
+ : this(authorizationServer.AuthorizationEndpoint, authorizationServer.Version) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ Contract.Requires<ArgumentException>(authorizationServer.Version != null);
+ Contract.Requires<ArgumentException>(authorizationServer.AuthorizationEndpoint != null);
+ }
+
+ /// <summary>
+ /// Gets or sets the grant type that the client expects of the authorization server.
+ /// </summary>
+ /// <value>Always <see cref="EndUserAuthorizationResponseType.AuthorizationCode"/>. Other response types are not supported.</value>
+ [MessagePart(Protocol.response_type, IsRequired = true, Encoder = typeof(EndUserAuthorizationResponseTypeEncoder))]
+ public EndUserAuthorizationResponseType ResponseType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the identifier by which this client is known to the Authorization Server.
+ /// </summary>
+ [MessagePart(Protocol.client_id, IsRequired = true)]
+ public string ClientIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets a value indicating whether the client requesting the access token has authenticated itself.
+ /// </summary>
+ /// <value>
+ /// Always false because authorization requests only include the client_id, without a secret.
+ /// </value>
+ bool IAccessTokenRequest.ClientAuthenticated {
+ get { return false; }
+ }
+
+ /// <summary>
+ /// Gets or sets the callback URL.
+ /// </summary>
+ /// <value>
+ /// An absolute URL to which the Authorization Server will redirect the User back after
+ /// the user has approved the authorization request.
+ /// </value>
+ /// <remarks>
+ /// REQUIRED unless a redirection URI has been established between the client and authorization server via other means. An absolute URI to which the authorization server will redirect the user-agent to when the end-user authorization step is completed. The authorization server MAY require the client to pre-register their redirection URI. The redirection URI MUST NOT include a query component as defined by [RFC3986] (Berners-Lee, T., Fielding, R., and L. Masinter, “Uniform Resource Identifier (URI): Generic Syntax,” January 2005.) section 3 if the state parameter is present.
+ /// </remarks>
+ [MessagePart(Protocol.redirect_uri, IsRequired = false)]
+ public Uri Callback { get; set; }
+
+ /// <summary>
+ /// Gets or sets state of the client that should be sent back with the authorization response.
+ /// </summary>
+ /// <value>
+ /// An opaque value that Clients can use to maintain state associated with this request.
+ /// </value>
+ /// <remarks>
+ /// This data is proprietary to the client and should be considered an opaque string to the
+ /// authorization server.
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false)]
+ public string ClientState { get; set; }
+
+ /// <summary>
+ /// Gets the scope of access being requested.
+ /// </summary>
+ /// <value>The scope of the access request expressed as a list of space-delimited strings. The value of the scope parameter is defined by the authorization server. If the value contains multiple space-delimited strings, their order does not matter, and each string adds an additional access range to the requested scope.</value>
+ [MessagePart(Protocol.scope, IsRequired = false, Encoder = typeof(ScopeEncoder))]
+ public HashSet<string> Scope { get; private set; }
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ protected override void EnsureValidMessage() {
+ base.EnsureValidMessage();
+
+ ErrorUtilities.VerifyProtocol(
+ DotNetOpenAuthSection.Configuration.Messaging.RelaxSslRequirements || this.Recipient.IsTransportSecure(),
+ OAuthStrings.HttpsRequired);
+ ErrorUtilities.VerifyProtocol(this.Callback == null || this.Callback.IsAbsoluteUri, this, OAuthStrings.AbsoluteUriRequired, Protocol.redirect_uri);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationResponseType.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationResponseType.cs
new file mode 100644
index 0000000..815fef6
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationResponseType.cs
@@ -0,0 +1,25 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationResponseType.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+
+ /// <summary>
+ /// An indication of what kind of response the client is requesting from the authorization server
+ /// after the user has granted authorized access.
+ /// </summary>
+ public enum EndUserAuthorizationResponseType {
+ /// <summary>
+ /// An access token should be returned immediately.
+ /// </summary>
+ AccessToken,
+
+ /// <summary>
+ /// An authorization code should be returned, which can later be exchanged for refresh and access tokens.
+ /// </summary>
+ AuthorizationCode,
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs
new file mode 100644
index 0000000..c9373eb
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs
@@ -0,0 +1,121 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationSuccessAccessTokenResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// The message sent by the Authorization Server to the Client via the user agent
+ /// to indicate that user authorization was granted, carrying only an access token,
+ /// and to return the user to the Client where they started their experience.
+ /// </summary>
+ internal class EndUserAuthorizationSuccessAccessTokenResponse : EndUserAuthorizationSuccessResponseBase, IAuthorizationCarryingRequest, IHttpIndirectResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessAccessTokenResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="version">The protocol version.</param>
+ internal EndUserAuthorizationSuccessAccessTokenResponse(Uri clientCallback, Version version)
+ : base(clientCallback, version) {
+ Contract.Requires<ArgumentNullException>(version != null);
+ Contract.Requires<ArgumentNullException>(clientCallback != null);
+ this.TokenType = Protocol.AccessTokenTypes.Bearer;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessAccessTokenResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="request">The authorization request from the user agent on behalf of the client.</param>
+ internal EndUserAuthorizationSuccessAccessTokenResponse(Uri clientCallback, EndUserAuthorizationRequest request)
+ : base(clientCallback, request) {
+ Contract.Requires<ArgumentNullException>(clientCallback != null);
+ Contract.Requires<ArgumentNullException>(request != null);
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ this.TokenType = Protocol.AccessTokenTypes.Bearer;
+ }
+
+ #region IAuthorizationCarryingRequest Members
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string IAuthorizationCarryingRequest.CodeOrToken {
+ get { return this.AccessToken; }
+ set { this.AccessToken = value; }
+ }
+
+ /// <summary>
+ /// Gets the type of the code or token.
+ /// </summary>
+ /// <value>The type of the code or token.</value>
+ CodeOrTokenType IAuthorizationCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AccessToken; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ /// <value></value>
+ IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get; set; }
+
+ #endregion
+
+ #region IHttpIndirectResponse Members
+
+ /// <summary>
+ /// Gets a value indicating whether the payload for the message should be included
+ /// in the redirect fragment instead of the query string or POST entity.
+ /// </summary>
+ bool IHttpIndirectResponse.Include301RedirectPayloadInFragment {
+ get { return true; }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets or sets the token type.
+ /// </summary>
+ /// <value>Usually "bearer".</value>
+ /// <remarks>
+ /// Described in OAuth 2.0 section 7.1.
+ /// </remarks>
+ [MessagePart(Protocol.token_type, IsRequired = true)]
+ public string TokenType { get; internal set; }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ [MessagePart(Protocol.access_token, IsRequired = true)]
+ public string AccessToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the scope of the <see cref="AccessToken"/> if one is given; otherwise the scope of the authorization code.
+ /// </summary>
+ /// <value>The scope.</value>
+ [MessagePart(Protocol.scope, IsRequired = false, Encoder = typeof(ScopeEncoder))]
+ public new ICollection<string> Scope {
+ get { return base.Scope; }
+ protected set { base.Scope = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the lifetime of the authorization.
+ /// </summary>
+ /// <value>The lifetime.</value>
+ [MessagePart(Protocol.expires_in, IsRequired = false, Encoder = typeof(TimespanSecondsEncoder))]
+ internal TimeSpan? Lifetime { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs
new file mode 100644
index 0000000..65965ef
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs
@@ -0,0 +1,76 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationSuccessAuthCodeResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Diagnostics.Contracts;
+
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// The message sent by the Authorization Server to the Client via the user agent
+ /// to indicate that user authorization was granted, carrying an authorization code and possibly an access token,
+ /// and to return the user to the Client where they started their experience.
+ /// </summary>
+ internal class EndUserAuthorizationSuccessAuthCodeResponse : EndUserAuthorizationSuccessResponseBase, IAuthorizationCarryingRequest {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessAuthCodeResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="version">The protocol version.</param>
+ internal EndUserAuthorizationSuccessAuthCodeResponse(Uri clientCallback, Version version)
+ : base(clientCallback, version) {
+ Contract.Requires<ArgumentNullException>(version != null);
+ Contract.Requires<ArgumentNullException>(clientCallback != null);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessAuthCodeResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="request">The authorization request from the user agent on behalf of the client.</param>
+ internal EndUserAuthorizationSuccessAuthCodeResponse(Uri clientCallback, EndUserAuthorizationRequest request)
+ : base(clientCallback, request) {
+ Contract.Requires<ArgumentNullException>(clientCallback != null);
+ Contract.Requires<ArgumentNullException>(request != null);
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ }
+
+ #region IAuthorizationCarryingRequest Members
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string IAuthorizationCarryingRequest.CodeOrToken {
+ get { return this.AuthorizationCode; }
+ set { this.AuthorizationCode = value; }
+ }
+
+ /// <summary>
+ /// Gets the type of the code or token.
+ /// </summary>
+ /// <value>The type of the code or token.</value>
+ CodeOrTokenType IAuthorizationCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AuthorizationCode; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription IAuthorizationCarryingRequest.AuthorizationDescription { get; set; }
+
+ #endregion
+
+ /// <summary>
+ /// Gets or sets the authorization code.
+ /// </summary>
+ /// <value>The authorization code.</value>
+ [MessagePart(Protocol.code, IsRequired = true)]
+ internal string AuthorizationCode { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs
new file mode 100644
index 0000000..d3c32e8
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs
@@ -0,0 +1,69 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationSuccessResponseBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Security.Cryptography;
+
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// The message sent by the Authorization Server to the Client via the user agent
+ /// to indicate that user authorization was granted, and to return the user
+ /// to the Client where they started their experience.
+ /// </summary>
+ public abstract class EndUserAuthorizationSuccessResponseBase : MessageBase, IMessageWithClientState {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessResponseBase"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="version">The protocol version.</param>
+ internal EndUserAuthorizationSuccessResponseBase(Uri clientCallback, Version version)
+ : base(version, MessageTransport.Indirect, clientCallback) {
+ Contract.Requires<ArgumentNullException>(version != null);
+ Contract.Requires<ArgumentNullException>(clientCallback != null);
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="EndUserAuthorizationSuccessResponseBase"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The URL to redirect to so the client receives the message. This may not be built into the request message if the client pre-registered the URL with the authorization server.</param>
+ /// <param name="request">The authorization request from the user agent on behalf of the client.</param>
+ internal EndUserAuthorizationSuccessResponseBase(Uri clientCallback, EndUserAuthorizationRequest request)
+ : base(request, clientCallback) {
+ Contract.Requires<ArgumentNullException>(clientCallback != null);
+ Contract.Requires<ArgumentNullException>(request != null);
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ this.Scope.ResetContents(request.Scope);
+ }
+
+ /// <summary>
+ /// Gets or sets some state as provided by the client in the authorization request.
+ /// </summary>
+ /// <value>An opaque value defined by the client.</value>
+ /// <remarks>
+ /// REQUIRED if the Client sent the value in the <see cref="EndUserAuthorizationRequest"/>.
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false)]
+ string IMessageWithClientState.ClientState { get; set; }
+
+ /// <summary>
+ /// Gets or sets the scope of the <see cref="AccessToken"/> if one is given; otherwise the scope of the authorization code.
+ /// </summary>
+ /// <value>The scope.</value>
+ public ICollection<string> Scope { get; protected set; }
+
+ /// <summary>
+ /// Gets or sets the authorizing user's account name.
+ /// </summary>
+ internal string AuthorizingUsername { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/GrantType.cs b/src/DotNetOpenAuth/OAuth2/Messages/GrantType.cs
new file mode 100644
index 0000000..4580a7f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/GrantType.cs
@@ -0,0 +1,42 @@
+//-----------------------------------------------------------------------
+// <copyright file="GrantType.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ /// <summary>
+ /// The types of authorizations that a client can use to obtain
+ /// a refresh token and/or an access token.
+ /// </summary>
+ internal enum GrantType {
+ /// <summary>
+ /// The client is providing the authorization code previously obtained from an end user authorization response.
+ /// </summary>
+ AuthorizationCode,
+
+ /// <summary>
+ /// The client is providing the end user's username and password to the authorization server.
+ /// </summary>
+ Password,
+
+ /// <summary>
+ /// The client is providing an assertion it obtained from another source.
+ /// </summary>
+ Assertion,
+
+ /// <summary>
+ /// The client is providing a refresh token.
+ /// </summary>
+ RefreshToken,
+
+ /// <summary>
+ /// No authorization to access a user's data has been given. The client is requesting
+ /// an access token authorized for its own private data. This fits the classic OAuth 1.0(a) "2-legged OAuth" scenario.
+ /// </summary>
+ /// <remarks>
+ /// When requesting an access token using the none access grant type (no access grant is included), the client is requesting access to the protected resources under its control, or those of another resource owner which has been previously arranged with the authorization server (the method of which is beyond the scope of this specification).
+ /// </remarks>
+ ClientCredentials,
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/IAccessTokenRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/IAccessTokenRequest.cs
new file mode 100644
index 0000000..7246beb
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/IAccessTokenRequest.cs
@@ -0,0 +1,37 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAccessTokenRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// A request from a client that should be responded to directly with an access token.
+ /// </summary>
+ public interface IAccessTokenRequest : IMessage {
+ /// <summary>
+ /// Gets a value indicating whether the client requesting the access token has authenticated itself.
+ /// </summary>
+ /// <value>
+ /// <c>false</c> for implicit grant requests; otherwise, <c>true</c>.
+ /// </value>
+ bool ClientAuthenticated { get; }
+
+ /// <summary>
+ /// Gets the identifier of the client authorized to access protected data.
+ /// </summary>
+ string ClientIdentifier { get; }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ HashSet<string> Scope { get; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/IMessageWithClientState.cs b/src/DotNetOpenAuth/OAuth2/Messages/IMessageWithClientState.cs
new file mode 100644
index 0000000..fa371ae
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/IMessageWithClientState.cs
@@ -0,0 +1,21 @@
+//-----------------------------------------------------------------------
+// <copyright file="IMessageWithClientState.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A message carrying client state the authorization server should preserve on behalf of the client
+ /// during an authorization.
+ /// </summary>
+ internal interface IMessageWithClientState : IProtocolMessage {
+ /// <summary>
+ /// Gets or sets the state of the client.
+ /// </summary>
+ /// <value>The state of the client.</value>
+ string ClientState { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/MessageBase.cs b/src/DotNetOpenAuth/OAuth2/Messages/MessageBase.cs
new file mode 100644
index 0000000..e390d6e
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/MessageBase.cs
@@ -0,0 +1,239 @@
+//-----------------------------------------------------------------------
+// <copyright file="MessageBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A common message base class for OAuth messages.
+ /// </summary>
+ [Serializable]
+ public class MessageBase : IDirectedProtocolMessage, IDirectResponseProtocolMessage {
+ /// <summary>
+ /// A dictionary to contain extra message data.
+ /// </summary>
+ private Dictionary<string, string> extraData = new Dictionary<string, string>();
+
+ /// <summary>
+ /// The originating request.
+ /// </summary>
+ private IDirectedProtocolMessage originatingRequest;
+
+ /// <summary>
+ /// The backing field for the <see cref="IMessage.Version"/> property.
+ /// </summary>
+ private Version version;
+
+ /// <summary>
+ /// A value indicating whether this message is a direct or indirect message.
+ /// </summary>
+ private MessageTransport messageTransport;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MessageBase"/> class
+ /// that is used for direct response messages.
+ /// </summary>
+ /// <param name="version">The version.</param>
+ protected MessageBase(Version version) {
+ Contract.Requires<ArgumentNullException>(version != null);
+ this.messageTransport = MessageTransport.Direct;
+ this.version = version;
+ this.HttpMethods = HttpDeliveryMethods.GetRequest;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MessageBase"/> class.
+ /// </summary>
+ /// <param name="request">The originating request.</param>
+ /// <param name="recipient">The recipient of the directed message. Null if not applicable.</param>
+ protected MessageBase(IDirectedProtocolMessage request, Uri recipient = null) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ this.originatingRequest = request;
+ this.messageTransport = request.Transport;
+ this.version = request.Version;
+ this.Recipient = recipient;
+ this.HttpMethods = HttpDeliveryMethods.GetRequest;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MessageBase"/> class
+ /// that is used for directed messages.
+ /// </summary>
+ /// <param name="version">The version.</param>
+ /// <param name="messageTransport">The message transport.</param>
+ /// <param name="recipient">The recipient.</param>
+ protected MessageBase(Version version, MessageTransport messageTransport, Uri recipient) {
+ Contract.Requires<ArgumentNullException>(version != null);
+ Contract.Requires<ArgumentNullException>(recipient != null);
+
+ this.version = version;
+ this.messageTransport = messageTransport;
+ this.Recipient = recipient;
+ this.HttpMethods = HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.PostRequest;
+ }
+
+ #region IMessage Properties
+
+ /// <summary>
+ /// Gets the version of the protocol or extension this message is prepared to implement.
+ /// </summary>
+ /// <remarks>
+ /// Implementations of this interface should ensure that this property never returns null.
+ /// </remarks>
+ Version IMessage.Version {
+ get { return this.Version; }
+ }
+
+ /// <summary>
+ /// Gets the extra, non-standard Protocol parameters included in the message.
+ /// </summary>
+ /// <value></value>
+ /// <remarks>
+ /// Implementations of this interface should ensure that this property never returns null.
+ /// </remarks>
+ public IDictionary<string, string> ExtraData {
+ get { return this.extraData; }
+ }
+
+ #endregion
+
+ #region IProtocolMessage Members
+
+ /// <summary>
+ /// Gets the level of protection this message requires.
+ /// </summary>
+ /// <value><see cref="MessageProtections.None"/></value>
+ MessageProtections IProtocolMessage.RequiredProtection {
+ get { return RequiredProtection; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether this is a direct or indirect message.
+ /// </summary>
+ /// <value></value>
+ MessageTransport IProtocolMessage.Transport {
+ get { return this.Transport; }
+ }
+
+ #endregion
+
+ #region IDirectedProtocolMessage Members
+
+ /// <summary>
+ /// Gets the preferred method of transport for the message.
+ /// </summary>
+ /// <remarks>
+ /// For indirect messages this will likely be GET+POST, which both can be simulated in the user agent:
+ /// the GET with a simple 301 Redirect, and the POST with an HTML form in the response with javascript
+ /// to automate submission.
+ /// </remarks>
+ HttpDeliveryMethods IDirectedProtocolMessage.HttpMethods {
+ get { return this.HttpMethods; }
+ }
+
+ /// <summary>
+ /// Gets the URL of the intended receiver of this message.
+ /// </summary>
+ Uri IDirectedProtocolMessage.Recipient {
+ get { return this.Recipient; }
+ }
+
+ #endregion
+
+ #region IDirectResponseProtocolMessage Members
+
+ /// <summary>
+ /// Gets the originating request message that caused this response to be formed.
+ /// </summary>
+ IDirectedProtocolMessage IDirectResponseProtocolMessage.OriginatingRequest {
+ get { return this.OriginatingRequest; }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets the level of protection this message requires.
+ /// </summary>
+ protected static MessageProtections RequiredProtection {
+ get { return MessageProtections.None; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether this is a direct or indirect message.
+ /// </summary>
+ protected MessageTransport Transport {
+ get { return this.messageTransport; }
+ }
+
+ /// <summary>
+ /// Gets the version of the protocol or extension this message is prepared to implement.
+ /// </summary>
+ protected Version Version {
+ get { return this.version; }
+ }
+
+ /// <summary>
+ /// Gets or sets the preferred method of transport for the message.
+ /// </summary>
+ /// <remarks>
+ /// For indirect messages this will likely be GET+POST, which both can be simulated in the user agent:
+ /// the GET with a simple 301 Redirect, and the POST with an HTML form in the response with javascript
+ /// to automate submission.
+ /// </remarks>
+ protected HttpDeliveryMethods HttpMethods { get; set; }
+
+ /// <summary>
+ /// Gets the originating request message that caused this response to be formed.
+ /// </summary>
+ protected IDirectedProtocolMessage OriginatingRequest {
+ get { return this.originatingRequest; }
+ }
+
+ /// <summary>
+ /// Gets the URL of the intended receiver of this message.
+ /// </summary>
+ protected Uri Recipient { get; private set; }
+
+ #region IMessage Methods
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ void IMessage.EnsureValidMessage() {
+ this.EnsureValidMessage();
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Checks the message state for conformity to the protocol specification
+ /// and throws an exception if the message is invalid.
+ /// </summary>
+ /// <remarks>
+ /// <para>Some messages have required fields, or combinations of fields that must relate to each other
+ /// in specialized ways. After deserializing a message, this method checks the state of the
+ /// message to see if it conforms to the protocol.</para>
+ /// <para>Note that this property should <i>not</i> check signatures or perform any state checks
+ /// outside this scope of this particular message.</para>
+ /// </remarks>
+ /// <exception cref="ProtocolException">Thrown if the message is invalid.</exception>
+ protected virtual void EnsureValidMessage() {
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/OAuth 2 Messages.cd b/src/DotNetOpenAuth/OAuth2/Messages/OAuth 2 Messages.cd
new file mode 100644
index 0000000..05e3ad9
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/OAuth 2 Messages.cd
@@ -0,0 +1,164 @@
+<?xml version="1.0" encoding="utf-8"?>
+<ClassDiagram MajorVersion="1" MinorVersion="1">
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.MessageBase" Collapsed="true">
+ <Position X="0.5" Y="0.5" Width="1.5" />
+ <TypeIdentifier>
+ <HashCode>IAAMACQAQAAAgAkAAAAIAAYACgAAIAAAIACAACAAAIA=</HashCode>
+ <FileName>OAuth2\Messages\MessageBase.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenAuthorizationCodeRequest" Collapsed="true">
+ <Position X="8.5" Y="6.75" Width="3" />
+ <TypeIdentifier>
+ <HashCode>ACAAEAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAgAAAATAA=</HashCode>
+ <FileName>OAuth2\Messages\AccessTokenAuthorizationCodeRequest.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenClientCredentialsRequest" Collapsed="true">
+ <Position X="8.5" Y="8.75" Width="2.75" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\AccessTokenClientCredentialsRequest.cs</FileName>
+ </TypeIdentifier>
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenFailedResponse" Collapsed="true">
+ <Position X="3.25" Y="8.5" Width="2.25" />
+ <TypeIdentifier>
+ <HashCode>AAAAAIAAAAAAAQAAAABAAAQAAAAAAAEQAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\AccessTokenFailedResponse.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenRefreshRequest" Collapsed="true">
+ <Position X="8.5" Y="9.75" Width="2.25" />
+ <TypeIdentifier>
+ <HashCode>AAAAEAAAQAAAAAAAAAAAAAAQAAAAAAAAAAAgAAAABAA=</HashCode>
+ <FileName>OAuth2\Messages\AccessTokenRefreshRequest.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenRequestBase" Collapsed="true">
+ <Position X="5.75" Y="5.75" Width="2" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAQABAAAAAAAAAAAAQAAAAAAAAAAAAAAAACAA=</HashCode>
+ <FileName>OAuth2\Messages\AccessTokenRequestBase.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenResourceOwnerPasswordCredentialsRequest" Collapsed="true">
+ <Position X="8.5" Y="10.5" Width="4" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAAAAAAAAAAAAAAAAQAAAAAAACAQAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\AccessTokenResourceOwnerPasswordCredentialsRequest.cs</FileName>
+ </TypeIdentifier>
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessTokenSuccessResponse" Collapsed="true">
+ <Position X="3.25" Y="7.5" Width="2.25" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAQAAAACAAAAAAAAQAEAAAAAAQAEAAAAAAAgA=</HashCode>
+ <FileName>OAuth2\Messages\AccessTokenSuccessResponse.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AuthenticatedClientRequestBase" Collapsed="true">
+ <Position X="3.25" Y="5.25" Width="2.25" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAwAAAAAAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\AuthenticatedClientRequestBase.cs</FileName>
+ </TypeIdentifier>
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationFailedResponse" Collapsed="true">
+ <Position X="3.25" Y="4.5" Width="2.75" />
+ <TypeIdentifier>
+ <HashCode>AAAAAIAAAAAAAQAAAAAAAAgAAAAAAAEAAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\EndUserAuthorizationFailedResponse.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationRequest" Collapsed="true">
+ <Position X="3.25" Y="0.5" Width="2.25" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAQABAACAAAAAAAACAAAQAAAQAAAAAAAAAQAA=</HashCode>
+ <FileName>OAuth2\Messages\EndUserAuthorizationRequest.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationSuccessAccessTokenResponse" Collapsed="true">
+ <Position X="6.25" Y="3.75" Width="3.75" />
+ <TypeIdentifier>
+ <HashCode>AAAAEAAAAAAAAAAAAAAAAAACEAAAAAAAAAAgAAAABgA=</HashCode>
+ <FileName>OAuth2\Messages\EndUserAuthorizationSuccessAccessTokenResponse.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationSuccessAuthCodeResponse" Collapsed="true">
+ <Position X="6.25" Y="2.5" Width="3.5" />
+ <TypeIdentifier>
+ <HashCode>ACAAEAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAgAAAABAA=</HashCode>
+ <FileName>OAuth2\Messages\EndUserAuthorizationSuccessAuthCodeResponse.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationSuccessResponseBase" Collapsed="true">
+ <Position X="3.25" Y="1.5" Width="2.75" />
+ <TypeIdentifier>
+ <HashCode>AAACAAAAAAAAACAAAAAAAAgAAAAAAAAAAEAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\EndUserAuthorizationSuccessResponseBase.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.AccessProtectedResourceRequest" Collapsed="true">
+ <Position X="3.25" Y="9.75" Width="2.5" />
+ <TypeIdentifier>
+ <HashCode>AAAAEAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAgAAAABgA=</HashCode>
+ <FileName>OAuth2\Messages\AccessProtectedResourceRequest.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.UnauthorizedResponse" Collapsed="true">
+ <Position X="3.25" Y="10.75" Width="2" />
+ <TypeIdentifier>
+ <HashCode>AUABAAAAAAAAACAAAAAAAAQIAAAAAAAQAAAAAAAAABA=</HashCode>
+ <FileName>OAuth2\Messages\UnauthorizedResponse.cs</FileName>
+ </TypeIdentifier>
+ <Lollipop Position="0.2" />
+ </Class>
+ <Class Name="DotNetOpenAuth.OAuth2.Messages.ScopedAccessTokenRequest" Collapsed="true">
+ <Position X="6.75" Y="7.75" Width="2.25" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAAAAAAACAA=</HashCode>
+ <FileName>OAuth2\Messages\ScopedAccessTokenRequest.cs</FileName>
+ </TypeIdentifier>
+ </Class>
+ <Interface Name="DotNetOpenAuth.OAuth2.Messages.IMessageWithClientState">
+ <Position X="11.5" Y="0.5" Width="2" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\IMessageWithClientState.cs</FileName>
+ </TypeIdentifier>
+ </Interface>
+ <Interface Name="DotNetOpenAuth.OAuth2.ChannelElements.IAuthorizationCarryingRequest">
+ <Position X="11.75" Y="2" Width="2.5" />
+ <TypeIdentifier>
+ <HashCode>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAEAAAAA=</HashCode>
+ <FileName>OAuth2\ChannelElements\IAuthorizationCarryingRequest.cs</FileName>
+ </TypeIdentifier>
+ </Interface>
+ <Enum Name="DotNetOpenAuth.OAuth2.Messages.EndUserAuthorizationResponseType">
+ <Position X="8" Y="0.5" Width="3" />
+ <TypeIdentifier>
+ <HashCode>ACAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\EndUserAuthorizationResponseType.cs</FileName>
+ </TypeIdentifier>
+ </Enum>
+ <Enum Name="DotNetOpenAuth.OAuth2.Messages.GrantType">
+ <Position X="6.25" Y="0.5" Width="1.5" />
+ <TypeIdentifier>
+ <HashCode>ACAAAAAAQAAAAAQAAgAAAAAAAAAAAAACAAAAAAAAAAA=</HashCode>
+ <FileName>OAuth2\Messages\GrantType.cs</FileName>
+ </TypeIdentifier>
+ </Enum>
+ <Font Name="Segoe UI" Size="9" />
+</ClassDiagram> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/ScopedAccessTokenRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/ScopedAccessTokenRequest.cs
new file mode 100644
index 0000000..5568b1c
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/ScopedAccessTokenRequest.cs
@@ -0,0 +1,41 @@
+//-----------------------------------------------------------------------
+// <copyright file="ScopedAccessTokenRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Collections.Generic;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// An access token request that includes a scope parameter.
+ /// </summary>
+ internal abstract class ScopedAccessTokenRequest : AccessTokenRequestBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ScopedAccessTokenRequest"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The Authorization Server's access token endpoint URL.</param>
+ /// <param name="version">The version.</param>
+ internal ScopedAccessTokenRequest(Uri tokenEndpoint, Version version)
+ : base(tokenEndpoint, version) {
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ }
+
+ /// <summary>
+ /// Gets the set of scopes the Client would like the access token to provide access to.
+ /// </summary>
+ /// <value>A set of scopes. Never null.</value>
+ [MessagePart(Protocol.scope, IsRequired = false, Encoder = typeof(ScopeEncoder))]
+ internal HashSet<string> Scope { get; private set; }
+
+ /// <summary>
+ /// Gets the scope of operations the client is allowed to invoke.
+ /// </summary>
+ protected override HashSet<string> RequestedScope {
+ get { return this.Scope; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/UnauthorizedResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/UnauthorizedResponse.cs
new file mode 100644
index 0000000..d79c00b
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/UnauthorizedResponse.cs
@@ -0,0 +1,115 @@
+//-----------------------------------------------------------------------
+// <copyright file="UnauthorizedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ using System.Diagnostics.Contracts;
+ using System.Net;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A direct response that is simply a 401 Unauthorized with an
+ /// WWW-Authenticate: OAuth header.
+ /// </summary>
+ internal class UnauthorizedResponse : MessageBase, IHttpDirectResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UnauthorizedResponse"/> class.
+ /// </summary>
+ /// <param name="exception">The exception.</param>
+ /// <param name="version">The protocol version.</param>
+ internal UnauthorizedResponse(ProtocolException exception, Version version = null)
+ : base(version ?? Protocol.Default.Version) {
+ Contract.Requires<ArgumentNullException>(exception != null);
+ this.ErrorMessage = exception.Message;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UnauthorizedResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal UnauthorizedResponse(IDirectedProtocolMessage request)
+ : base(request) {
+ this.Realm = "Service";
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UnauthorizedResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ /// <param name="exception">The exception.</param>
+ internal UnauthorizedResponse(IDirectedProtocolMessage request, ProtocolException exception)
+ : this(request) {
+ Contract.Requires<ArgumentNullException>(exception != null);
+ this.ErrorMessage = exception.Message;
+ }
+
+ #region IHttpDirectResponse Members
+
+ /// <summary>
+ /// Gets the HTTP status code that the direct response should be sent with.
+ /// </summary>
+ HttpStatusCode IHttpDirectResponse.HttpStatusCode {
+ get { return HttpStatusCode.Unauthorized; }
+ }
+
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ /// <value>May be an empty collection, but must not be <c>null</c>.</value>
+ WebHeaderCollection IHttpDirectResponse.Headers {
+ get {
+ return new WebHeaderCollection() {
+ { HttpResponseHeader.WwwAuthenticate, Protocol.BearerHttpAuthorizationScheme },
+ };
+ }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets or sets the error message.
+ /// </summary>
+ /// <value>The error message.</value>
+ [MessagePart("error")]
+ internal string ErrorMessage { get; set; }
+
+ /// <summary>
+ /// Gets or sets the realm.
+ /// </summary>
+ /// <value>The realm.</value>
+ [MessagePart("realm")]
+ internal string Realm { get; set; }
+
+ /// <summary>
+ /// Gets or sets the scope.
+ /// </summary>
+ /// <value>The scope.</value>
+ [MessagePart("scope")]
+ internal string Scope { get; set; }
+
+ /// <summary>
+ /// Gets or sets the algorithms.
+ /// </summary>
+ /// <value>The algorithms.</value>
+ [MessagePart("algorithms")]
+ internal string Algorithms { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user endpoint.
+ /// </summary>
+ /// <value>The user endpoint.</value>
+ [MessagePart("user-uri")]
+ internal Uri UserEndpoint { get; set; }
+
+ /// <summary>
+ /// Gets or sets the token endpoint.
+ /// </summary>
+ /// <value>The token endpoint.</value>
+ [MessagePart("token-uri")]
+ internal Uri TokenEndpoint { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/OAuthStrings.Designer.cs b/src/DotNetOpenAuth/OAuth2/OAuthStrings.Designer.cs
new file mode 100644
index 0000000..9ea12ab
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/OAuthStrings.Designer.cs
@@ -0,0 +1,144 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.225
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+
+
+ /// <summary>
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ /// </summary>
+ // This class was auto-generated by the StronglyTypedResourceBuilder
+ // class via a tool like ResGen or Visual Studio.
+ // To add or remove a member, edit your .ResX file then rerun ResGen
+ // with the /str option, or rebuild your VS project.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class OAuthStrings {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal OAuthStrings() {
+ }
+
+ /// <summary>
+ /// Returns the cached ResourceManager instance used by this class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager {
+ get {
+ if (object.ReferenceEquals(resourceMan, null)) {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DotNetOpenAuth.OAuth2.OAuthStrings", typeof(OAuthStrings).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ /// <summary>
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The value for message part &quot;{0}&quot; must be an absolute URI..
+ /// </summary>
+ internal static string AbsoluteUriRequired {
+ get {
+ return ResourceManager.GetString("AbsoluteUriRequired", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The requested access scope (&quot;{0}&quot;) exceeds the grant scope (&quot;{1}&quot;)..
+ /// </summary>
+ internal static string AccessScopeExceedsGrantScope {
+ get {
+ return ResourceManager.GetString("AccessScopeExceedsGrantScope", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Failed to obtain access token. Authorization Server reports reason: {0}.
+ /// </summary>
+ internal static string CannotObtainAccessTokenWithReason {
+ get {
+ return ResourceManager.GetString("CannotObtainAccessTokenWithReason", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The callback URL ({0}) is not allowed for this client..
+ /// </summary>
+ internal static string ClientCallbackDisallowed {
+ get {
+ return ResourceManager.GetString("ClientCallbackDisallowed", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to This message can only be sent over HTTPS..
+ /// </summary>
+ internal static string HttpsRequired {
+ get {
+ return ResourceManager.GetString("HttpsRequired", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Failed to obtain access token due to invalid Client Identifier or Client Secret..
+ /// </summary>
+ internal static string InvalidClientCredentials {
+ get {
+ return ResourceManager.GetString("InvalidClientCredentials", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to No callback URI was available for this request..
+ /// </summary>
+ internal static string NoCallback {
+ get {
+ return ResourceManager.GetString("NoCallback", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Refresh tokens should not be granted without the request including an access grant..
+ /// </summary>
+ internal static string NoGrantNoRefreshToken {
+ get {
+ return ResourceManager.GetString("NoGrantNoRefreshToken", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Individual scopes may not contain spaces..
+ /// </summary>
+ internal static string ScopesMayNotContainSpaces {
+ get {
+ return ResourceManager.GetString("ScopesMayNotContainSpaces", resourceCulture);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/OAuthStrings.resx b/src/DotNetOpenAuth/OAuth2/OAuthStrings.resx
new file mode 100644
index 0000000..fc2f2d2
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/OAuthStrings.resx
@@ -0,0 +1,147 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <data name="AbsoluteUriRequired" xml:space="preserve">
+ <value>The value for message part "{0}" must be an absolute URI.</value>
+ </data>
+ <data name="AccessScopeExceedsGrantScope" xml:space="preserve">
+ <value>The requested access scope ("{0}") exceeds the grant scope ("{1}").</value>
+ </data>
+ <data name="CannotObtainAccessTokenWithReason" xml:space="preserve">
+ <value>Failed to obtain access token. Authorization Server reports reason: {0}</value>
+ </data>
+ <data name="ClientCallbackDisallowed" xml:space="preserve">
+ <value>The callback URL ({0}) is not allowed for this client.</value>
+ </data>
+ <data name="HttpsRequired" xml:space="preserve">
+ <value>This message can only be sent over HTTPS.</value>
+ </data>
+ <data name="InvalidClientCredentials" xml:space="preserve">
+ <value>Failed to obtain access token due to invalid Client Identifier or Client Secret.</value>
+ </data>
+ <data name="NoCallback" xml:space="preserve">
+ <value>No callback URI was available for this request.</value>
+ </data>
+ <data name="NoGrantNoRefreshToken" xml:space="preserve">
+ <value>Refresh tokens should not be granted without the request including an access grant.</value>
+ </data>
+ <data name="ScopesMayNotContainSpaces" xml:space="preserve">
+ <value>Individual scopes may not contain spaces.</value>
+ </data>
+</root> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OAuth2/OAuthUtilities.cs b/src/DotNetOpenAuth/OAuth2/OAuthUtilities.cs
new file mode 100644
index 0000000..c2b2f5f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/OAuthUtilities.cs
@@ -0,0 +1,123 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthUtilities.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Globalization;
+ using System.Linq;
+ using System.Net;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// Some common utility methods for OAuth 2.0.
+ /// </summary>
+ public static class OAuthUtilities {
+ /// <summary>
+ /// The <see cref="StringComparer"/> instance to use when comparing scope equivalence.
+ /// </summary>
+ public static readonly StringComparer ScopeStringComparer = StringComparer.Ordinal;
+
+ /// <summary>
+ /// The delimiter between scope elements.
+ /// </summary>
+ private static char[] scopeDelimiter = new char[] { ' ' };
+
+ /// <summary>
+ /// The characters that may appear in an access token that is included in an HTTP Authorization header.
+ /// </summary>
+ /// <remarks>
+ /// This is defined in OAuth 2.0 DRAFT 10, section 5.1.1. (http://tools.ietf.org/id/draft-ietf-oauth-v2-10.html#authz-header)
+ /// </remarks>
+ private static string accessTokenAuthorizationHeaderAllowedCharacters = MessagingUtilities.UppercaseLetters +
+ MessagingUtilities.LowercaseLetters +
+ MessagingUtilities.Digits +
+ @"!#$%&'()*+-./:<=>?@[]^_`{|}~\,;";
+
+ /// <summary>
+ /// Determines whether one given scope is a subset of another scope.
+ /// </summary>
+ /// <param name="requestedScope">The requested scope, which may be a subset of <paramref name="grantedScope"/>.</param>
+ /// <param name="grantedScope">The granted scope, the suspected superset.</param>
+ /// <returns>
+ /// <c>true</c> if all the elements that appear in <paramref name="requestedScope"/> also appear in <paramref name="grantedScope"/>;
+ /// <c>false</c> otherwise.
+ /// </returns>
+ public static bool IsScopeSubset(string requestedScope, string grantedScope) {
+ if (string.IsNullOrEmpty(requestedScope)) {
+ return true;
+ }
+
+ if (string.IsNullOrEmpty(grantedScope)) {
+ return false;
+ }
+
+ var requestedScopes = new HashSet<string>(requestedScope.Split(scopeDelimiter, StringSplitOptions.RemoveEmptyEntries));
+ var grantedScopes = new HashSet<string>(grantedScope.Split(scopeDelimiter, StringSplitOptions.RemoveEmptyEntries));
+ return requestedScopes.IsSubsetOf(grantedScopes);
+ }
+
+ /// <summary>
+ /// Identifies individual scope elements
+ /// </summary>
+ /// <param name="scope">The space-delimited list of scopes.</param>
+ /// <returns>A set of individual scopes, with any duplicates removed.</returns>
+ public static HashSet<string> SplitScopes(string scope) {
+ if (string.IsNullOrEmpty(scope)) {
+ return new HashSet<string>();
+ }
+
+ return new HashSet<string>(scope.Split(scopeDelimiter, StringSplitOptions.RemoveEmptyEntries), ScopeStringComparer);
+ }
+
+ /// <summary>
+ /// Serializes a set of scopes as a space-delimited list.
+ /// </summary>
+ /// <param name="scopes">The scopes to serialize.</param>
+ /// <returns>A space-delimited list.</returns>
+ public static string JoinScopes(HashSet<string> scopes) {
+ Contract.Requires<ArgumentNullException>(scopes != null);
+ return string.Join(" ", scopes.ToArray());
+ }
+
+ /// <summary>
+ /// Authorizes an HTTP request using an OAuth 2.0 access token in an HTTP Authorization header.
+ /// </summary>
+ /// <param name="request">The request to authorize.</param>
+ /// <param name="accessToken">The access token previously obtained from the Authorization Server.</param>
+ internal static void AuthorizeWithBearerToken(this HttpWebRequest request, string accessToken) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(accessToken));
+ ErrorUtilities.VerifyProtocol(accessToken.All(ch => accessTokenAuthorizationHeaderAllowedCharacters.IndexOf(ch) >= 0), "The access token contains characters that must not appear in the HTTP Authorization header.");
+
+ request.Headers[HttpRequestHeader.Authorization] = string.Format(
+ CultureInfo.InvariantCulture,
+ Protocol.BearerHttpAuthorizationHeaderFormat,
+ accessToken);
+ }
+
+ /// <summary>
+ /// Gets information about the client with a given identifier.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <returns>The client information. Never null.</returns>
+ internal static IConsumerDescription GetClientOrThrow(this IAuthorizationServer authorizationServer, string clientIdentifier) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(clientIdentifier));
+ Contract.Ensures(Contract.Result<IConsumerDescription>() != null);
+
+ try {
+ return authorizationServer.GetClient(clientIdentifier);
+ } catch (KeyNotFoundException ex) {
+ throw ErrorUtilities.Wrap(ex, OAuth.OAuthStrings.ConsumerOrTokenSecretNotFound);
+ } catch (ArgumentException ex) {
+ throw ErrorUtilities.Wrap(ex, OAuth.OAuthStrings.ConsumerOrTokenSecretNotFound);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Protocol.cs b/src/DotNetOpenAuth/OAuth2/Protocol.cs
new file mode 100644
index 0000000..3cb8253
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Protocol.cs
@@ -0,0 +1,355 @@
+// <auto-generated/> // disable StyleCop on this file
+//-----------------------------------------------------------------------
+// <copyright file="Protocol.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+
+ /// <summary>
+ /// An enumeration of the OAuth protocol versions supported by this library.
+ /// </summary>
+ public enum ProtocolVersion {
+ /// <summary>
+ /// The OAuth 2.0 specification.
+ /// </summary>
+ V20,
+ }
+
+ /// <summary>
+ /// Protocol constants for OAuth 2.0.
+ /// </summary>
+ internal class Protocol {
+ /// <summary>
+ /// The HTTP authorization scheme "Bearer";
+ /// </summary>
+ internal const string BearerHttpAuthorizationScheme = "Bearer";
+
+ /// <summary>
+ /// The HTTP authorization scheme "Bearer ";
+ /// </summary>
+ internal const string BearerHttpAuthorizationSchemeWithTrailingSpace = BearerHttpAuthorizationScheme + " ";
+
+ /// <summary>
+ /// The format of the HTTP Authorization header value that authorizes OAuth 2.0 requests using bearer access tokens.
+ /// </summary>
+ internal const string BearerHttpAuthorizationHeaderFormat = BearerHttpAuthorizationSchemeWithTrailingSpace + "{0}";
+
+ /// <summary>
+ /// The name of the parameter whose value is an OAuth 2.0 bearer access token, as it is defined
+ /// in a URL-encoded POST entity or URL query string.
+ /// </summary>
+ internal const string BearerTokenEncodedUrlParameterName = "access_token";
+
+ /// <summary>
+ /// The "type" string.
+ /// </summary>
+ internal const string type = "type";
+
+ /// <summary>
+ /// The "state" string.
+ /// </summary>
+ internal const string state = "state";
+
+ /// <summary>
+ /// The "redirect_uri_mismatch" string.
+ /// </summary>
+ internal const string redirect_uri_mismatch = "redirect_uri_mismatch";
+
+ /// <summary>
+ /// The "bad_verification_code" string.
+ /// </summary>
+ internal const string bad_verification_code = "bad_verification_code";
+
+ /// <summary>
+ /// The "incorrect_client_credentials" string.
+ /// </summary>
+ internal const string incorrect_client_credentials = "incorrect_client_credentials";
+
+ /// <summary>
+ /// The "unauthorized_client" string.
+ /// </summary>
+ internal const string unauthorized_client = "unauthorized_client";
+
+ /// <summary>
+ /// The "authorization_expired" string.
+ /// </summary>
+ internal const string authorization_expired = "authorization_expired";
+
+ /// <summary>
+ /// The "redirect_uri" string.
+ /// </summary>
+ internal const string redirect_uri = "redirect_uri";
+
+ /// <summary>
+ /// The "client_id" string.
+ /// </summary>
+ internal const string client_id = "client_id";
+
+ /// <summary>
+ /// The "scope" string.
+ /// </summary>
+ internal const string scope = "scope";
+
+ /// <summary>
+ /// The "immediate" string.
+ /// </summary>
+ internal const string immediate = "immediate";
+
+ /// <summary>
+ /// The "client_secret" string.
+ /// </summary>
+ internal const string client_secret = "client_secret";
+
+ /// <summary>
+ /// The "code" string.
+ /// </summary>
+ internal const string code = "code";
+
+ /// <summary>
+ /// The "user_code" string.
+ /// </summary>
+ internal const string user_code = "user_code";
+
+ /// <summary>
+ /// The "verification_uri" string.
+ /// </summary>
+ internal const string verification_uri = "verification_uri";
+
+ /// <summary>
+ /// The "interval" string.
+ /// </summary>
+ internal const string interval = "interval";
+
+ /// <summary>
+ /// The "error" string.
+ /// </summary>
+ internal const string error = "error";
+
+ /// <summary>
+ /// The "access_token" string.
+ /// </summary>
+ internal const string access_token = "access_token";
+
+ /// <summary>
+ /// The "access_token_secret" string.
+ /// </summary>
+ internal const string access_token_secret = "access_token_secret";
+
+ /// <summary>
+ /// The "token_type" string.
+ /// </summary>
+ internal const string token_type = "token_type";
+
+ /// <summary>
+ /// The "refresh_token" string.
+ /// </summary>
+ internal const string refresh_token = "refresh_token";
+
+ /// <summary>
+ /// The "expires_in" string.
+ /// </summary>
+ internal const string expires_in = "expires_in";
+
+ /// <summary>
+ /// The "expired_delegation_code" string.
+ /// </summary>
+ internal const string expired_delegation_code = "expired_delegation_code";
+
+ /// <summary>
+ /// The "username" string.
+ /// </summary>
+ internal const string username = "username";
+
+ /// <summary>
+ /// The "password" string.
+ /// </summary>
+ internal const string password = "password";
+
+ /// <summary>
+ /// The "format" string.
+ /// </summary>
+ internal const string format = "format";
+
+ /// <summary>
+ /// The "assertion" string.
+ /// </summary>
+ internal const string assertion = "assertion";
+
+ /// <summary>
+ /// The "assertion_type" string.
+ /// </summary>
+ internal const string assertion_type = "assertion_type";
+
+ /// <summary>
+ /// The "user_denied" string.
+ /// </summary>
+ internal const string user_denied = "user_denied";
+
+ /// <summary>
+ /// Gets the <see cref="Protocol"/> instance with values initialized for V1.0 of the protocol.
+ /// </summary>
+ internal static readonly Protocol V20 = new Protocol {
+ Version = new Version(2, 0),
+ ProtocolVersion = ProtocolVersion.V20,
+ };
+
+ /// <summary>
+ /// A list of all supported OAuth versions, in order starting from newest version.
+ /// </summary>
+ internal static readonly List<Protocol> AllVersions = new List<Protocol>() { V20 };
+
+ /// <summary>
+ /// The default (or most recent) supported version of the OpenID protocol.
+ /// </summary>
+ internal static readonly Protocol Default = AllVersions[0];
+
+ /// <summary>
+ /// The "error_uri" string.
+ /// </summary>
+ public const string error_uri = "error_uri";
+
+ /// <summary>
+ /// The "error_description" string.
+ /// </summary>
+ internal const string error_description = "error_description";
+
+ /// <summary>
+ /// The "response_type" string.
+ /// </summary>
+ internal const string response_type = "response_type";
+
+ /// <summary>
+ /// The "grant_type" string.
+ /// </summary>
+ internal const string grant_type = "grant_type";
+
+ /// <summary>
+ /// Gets or sets the OAuth 2.0 version represented by this instance.
+ /// </summary>
+ /// <value>The version.</value>
+ internal Version Version { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the OAuth 2.0 version represented by this instance.
+ /// </summary>
+ /// <value>The protocol version.</value>
+ internal ProtocolVersion ProtocolVersion { get; private set; }
+
+ /// <summary>
+ /// Gets the OAuth Protocol instance to use for the given version.
+ /// </summary>
+ /// <param name="version">The OAuth version to get.</param>
+ /// <returns>A matching <see cref="Protocol"/> instance.</returns>
+ public static Protocol Lookup(ProtocolVersion version) {
+ switch (version) {
+ case ProtocolVersion.V20: return Protocol.V20;
+ default: throw new ArgumentOutOfRangeException("version");
+ }
+ }
+
+ /// <summary>
+ /// Values for the "response_type" parameter.
+ /// </summary>
+ internal static class ResponseTypes
+ {
+ /// <summary>
+ /// The string "code".
+ /// </summary>
+ internal const string Code = "code";
+
+ /// <summary>
+ /// The string "token".
+ /// </summary>
+ internal const string Token = "token";
+ }
+
+ internal static class GrantTypes
+ {
+ internal const string AuthorizationCode = "authorization_code";
+
+ internal const string Password = "password";
+
+ internal const string Assertion = "assertion";
+
+ internal const string RefreshToken = "refresh_token";
+
+ internal const string ClientCredentials = "client_credentials";
+ }
+
+ /// <summary>
+ /// Error codes that an authorization server can return to a client in response to a malformed or unsupported access token request.
+ /// </summary>
+ internal static class AccessTokenRequestErrorCodes
+ {
+ /// <summary>
+ /// The request is missing a required parameter, includes an unknown parameter or parameter value, repeats a parameter, includes multiple credentials, utilizes more than one mechanism for authenticating the client, or is otherwise malformed.
+ /// </summary>
+ internal const string InvalidRequest = "invalid_request";
+
+ /// <summary>
+ /// The client is not authorized to use the access grant type provided.
+ /// </summary>
+ internal const string UnauthorizedClient = "unauthorized_client";
+
+ /// <summary>
+ /// The resource owner or authorization server denied the request.
+ /// </summary>
+ internal const string AccessDenied = "access_denied";
+
+ /// <summary>
+ /// The authorization server does not support obtaining an access token using this method.
+ /// </summary>
+ internal const string UnsupportedGrantType = "unsupported_response_type";
+
+ /// <summary>
+ /// The requested scope is invalid, unknown, malformed, or exceeds the previously granted scope.
+ /// </summary>
+ internal const string InvalidScope = "invalid_scope";
+ }
+
+ /// <summary>
+ /// Error codes that an authorization server can return to a client in response to a malformed or unsupported end user authorization request.
+ /// </summary>
+ internal static class EndUserAuthorizationRequestErrorCodes
+ {
+ /// <summary>
+ /// The request is missing a required parameter, includes an unknown parameter or parameter value, or is otherwise malformed.
+ /// </summary>
+ internal const string InvalidRequest = "invalid_request";
+
+ /// <summary>
+ /// The client is not authorized to use the requested response type.
+ /// </summary>
+ internal const string UnauthorizedClient = "unauthorized_client";
+
+ /// <summary>
+ /// The end-user or authorization server denied the request.
+ /// </summary>
+ internal const string AccessDenied = "access_denied";
+
+ /// <summary>
+ /// The requested response type is not supported by the authorization server.
+ /// </summary>
+ internal const string UnsupportedResponseType = "unsupported_response_type";
+
+ /// <summary>
+ /// The requested scope is invalid, unknown, or malformed.
+ /// </summary>
+ internal const string InvalidScope = "invalid_scope";
+ }
+
+ /// <summary>
+ /// Recognized access token types.
+ /// </summary>
+ internal static class AccessTokenTypes {
+ /// <summary>
+ /// The "bearer" token type.
+ /// </summary>
+ internal const string Bearer = "bearer";
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ResourceServer.cs b/src/DotNetOpenAuth/OAuth2/ResourceServer.cs
new file mode 100644
index 0000000..a5baef0
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ResourceServer.cs
@@ -0,0 +1,136 @@
+//-----------------------------------------------------------------------
+// <copyright file="ResourceServer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.CodeAnalysis;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Net;
+ using System.Security.Principal;
+ using System.ServiceModel.Channels;
+ using System.Text;
+ using System.Text.RegularExpressions;
+ using System.Web;
+ using ChannelElements;
+ using Messages;
+ using Messaging;
+
+ /// <summary>
+ /// Provides services for validating OAuth access tokens.
+ /// </summary>
+ public class ResourceServer {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ResourceServer"/> class.
+ /// </summary>
+ /// <param name="accessTokenAnalyzer">The access token analyzer.</param>
+ public ResourceServer(IAccessTokenAnalyzer accessTokenAnalyzer) {
+ Contract.Requires<ArgumentNullException>(accessTokenAnalyzer != null);
+
+ this.AccessTokenAnalyzer = accessTokenAnalyzer;
+ this.Channel = new OAuth2ResourceServerChannel();
+ }
+
+ /// <summary>
+ /// Gets the access token analyzer.
+ /// </summary>
+ /// <value>The access token analyzer.</value>
+ public IAccessTokenAnalyzer AccessTokenAnalyzer { get; private set; }
+
+ /// <summary>
+ /// Gets the channel.
+ /// </summary>
+ /// <value>The channel.</value>
+ internal OAuth2ResourceServerChannel Channel { get; private set; }
+
+ /// <summary>
+ /// Discovers what access the client should have considering the access token in the current request.
+ /// </summary>
+ /// <param name="userName">The name on the account the client has access to.</param>
+ /// <param name="scope">The set of operations the client is authorized for.</param>
+ /// <returns>An error to return to the client if access is not authorized; <c>null</c> if access is granted.</returns>
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Try pattern")]
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")]
+ public OutgoingWebResponse VerifyAccess(out string userName, out HashSet<string> scope) {
+ return this.VerifyAccess(this.Channel.GetRequestFromContext(), out userName, out scope);
+ }
+
+ /// <summary>
+ /// Discovers what access the client should have considering the access token in the current request.
+ /// </summary>
+ /// <param name="httpRequestInfo">The HTTP request info.</param>
+ /// <param name="userName">The name on the account the client has access to.</param>
+ /// <param name="scope">The set of operations the client is authorized for.</param>
+ /// <returns>
+ /// An error to return to the client if access is not authorized; <c>null</c> if access is granted.
+ /// </returns>
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")]
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Try pattern")]
+ public virtual OutgoingWebResponse VerifyAccess(HttpRequestInfo httpRequestInfo, out string userName, out HashSet<string> scope) {
+ Contract.Requires<ArgumentNullException>(httpRequestInfo != null);
+
+ AccessProtectedResourceRequest request = null;
+ try {
+ if (this.Channel.TryReadFromRequest<AccessProtectedResourceRequest>(httpRequestInfo, out request)) {
+ if (this.AccessTokenAnalyzer.TryValidateAccessToken(request, request.AccessToken, out userName, out scope)) {
+ // No errors to return.
+ return null;
+ }
+
+ throw ErrorUtilities.ThrowProtocol("Bad access token");
+ } else {
+ var response = new UnauthorizedResponse(new ProtocolException("Missing access token"));
+
+ userName = null;
+ scope = null;
+ return this.Channel.PrepareResponse(response);
+ }
+ } catch (ProtocolException ex) {
+ var response = request != null ? new UnauthorizedResponse(request, ex) : new UnauthorizedResponse(ex);
+
+ userName = null;
+ scope = null;
+ return this.Channel.PrepareResponse(response);
+ }
+ }
+
+ /// <summary>
+ /// Discovers what access the client should have considering the access token in the current request.
+ /// </summary>
+ /// <param name="httpRequestInfo">The HTTP request info.</param>
+ /// <param name="principal">The principal that contains the user and roles that the access token is authorized for.</param>
+ /// <returns>
+ /// An error to return to the client if access is not authorized; <c>null</c> if access is granted.
+ /// </returns>
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")]
+ public virtual OutgoingWebResponse VerifyAccess(HttpRequestInfo httpRequestInfo, out IPrincipal principal) {
+ string username;
+ HashSet<string> scope;
+ var result = this.VerifyAccess(httpRequestInfo, out username, out scope);
+ principal = result == null ? new OAuth.ChannelElements.OAuthPrincipal(username, scope != null ? scope.ToArray() : new string[0]) : null;
+ return result;
+ }
+
+ /// <summary>
+ /// Discovers what access the client should have considering the access token in the current request.
+ /// </summary>
+ /// <param name="request">HTTP details from an incoming WCF message.</param>
+ /// <param name="requestUri">The URI of the WCF service endpoint.</param>
+ /// <param name="principal">The principal that contains the user and roles that the access token is authorized for.</param>
+ /// <returns>
+ /// An error to return to the client if access is not authorized; <c>null</c> if access is granted.
+ /// </returns>
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "Try pattern")]
+ [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "2#", Justification = "Try pattern")]
+ public virtual OutgoingWebResponse VerifyAccess(HttpRequestMessageProperty request, Uri requestUri, out IPrincipal principal) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<ArgumentNullException>(requestUri != null);
+
+ return this.VerifyAccess(new HttpRequestInfo(request, requestUri), out principal);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/StandardAccessTokenAnalyzer.cs b/src/DotNetOpenAuth/OAuth2/StandardAccessTokenAnalyzer.cs
new file mode 100644
index 0000000..1f59e52
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/StandardAccessTokenAnalyzer.cs
@@ -0,0 +1,66 @@
+//-----------------------------------------------------------------------
+// <copyright file="StandardAccessTokenAnalyzer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Security.Cryptography;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// An access token reader that understands DotNetOpenAuth authorization server issued tokens.
+ /// </summary>
+ public class StandardAccessTokenAnalyzer : IAccessTokenAnalyzer {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="StandardAccessTokenAnalyzer"/> class.
+ /// </summary>
+ /// <param name="authorizationServerPublicSigningKey">The crypto service provider with the authorization server public signing key.</param>
+ /// <param name="resourceServerPrivateEncryptionKey">The crypto service provider with the resource server private encryption key.</param>
+ public StandardAccessTokenAnalyzer(RSACryptoServiceProvider authorizationServerPublicSigningKey, RSACryptoServiceProvider resourceServerPrivateEncryptionKey) {
+ Contract.Requires<ArgumentNullException>(authorizationServerPublicSigningKey != null);
+ Contract.Requires<ArgumentNullException>(resourceServerPrivateEncryptionKey != null);
+ Contract.Requires<ArgumentException>(!resourceServerPrivateEncryptionKey.PublicOnly);
+ this.AuthorizationServerPublicSigningKey = authorizationServerPublicSigningKey;
+ this.ResourceServerPrivateEncryptionKey = resourceServerPrivateEncryptionKey;
+ }
+
+ /// <summary>
+ /// Gets the authorization server public signing key.
+ /// </summary>
+ /// <value>The authorization server public signing key.</value>
+ public RSACryptoServiceProvider AuthorizationServerPublicSigningKey { get; private set; }
+
+ /// <summary>
+ /// Gets the resource server private encryption key.
+ /// </summary>
+ /// <value>The resource server private encryption key.</value>
+ public RSACryptoServiceProvider ResourceServerPrivateEncryptionKey { get; private set; }
+
+ /// <summary>
+ /// Reads an access token to find out what data it authorizes access to.
+ /// </summary>
+ /// <param name="message">The message carrying the access token.</param>
+ /// <param name="accessToken">The access token.</param>
+ /// <param name="user">The user whose data is accessible with this access token.</param>
+ /// <param name="scope">The scope of access authorized by this access token.</param>
+ /// <returns>
+ /// A value indicating whether this access token is valid.
+ /// </returns>
+ /// <remarks>
+ /// This method also responsible to throw a <see cref="ProtocolException"/> or return
+ /// <c>false</c> when the access token is expired, invalid, or from an untrusted authorization server.
+ /// </remarks>
+ public virtual bool TryValidateAccessToken(IDirectedProtocolMessage message, string accessToken, out string user, out HashSet<string> scope) {
+ var accessTokenFormatter = AccessToken.CreateFormatter(this.AuthorizationServerPublicSigningKey, this.ResourceServerPrivateEncryptionKey);
+ var token = accessTokenFormatter.Deserialize(message, accessToken);
+ user = token.User;
+ scope = new HashSet<string>(token.Scope, OAuthUtilities.ScopeStringComparer);
+ return true;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/UserAgentClient.cs b/src/DotNetOpenAuth/OAuth2/UserAgentClient.cs
new file mode 100644
index 0000000..65c5898
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/UserAgentClient.cs
@@ -0,0 +1,108 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserAgentClient.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// The OAuth client for the user-agent flow, providing services for installed apps
+ /// and in-browser Javascript widgets.
+ /// </summary>
+ public class UserAgentClient : ClientBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserAgentClient"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The token issuer.</param>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <param name="clientSecret">The client secret.</param>
+ public UserAgentClient(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, string clientSecret = null)
+ : base(authorizationServer, clientIdentifier, clientSecret) {
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserAgentClient"/> class.
+ /// </summary>
+ /// <param name="authorizationEndpoint">The authorization endpoint.</param>
+ public UserAgentClient(Uri authorizationEndpoint)
+ : base(new AuthorizationServerDescription { AuthorizationEndpoint = authorizationEndpoint }) {
+ Contract.Requires<ArgumentNullException>(authorizationEndpoint != null);
+ }
+
+ /// <summary>
+ /// Generates a URL that the user's browser can be directed to in order to authorize
+ /// this client to access protected data at some resource server.
+ /// </summary>
+ /// <param name="scope">The scope of authorized access requested.</param>
+ /// <returns>A fully-qualified URL suitable to initiate the authorization flow.</returns>
+ public Uri RequestUserAuthorization(IEnumerable<string> scope = null) {
+ var authorization = new AuthorizationState(scope);
+ return this.RequestUserAuthorization(authorization);
+ }
+
+ /// <summary>
+ /// Generates a URL that the user's browser can be directed to in order to authorize
+ /// this client to access protected data at some resource server.
+ /// </summary>
+ /// <param name="authorization">The authorization state that is tracking this particular request. Optional.</param>
+ /// <returns>A fully-qualified URL suitable to initiate the authorization flow.</returns>
+ public Uri RequestUserAuthorization(IAuthorizationState authorization) {
+ Contract.Requires<ArgumentNullException>(authorization != null);
+ Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientIdentifier));
+
+ if (authorization.Callback == null) {
+ authorization.Callback = new Uri("http://localhost/");
+ }
+
+ var request = new EndUserAuthorizationRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ Callback = authorization.Callback,
+ };
+ request.Scope.ResetContents(authorization.Scope);
+
+ return this.Channel.PrepareResponse(request).GetDirectUriRequest(this.Channel);
+ }
+
+ /// <summary>
+ /// Scans the incoming request for an authorization response message.
+ /// </summary>
+ /// <param name="actualRedirectUrl">The actual URL of the incoming HTTP request.</param>
+ /// <param name="authorizationState">The authorization.</param>
+ /// <returns>The granted authorization, or <c>null</c> if the incoming HTTP request did not contain an authorization server response or authorization was rejected.</returns>
+ public IAuthorizationState ProcessUserAuthorization(Uri actualRedirectUrl, IAuthorizationState authorizationState = null) {
+ Contract.Requires<ArgumentNullException>(actualRedirectUrl != null);
+
+ if (authorizationState == null) {
+ authorizationState = new AuthorizationState();
+ }
+
+ var carrier = new HttpRequestInfo("GET", actualRedirectUrl, actualRedirectUrl.PathAndQuery, new System.Net.WebHeaderCollection(), null);
+ IDirectedProtocolMessage response = this.Channel.ReadFromRequest(carrier);
+ if (response == null) {
+ return null;
+ }
+
+ EndUserAuthorizationSuccessAccessTokenResponse accessTokenSuccess;
+ EndUserAuthorizationSuccessAuthCodeResponse authCodeSuccess;
+ EndUserAuthorizationFailedResponse failure;
+ if ((accessTokenSuccess = response as EndUserAuthorizationSuccessAccessTokenResponse) != null) {
+ UpdateAuthorizationWithResponse(authorizationState, accessTokenSuccess);
+ } else if ((authCodeSuccess = response as EndUserAuthorizationSuccessAuthCodeResponse) != null) {
+ this.UpdateAuthorizationWithResponse(authorizationState, authCodeSuccess);
+ } else if ((failure = response as EndUserAuthorizationFailedResponse) != null) {
+ authorizationState.Delete();
+ return null;
+ }
+
+ return authorizationState;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/WebServerClient.cs b/src/DotNetOpenAuth/OAuth2/WebServerClient.cs
new file mode 100644
index 0000000..fb084d1
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/WebServerClient.cs
@@ -0,0 +1,130 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebServerClient.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Net;
+ using System.Text;
+ using System.Web;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <summary>
+ /// An OAuth 2.0 consumer designed for web applications.
+ /// </summary>
+ public class WebServerClient : ClientBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebServerClient"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ /// <param name="clientIdentifier">The client identifier.</param>
+ /// <param name="clientSecret">The client secret.</param>
+ public WebServerClient(AuthorizationServerDescription authorizationServer, string clientIdentifier = null, string clientSecret = null)
+ : base(authorizationServer, clientIdentifier, clientSecret) {
+ }
+
+ /// <summary>
+ /// Gets or sets an optional component that gives you greater control to record and influence the authorization process.
+ /// </summary>
+ /// <value>The authorization tracker.</value>
+ public IClientAuthorizationTracker AuthorizationTracker { get; set; }
+
+ /// <summary>
+ /// Prepares a request for user authorization from an authorization server.
+ /// </summary>
+ /// <param name="scope">The scope of authorized access requested.</param>
+ /// <param name="state">The state of the client that should be sent back with the authorization response.</param>
+ /// <param name="returnTo">The URL the authorization server should redirect the browser (typically on this site) to when the authorization is completed. If null, the current request's URL will be used.</param>
+ public void RequestUserAuthorization(IEnumerable<string> scope = null, string state = null, Uri returnTo = null) {
+ var authorizationState = new AuthorizationState(scope) {
+ Callback = returnTo,
+ };
+ this.PrepareRequestUserAuthorization(authorizationState, state).Respond();
+ }
+
+ /// <summary>
+ /// Prepares a request for user authorization from an authorization server.
+ /// </summary>
+ /// <param name="scopes">The scope of authorized access requested.</param>
+ /// <param name="state">The state of the client that should be sent back with the authorization response.</param>
+ /// <returns>The authorization request.</returns>
+ public OutgoingWebResponse PrepareRequestUserAuthorization(IEnumerable<string> scopes = null, string state = null) {
+ var authorizationState = new AuthorizationState(scopes);
+ return this.PrepareRequestUserAuthorization(authorizationState, state);
+ }
+
+ /// <summary>
+ /// Prepares a request for user authorization from an authorization server.
+ /// </summary>
+ /// <param name="authorization">The authorization state to associate with this particular request.</param>
+ /// <param name="state">The state of the client that should be sent back with the authorization response.</param>
+ /// <returns>The authorization request.</returns>
+ public OutgoingWebResponse PrepareRequestUserAuthorization(IAuthorizationState authorization, string state = null) {
+ Contract.Requires<ArgumentNullException>(authorization != null);
+ Contract.Requires<InvalidOperationException>(authorization.Callback != null || (HttpContext.Current != null && HttpContext.Current.Request != null), MessagingStrings.HttpContextRequired);
+ Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientIdentifier));
+ Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
+
+ if (authorization.Callback == null) {
+ authorization.Callback = this.Channel.GetRequestFromContext().UrlBeforeRewriting
+ .StripMessagePartsFromQueryString(this.Channel.MessageDescriptions.Get(typeof(EndUserAuthorizationSuccessResponseBase), Protocol.Default.Version))
+ .StripMessagePartsFromQueryString(this.Channel.MessageDescriptions.Get(typeof(EndUserAuthorizationFailedResponse), Protocol.Default.Version));
+ authorization.SaveChanges();
+ }
+
+ var request = new EndUserAuthorizationRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ Callback = authorization.Callback,
+ ClientState = state,
+ };
+ request.Scope.ResetContents(authorization.Scope);
+
+ return this.Channel.PrepareResponse(request);
+ }
+
+ /// <summary>
+ /// Processes the authorization response from an authorization server, if available.
+ /// </summary>
+ /// <param name="request">The incoming HTTP request that may carry an authorization response.</param>
+ /// <returns>The authorization state that contains the details of the authorization.</returns>
+ public IAuthorizationState ProcessUserAuthorization(HttpRequestInfo request = null) {
+ Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientIdentifier));
+ Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientSecret));
+
+ if (request == null) {
+ request = this.Channel.GetRequestFromContext();
+ }
+
+ IMessageWithClientState response;
+ if (this.Channel.TryReadFromRequest<IMessageWithClientState>(request, out response)) {
+ Uri callback = MessagingUtilities.StripMessagePartsFromQueryString(request.UrlBeforeRewriting, this.Channel.MessageDescriptions.Get(response));
+ IAuthorizationState authorizationState;
+ if (this.AuthorizationTracker != null) {
+ authorizationState = this.AuthorizationTracker.GetAuthorizationState(callback, response.ClientState);
+ ErrorUtilities.VerifyProtocol(authorizationState != null, "Unexpected OAuth authorization response received with callback and client state that does not match an expected value.");
+ } else {
+ authorizationState = new AuthorizationState { Callback = callback };
+ }
+ var success = response as EndUserAuthorizationSuccessAuthCodeResponse;
+ var failure = response as EndUserAuthorizationFailedResponse;
+ ErrorUtilities.VerifyProtocol(success != null || failure != null, MessagingStrings.UnexpectedMessageReceivedOfMany);
+ if (success != null) {
+ UpdateAuthorizationWithResponse(authorizationState, success);
+ } else { // failure
+ Logger.OAuth.Info("User refused to grant the requested authorization at the Authorization Server.");
+ authorizationState.Delete();
+ }
+
+ return authorizationState;
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Association.cs b/src/DotNetOpenAuth/OpenId/Association.cs
index 3c7e89f..5b97ad4 100644
--- a/src/DotNetOpenAuth/OpenId/Association.cs
+++ b/src/DotNetOpenAuth/OpenId/Association.cs
@@ -14,6 +14,7 @@ namespace DotNetOpenAuth.OpenId {
using System.Text;
using DotNetOpenAuth.Configuration;
using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OpenId.RelyingParty;
/// <summary>
/// Stores a secret used in signing and verifying messages.
@@ -51,7 +52,7 @@ namespace DotNetOpenAuth.OpenId {
/// <summary>
/// Gets a unique handle by which this <see cref="Association"/> may be stored or retrieved.
/// </summary>
- public string Handle { get; private set; }
+ public string Handle { get; internal set; }
/// <summary>
/// Gets the UTC time when this <see cref="Association"/> will expire.
@@ -85,6 +86,7 @@ namespace DotNetOpenAuth.OpenId {
/// <summary>
/// Gets or sets the UTC time that this <see cref="Association"/> was first created.
/// </summary>
+ [MessagePart]
internal DateTime Issued { get; set; }
/// <summary>
@@ -102,6 +104,7 @@ namespace DotNetOpenAuth.OpenId {
/// Gets the shared secret key between the consumer and provider.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "It is a buffer.")]
+ [MessagePart("key")]
protected internal byte[] SecretKey { get; private set; }
/// <summary>
@@ -117,6 +120,7 @@ namespace DotNetOpenAuth.OpenId {
/// <summary>
/// Gets the lifetime the OpenID provider permits this <see cref="Association"/>.
/// </summary>
+ [MessagePart("ttl")]
protected TimeSpan TotalLifeLength { get; private set; }
/// <summary>
@@ -156,7 +160,7 @@ namespace DotNetOpenAuth.OpenId {
/// <returns>
/// The newly dehydrated <see cref="Association"/>, which can be returned
/// from a custom association store's
- /// <see cref="IAssociationStore&lt;TKey&gt;.GetAssociation(TKey, SecuritySettings)"/> method.
+ /// <see cref="IRelyingPartyAssociationStore.GetAssociation(Uri, SecuritySettings)"/> method.
/// </returns>
public static Association Deserialize(string handle, DateTime expiresUtc, byte[] privateData) {
Contract.Requires<ArgumentNullException>(!String.IsNullOrEmpty(handle));
@@ -219,7 +223,7 @@ namespace DotNetOpenAuth.OpenId {
if (a.Handle != this.Handle ||
a.Issued != this.Issued ||
- a.TotalLifeLength != this.TotalLifeLength) {
+ !MessagingUtilities.Equals(a.TotalLifeLength, this.TotalLifeLength, TimeSpan.FromSeconds(1))) {
return false;
}
diff --git a/src/DotNetOpenAuth/OpenId/AssociationMemoryStore.cs b/src/DotNetOpenAuth/OpenId/AssociationMemoryStore.cs
deleted file mode 100644
index 7a20fd5..0000000
--- a/src/DotNetOpenAuth/OpenId/AssociationMemoryStore.cs
+++ /dev/null
@@ -1,133 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="AssociationMemoryStore.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId {
- using System.Collections.Generic;
- using System.Linq;
-
- /// <summary>
- /// Manages a set of associations in memory only (no database).
- /// </summary>
- /// <typeparam name="TKey">The type of the key.</typeparam>
- /// <remarks>
- /// This class should be used for low-to-medium traffic relying party sites that can afford to lose associations
- /// if the app pool was ever restarted. High traffic relying parties and providers should write their own
- /// implementation of <see cref="IAssociationStore&lt;TKey&gt;"/> that works against their own database schema
- /// to allow for persistance and recall of associations across servers in a web farm and server restarts.
- /// </remarks>
- internal class AssociationMemoryStore<TKey> : IAssociationStore<TKey> {
- /// <summary>
- /// How many association store requests should occur between each spring cleaning.
- /// </summary>
- private const int PeriodicCleaningFrequency = 10;
-
- /// <summary>
- /// For Relying Parties, this maps OP Endpoints to a set of associations with that endpoint.
- /// For Providers, this keeps smart and dumb associations in two distinct pools.
- /// </summary>
- private Dictionary<TKey, Associations> serverAssocsTable = new Dictionary<TKey, Associations>();
-
- /// <summary>
- /// A counter to track how close we are to an expired association cleaning run.
- /// </summary>
- private int periodicCleaning;
-
- /// <summary>
- /// Stores a given association for later recall.
- /// </summary>
- /// <param name="distinguishingFactor">The distinguishing factor, either an OP Endpoint or smart/dumb mode.</param>
- /// <param name="association">The association to store.</param>
- public void StoreAssociation(TKey distinguishingFactor, Association association) {
- lock (this) {
- if (!this.serverAssocsTable.ContainsKey(distinguishingFactor)) {
- this.serverAssocsTable.Add(distinguishingFactor, new Associations());
- }
- Associations server_assocs = this.serverAssocsTable[distinguishingFactor];
-
- server_assocs.Set(association);
-
- unchecked {
- this.periodicCleaning++;
- }
- if (this.periodicCleaning % PeriodicCleaningFrequency == 0) {
- this.ClearExpiredAssociations();
- }
- }
- }
-
- /// <summary>
- /// Gets the best association (the one with the longest remaining life) for a given key.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="securitySettings">The security settings.</param>
- /// <returns>
- /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
- /// </returns>
- public Association GetAssociation(TKey distinguishingFactor, SecuritySettings securitySettings) {
- lock (this) {
- return this.GetServerAssociations(distinguishingFactor).Best.FirstOrDefault(assoc => securitySettings.IsAssociationInPermittedRange(assoc));
- }
- }
-
- /// <summary>
- /// Gets the association for a given key and handle.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be recalled.</param>
- /// <returns>
- /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.
- /// </returns>
- public Association GetAssociation(TKey distinguishingFactor, string handle) {
- lock (this) {
- return this.GetServerAssociations(distinguishingFactor).Get(handle);
- }
- }
-
- /// <summary>
- /// Removes a specified handle that may exist in the store.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be deleted.</param>
- /// <returns>
- /// True if the association existed in this store previous to this call.
- /// </returns>
- /// <remarks>
- /// No exception should be thrown if the association does not exist in the store
- /// before this call.
- /// </remarks>
- public bool RemoveAssociation(TKey distinguishingFactor, string handle) {
- lock (this) {
- return this.GetServerAssociations(distinguishingFactor).Remove(handle);
- }
- }
-
- /// <summary>
- /// Gets the server associations for a given OP Endpoint or dumb/smart mode.
- /// </summary>
- /// <param name="distinguishingFactor">The distinguishing factor, either an OP Endpoint (for relying parties) or smart/dumb (for providers).</param>
- /// <returns>The collection of associations that fit the <paramref name="distinguishingFactor"/>.</returns>
- internal Associations GetServerAssociations(TKey distinguishingFactor) {
- lock (this) {
- if (!this.serverAssocsTable.ContainsKey(distinguishingFactor)) {
- this.serverAssocsTable.Add(distinguishingFactor, new Associations());
- }
-
- return this.serverAssocsTable[distinguishingFactor];
- }
- }
-
- /// <summary>
- /// Clears all expired associations from the store.
- /// </summary>
- private void ClearExpiredAssociations() {
- lock (this) {
- foreach (Associations assocs in this.serverAssocsTable.Values) {
- assocs.ClearExpired();
- }
- }
- }
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/Behaviors/GsaIcamProfile.cs b/src/DotNetOpenAuth/OpenId/Behaviors/GsaIcamProfile.cs
index 20c207f..66ac276 100644
--- a/src/DotNetOpenAuth/OpenId/Behaviors/GsaIcamProfile.cs
+++ b/src/DotNetOpenAuth/OpenId/Behaviors/GsaIcamProfile.cs
@@ -9,6 +9,7 @@ namespace DotNetOpenAuth.OpenId.Behaviors {
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
+ using DotNetOpenAuth.Configuration;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy;
@@ -34,6 +35,11 @@ namespace DotNetOpenAuth.OpenId.Behaviors {
private static readonly TimeSpan MaximumAssociationLifetime = TimeSpan.FromSeconds(86400);
/// <summary>
+ /// Backing field for the <see cref="DisableSslRequirement"/> static property.
+ /// </summary>
+ private static bool disableSslRequirement = DotNetOpenAuthSection.Configuration.Messaging.RelaxSslRequirements;
+
+ /// <summary>
/// Initializes a new instance of the <see cref="GsaIcamProfile"/> class.
/// </summary>
public GsaIcamProfile() {
@@ -57,7 +63,10 @@ namespace DotNetOpenAuth.OpenId.Behaviors {
/// <summary>
/// Gets or sets a value indicating whether to ignore the SSL requirement (for testing purposes only).
/// </summary>
- public static bool DisableSslRequirement { get; set; }
+ public static bool DisableSslRequirement { // not an auto-property because it has a default value, and FxCop doesn't want us using static constructors.
+ get { return disableSslRequirement; }
+ set { disableSslRequirement = value; }
+ }
#region IRelyingPartyBehavior Members
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/OpenIdChannel.cs b/src/DotNetOpenAuth/OpenId/ChannelElements/OpenIdChannel.cs
index bc613ed..d9a0e50 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/OpenIdChannel.cs
+++ b/src/DotNetOpenAuth/OpenId/ChannelElements/OpenIdChannel.cs
@@ -46,11 +46,11 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// Initializes a new instance of the <see cref="OpenIdChannel"/> class
/// for use by a Relying Party.
/// </summary>
- /// <param name="associationStore">The association store to use.</param>
+ /// <param name="cryptoKeyStore">The association store to use.</param>
/// <param name="nonceStore">The nonce store to use.</param>
/// <param name="securitySettings">The security settings to apply.</param>
- internal OpenIdChannel(IAssociationStore<Uri> associationStore, INonceStore nonceStore, RelyingPartySecuritySettings securitySettings)
- : this(associationStore, nonceStore, new OpenIdMessageFactory(), securitySettings, false) {
+ internal OpenIdChannel(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore, RelyingPartySecuritySettings securitySettings)
+ : this(cryptoKeyStore, nonceStore, new OpenIdMessageFactory(), securitySettings, false) {
Contract.Requires<ArgumentNullException>(securitySettings != null);
}
@@ -58,11 +58,12 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// Initializes a new instance of the <see cref="OpenIdChannel"/> class
/// for use by a Provider.
/// </summary>
- /// <param name="associationStore">The association store to use.</param>
+ /// <param name="cryptoKeyStore">The OpenID Provider's association store or handle encoder.</param>
/// <param name="nonceStore">The nonce store to use.</param>
/// <param name="securitySettings">The security settings.</param>
- internal OpenIdChannel(IAssociationStore<AssociationRelyingPartyType> associationStore, INonceStore nonceStore, ProviderSecuritySettings securitySettings)
- : this(associationStore, nonceStore, new OpenIdMessageFactory(), securitySettings) {
+ internal OpenIdChannel(IProviderAssociationStore cryptoKeyStore, INonceStore nonceStore, ProviderSecuritySettings securitySettings)
+ : this(cryptoKeyStore, nonceStore, new OpenIdMessageFactory(), securitySettings) {
+ Contract.Requires<ArgumentNullException>(cryptoKeyStore != null);
Contract.Requires<ArgumentNullException>(securitySettings != null);
}
@@ -70,13 +71,13 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// Initializes a new instance of the <see cref="OpenIdChannel"/> class
/// for use by a Relying Party.
/// </summary>
- /// <param name="associationStore">The association store to use.</param>
+ /// <param name="cryptoKeyStore">The association store to use.</param>
/// <param name="nonceStore">The nonce store to use.</param>
/// <param name="messageTypeProvider">An object that knows how to distinguish the various OpenID message types for deserialization purposes.</param>
/// <param name="securitySettings">The security settings to apply.</param>
/// <param name="nonVerifying">A value indicating whether the channel is set up with no functional security binding elements.</param>
- private OpenIdChannel(IAssociationStore<Uri> associationStore, INonceStore nonceStore, IMessageFactory messageTypeProvider, RelyingPartySecuritySettings securitySettings, bool nonVerifying) :
- this(messageTypeProvider, InitializeBindingElements(associationStore, nonceStore, securitySettings, nonVerifying)) {
+ private OpenIdChannel(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore, IMessageFactory messageTypeProvider, RelyingPartySecuritySettings securitySettings, bool nonVerifying) :
+ this(messageTypeProvider, InitializeBindingElements(cryptoKeyStore, nonceStore, securitySettings, nonVerifying)) {
Contract.Requires<ArgumentNullException>(messageTypeProvider != null);
Contract.Requires<ArgumentNullException>(securitySettings != null);
Contract.Requires<ArgumentException>(!nonVerifying || securitySettings is RelyingPartySecuritySettings);
@@ -86,12 +87,13 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// Initializes a new instance of the <see cref="OpenIdChannel"/> class
/// for use by a Provider.
/// </summary>
- /// <param name="associationStore">The association store to use.</param>
+ /// <param name="cryptoKeyStore">The association store to use.</param>
/// <param name="nonceStore">The nonce store to use.</param>
/// <param name="messageTypeProvider">An object that knows how to distinguish the various OpenID message types for deserialization purposes.</param>
/// <param name="securitySettings">The security settings.</param>
- private OpenIdChannel(IAssociationStore<AssociationRelyingPartyType> associationStore, INonceStore nonceStore, IMessageFactory messageTypeProvider, ProviderSecuritySettings securitySettings) :
- this(messageTypeProvider, InitializeBindingElements(associationStore, nonceStore, securitySettings, false)) {
+ private OpenIdChannel(IProviderAssociationStore cryptoKeyStore, INonceStore nonceStore, IMessageFactory messageTypeProvider, ProviderSecuritySettings securitySettings) :
+ this(messageTypeProvider, InitializeBindingElements(cryptoKeyStore, nonceStore, securitySettings)) {
+ Contract.Requires<ArgumentNullException>(cryptoKeyStore != null);
Contract.Requires<ArgumentNullException>(messageTypeProvider != null);
Contract.Requires<ArgumentNullException>(securitySettings != null);
}
@@ -302,65 +304,43 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// <summary>
/// Initializes the binding elements.
/// </summary>
- /// <typeparam name="T">The distinguishing factor used by the association store.</typeparam>
- /// <param name="associationStore">The association store.</param>
+ /// <param name="cryptoKeyStore">The crypto key store.</param>
/// <param name="nonceStore">The nonce store to use.</param>
/// <param name="securitySettings">The security settings to apply. Must be an instance of either <see cref="RelyingPartySecuritySettings"/> or <see cref="ProviderSecuritySettings"/>.</param>
/// <param name="nonVerifying">A value indicating whether the channel is set up with no functional security binding elements.</param>
/// <returns>
/// An array of binding elements which may be used to construct the channel.
/// </returns>
- [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Needed for code contracts.")]
- private static IChannelBindingElement[] InitializeBindingElements<T>(IAssociationStore<T> associationStore, INonceStore nonceStore, SecuritySettings securitySettings, bool nonVerifying) {
+ private static IChannelBindingElement[] InitializeBindingElements(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore, RelyingPartySecuritySettings securitySettings, bool nonVerifying) {
Contract.Requires<ArgumentNullException>(securitySettings != null);
- Contract.Requires<ArgumentException>(!nonVerifying || securitySettings is RelyingPartySecuritySettings);
-
- var rpSecuritySettings = securitySettings as RelyingPartySecuritySettings;
- var opSecuritySettings = securitySettings as ProviderSecuritySettings;
- ErrorUtilities.VerifyInternal(rpSecuritySettings != null || opSecuritySettings != null, "Expected an RP or OP security settings instance.");
- ErrorUtilities.VerifyInternal(!nonVerifying || rpSecuritySettings != null, "Non-verifying channels can only be constructed for relying parties.");
- bool isRelyingPartyRole = rpSecuritySettings != null;
-
- var rpAssociationStore = associationStore as IAssociationStore<Uri>;
- var opAssociationStore = associationStore as IAssociationStore<AssociationRelyingPartyType>;
- ErrorUtilities.VerifyInternal(isRelyingPartyRole || opAssociationStore != null, "Providers MUST have an association store.");
SigningBindingElement signingElement;
- if (isRelyingPartyRole) {
- signingElement = nonVerifying ? null : new SigningBindingElement(rpAssociationStore);
- } else {
- signingElement = new SigningBindingElement(opAssociationStore, opSecuritySettings);
- }
+ signingElement = nonVerifying ? null : new SigningBindingElement(new CryptoKeyStoreAsRelyingPartyAssociationStore(cryptoKeyStore ?? new MemoryCryptoKeyStore()));
var extensionFactory = OpenIdExtensionFactoryAggregator.LoadFromConfiguration();
List<IChannelBindingElement> elements = new List<IChannelBindingElement>(8);
elements.Add(new ExtensionsBindingElement(extensionFactory, securitySettings));
- if (isRelyingPartyRole) {
- elements.Add(new RelyingPartySecurityOptions(rpSecuritySettings));
- elements.Add(new BackwardCompatibilityBindingElement());
- ReturnToNonceBindingElement requestNonceElement = null;
-
- if (associationStore != null) {
- if (nonceStore != null) {
- // There is no point in having a ReturnToNonceBindingElement without
- // a ReturnToSignatureBindingElement because the nonce could be
- // artificially changed without it.
- requestNonceElement = new ReturnToNonceBindingElement(nonceStore, rpSecuritySettings);
- elements.Add(requestNonceElement);
- }
+ elements.Add(new RelyingPartySecurityOptions(securitySettings));
+ elements.Add(new BackwardCompatibilityBindingElement());
+ ReturnToNonceBindingElement requestNonceElement = null;
- // It is important that the return_to signing element comes last
- // so that the nonce is included in the signature.
- elements.Add(new ReturnToSignatureBindingElement(rpAssociationStore, rpSecuritySettings));
+ if (cryptoKeyStore != null) {
+ if (nonceStore != null) {
+ // There is no point in having a ReturnToNonceBindingElement without
+ // a ReturnToSignatureBindingElement because the nonce could be
+ // artificially changed without it.
+ requestNonceElement = new ReturnToNonceBindingElement(nonceStore, securitySettings);
+ elements.Add(requestNonceElement);
}
- ErrorUtilities.VerifyOperation(!rpSecuritySettings.RejectUnsolicitedAssertions || requestNonceElement != null, OpenIdStrings.UnsolicitedAssertionRejectionRequiresNonceStore);
- } else {
- // Providers must always have a nonce store.
- ErrorUtilities.VerifyArgumentNotNull(nonceStore, "nonceStore");
+ // It is important that the return_to signing element comes last
+ // so that the nonce is included in the signature.
+ elements.Add(new ReturnToSignatureBindingElement(cryptoKeyStore));
}
+ ErrorUtilities.VerifyOperation(!securitySettings.RejectUnsolicitedAssertions || requestNonceElement != null, OpenIdStrings.UnsolicitedAssertionRejectionRequiresNonceStore);
+
if (nonVerifying) {
elements.Add(new SkipSecurityBindingElement());
} else {
@@ -374,5 +354,33 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
return elements.ToArray();
}
+
+ /// <summary>
+ /// Initializes the binding elements.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The OpenID Provider's crypto key store.</param>
+ /// <param name="nonceStore">The nonce store to use.</param>
+ /// <param name="securitySettings">The security settings to apply. Must be an instance of either <see cref="RelyingPartySecuritySettings"/> or <see cref="ProviderSecuritySettings"/>.</param>
+ /// <returns>
+ /// An array of binding elements which may be used to construct the channel.
+ /// </returns>
+ private static IChannelBindingElement[] InitializeBindingElements(IProviderAssociationStore cryptoKeyStore, INonceStore nonceStore, ProviderSecuritySettings securitySettings) {
+ Contract.Requires<ArgumentNullException>(cryptoKeyStore != null);
+ Contract.Requires<ArgumentNullException>(securitySettings != null);
+ Contract.Requires<ArgumentNullException>(nonceStore != null);
+
+ SigningBindingElement signingElement;
+ signingElement = new SigningBindingElement(cryptoKeyStore, securitySettings);
+
+ var extensionFactory = OpenIdExtensionFactoryAggregator.LoadFromConfiguration();
+
+ List<IChannelBindingElement> elements = new List<IChannelBindingElement>(8);
+ elements.Add(new ExtensionsBindingElement(extensionFactory, securitySettings));
+ elements.Add(new StandardReplayProtectionBindingElement(nonceStore, true));
+ elements.Add(new StandardExpirationBindingElement());
+ elements.Add(signingElement);
+
+ return elements.ToArray();
+ }
}
}
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToNonceBindingElement.cs b/src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToNonceBindingElement.cs
index 370192a..3649543 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToNonceBindingElement.cs
+++ b/src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToNonceBindingElement.cs
@@ -53,6 +53,11 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
internal const string NonceParameter = OpenIdUtilities.CustomParameterPrefix + "request_nonce";
/// <summary>
+ /// The context within which return_to nonces must be unique -- they all go into the same bucket.
+ /// </summary>
+ private const string ReturnToNonceContext = "https://localhost/dnoa/return_to_nonce";
+
+ /// <summary>
/// The length of the generated nonce's random part.
/// </summary>
private const int NonceByteLength = 128 / 8; // 128-bit nonce
@@ -186,7 +191,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
}
IReplayProtectedProtocolMessage replayResponse = response;
- if (!this.nonceStore.StoreNonce(replayResponse.NonceContext, nonce.RandomPartAsString, nonce.CreationDateUtc)) {
+ if (!this.nonceStore.StoreNonce(ReturnToNonceContext, nonce.RandomPartAsString, nonce.CreationDateUtc)) {
Logger.OpenId.ErrorFormat("Replayed nonce detected ({0} {1}). Rejecting message.", replayResponse.Nonce, replayResponse.UtcCreationDate);
throw new ReplayedMessageException(message);
}
@@ -261,7 +266,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
internal static CustomNonce Deserialize(string value) {
Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(value));
- byte[] nonce = Convert.FromBase64String(value);
+ byte[] nonce = MessagingUtilities.FromBase64WebSafeString(value);
Contract.Assume(nonce != null);
DateTime creationDateUtc = new DateTime(BitConverter.ToInt64(nonce, 0), DateTimeKind.Utc);
byte[] randomPart = new byte[NonceByteLength];
@@ -278,7 +283,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
byte[] nonce = new byte[timestamp.Length + this.randomPart.Length];
timestamp.CopyTo(nonce, 0);
this.randomPart.CopyTo(nonce, timestamp.Length);
- string base64Nonce = Convert.ToBase64String(nonce);
+ string base64Nonce = MessagingUtilities.ConvertToBase64WebSafeString(nonce);
return base64Nonce;
}
}
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs b/src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs
index 438c496..30358e0 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs
+++ b/src/DotNetOpenAuth/OpenId/ChannelElements/ReturnToSignatureBindingElement.cs
@@ -11,7 +11,9 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
using System.Diagnostics.Contracts;
using System.Security.Cryptography;
using System.Web;
+ using DotNetOpenAuth.Configuration;
using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.OpenId.Messages;
using DotNetOpenAuth.OpenId.RelyingParty;
@@ -43,19 +45,23 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
private const string ReturnToSignatureHandleParameterName = OpenIdUtilities.CustomParameterPrefix + "return_to_sig_handle";
/// <summary>
- /// The hashing algorithm used to generate the private signature on the return_to parameter.
+ /// The URI to use for private associations at this RP.
/// </summary>
- private PrivateSecretManager secretManager;
+ private static readonly Uri SecretUri = new Uri("https://localhost/dnoa/secret");
+
+ /// <summary>
+ /// The key store used to generate the private signature on the return_to parameter.
+ /// </summary>
+ private ICryptoKeyStore cryptoKeyStore;
/// <summary>
/// Initializes a new instance of the <see cref="ReturnToSignatureBindingElement"/> class.
/// </summary>
- /// <param name="secretStore">The secret store from which to retrieve the secret used for signing.</param>
- /// <param name="securitySettings">The security settings.</param>
- internal ReturnToSignatureBindingElement(IAssociationStore<Uri> secretStore, RelyingPartySecuritySettings securitySettings) {
- Contract.Requires<ArgumentNullException>(secretStore != null);
+ /// <param name="cryptoKeyStore">The crypto key store.</param>
+ internal ReturnToSignatureBindingElement(ICryptoKeyStore cryptoKeyStore) {
+ Contract.Requires<ArgumentNullException>(cryptoKeyStore != null);
- this.secretManager = new PrivateSecretManager(securitySettings, secretStore);
+ this.cryptoKeyStore = cryptoKeyStore;
}
#region IChannelBindingElement Members
@@ -96,8 +102,10 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
public MessageProtections? ProcessOutgoingMessage(IProtocolMessage message) {
SignedResponseRequest request = message as SignedResponseRequest;
if (request != null && request.ReturnTo != null && request.SignReturnTo) {
- request.AddReturnToArguments(ReturnToSignatureHandleParameterName, this.secretManager.CurrentHandle);
- request.AddReturnToArguments(ReturnToSignatureParameterName, this.GetReturnToSignature(request.ReturnTo));
+ var cryptoKeyPair = this.cryptoKeyStore.GetCurrentKey(SecretUri.AbsoluteUri, DotNetOpenAuthSection.Configuration.OpenId.MaxAuthenticationTime);
+ request.AddReturnToArguments(ReturnToSignatureHandleParameterName, cryptoKeyPair.Key);
+ string signature = Convert.ToBase64String(this.GetReturnToSignature(request.ReturnTo, cryptoKeyPair.Value));
+ request.AddReturnToArguments(ReturnToSignatureParameterName, signature);
// We return none because we are not signing the entire message (only a part).
return MessageProtections.None;
@@ -134,10 +142,11 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
// Only check the return_to signature if one is present.
if (returnToParameters[ReturnToSignatureHandleParameterName] != null) {
// Set the safety flag showing whether the return_to url had a valid signature.
- string expected = this.GetReturnToSignature(response.ReturnTo);
+ byte[] expectedBytes = this.GetReturnToSignature(response.ReturnTo);
string actual = returnToParameters[ReturnToSignatureParameterName];
actual = OpenIdUtilities.FixDoublyUriDecodedBase64String(actual);
- response.ReturnToParametersSignatureValidated = actual == expected;
+ byte[] actualBytes = Convert.FromBase64String(actual);
+ response.ReturnToParametersSignatureValidated = MessagingUtilities.AreEquivalentConstantTime(actualBytes, expectedBytes);
if (!response.ReturnToParametersSignatureValidated) {
Logger.Bindings.WarnFormat("The return_to signature failed verification.");
}
@@ -155,13 +164,16 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// Gets the return to signature.
/// </summary>
/// <param name="returnTo">The return to.</param>
- /// <returns>The generated signature.</returns>
+ /// <param name="cryptoKey">The crypto key.</param>
+ /// <returns>
+ /// The generated signature.
+ /// </returns>
/// <remarks>
/// Only the parameters in the return_to URI are signed, rather than the base URI
/// itself, in order that OPs that might change the return_to's implicit port :80 part
/// or other minor changes do not invalidate the signature.
/// </remarks>
- private string GetReturnToSignature(Uri returnTo) {
+ private byte[] GetReturnToSignature(Uri returnTo, CryptoKey cryptoKey = null) {
Contract.Requires<ArgumentNullException>(returnTo != null);
// Assemble the dictionary to sign, taking care to remove the signature itself
@@ -182,12 +194,18 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
byte[] bytesToSign = KeyValueFormEncoding.GetBytes(sortedReturnToParameters);
byte[] signature;
try {
- signature = this.secretManager.Sign(bytesToSign, returnToParameters[ReturnToSignatureHandleParameterName]);
+ if (cryptoKey == null) {
+ cryptoKey = this.cryptoKeyStore.GetKey(SecretUri.AbsoluteUri, returnToParameters[ReturnToSignatureHandleParameterName]);
+ }
+
+ using (var signer = new HMACSHA256(cryptoKey.Key)) {
+ signature = signer.ComputeHash(bytesToSign);
+ }
} catch (ProtocolException ex) {
throw ErrorUtilities.Wrap(ex, OpenIdStrings.MaximumAuthenticationTimeExpired);
}
- string signatureBase64 = Convert.ToBase64String(signature);
- return signatureBase64;
+
+ return signature;
}
}
}
diff --git a/src/DotNetOpenAuth/OpenId/ChannelElements/SigningBindingElement.cs b/src/DotNetOpenAuth/OpenId/ChannelElements/SigningBindingElement.cs
index 30310ac..e301a3e 100644
--- a/src/DotNetOpenAuth/OpenId/ChannelElements/SigningBindingElement.cs
+++ b/src/DotNetOpenAuth/OpenId/ChannelElements/SigningBindingElement.cs
@@ -28,12 +28,12 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// <summary>
/// The association store used by Relying Parties to look up the secrets needed for signing.
/// </summary>
- private readonly IAssociationStore<Uri> rpAssociations;
+ private readonly IRelyingPartyAssociationStore rpAssociations;
/// <summary>
/// The association store used by Providers to look up the secrets needed for signing.
/// </summary>
- private readonly IAssociationStore<AssociationRelyingPartyType> opAssociations;
+ private readonly IProviderAssociationStore opAssociations;
/// <summary>
/// The security settings at the Provider.
@@ -45,7 +45,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// Initializes a new instance of the SigningBindingElement class for use by a Relying Party.
/// </summary>
/// <param name="associationStore">The association store used to look up the secrets needed for signing. May be null for dumb Relying Parties.</param>
- internal SigningBindingElement(IAssociationStore<Uri> associationStore) {
+ internal SigningBindingElement(IRelyingPartyAssociationStore associationStore) {
this.rpAssociations = associationStore;
}
@@ -54,7 +54,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// </summary>
/// <param name="associationStore">The association store used to look up the secrets needed for signing.</param>
/// <param name="securitySettings">The security settings.</param>
- internal SigningBindingElement(IAssociationStore<AssociationRelyingPartyType> associationStore, ProviderSecuritySettings securitySettings) {
+ internal SigningBindingElement(IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) {
Contract.Requires<ArgumentNullException>(associationStore != null);
Contract.Requires<ArgumentNullException>(securitySettings != null);
@@ -83,7 +83,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
/// Gets a value indicating whether this binding element is on a Provider channel.
/// </summary>
private bool IsOnProvider {
- get { return this.opAssociations != null; }
+ get { return this.opSecuritySettings != null; }
}
#region IChannelBindingElement Methods
@@ -232,14 +232,14 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
// get included in the list of checked parameters.
Protocol protocol = Protocol.Lookup(signedMessage.Version);
var partsRequiringProtection = from part in this.Channel.MessageDescriptions.Get(signedMessage).Mapping.Values
- where part.RequiredProtection != ProtectionLevel.None
- where part.IsRequired || part.IsNondefaultValueSet(signedMessage)
- select part.Name;
+ where part.RequiredProtection != ProtectionLevel.None
+ where part.IsRequired || part.IsNondefaultValueSet(signedMessage)
+ select part.Name;
ErrorUtilities.VerifyInternal(partsRequiringProtection.All(name => name.StartsWith(protocol.openid.Prefix, StringComparison.Ordinal)), "Signing only works when the parameters start with the 'openid.' prefix.");
string[] signedParts = signedMessage.SignedParameterOrder.Split(',');
var unsignedParts = from partName in partsRequiringProtection
- where !signedParts.Contains(partName.Substring(protocol.openid.Prefix.Length))
- select partName;
+ where !signedParts.Contains(partName.Substring(protocol.openid.Prefix.Length))
+ select partName;
ErrorUtilities.VerifyProtocol(!unsignedParts.Any(), OpenIdStrings.SignatureDoesNotIncludeMandatoryParts, string.Join(", ", unsignedParts.ToArray()));
}
@@ -293,7 +293,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
MessageDescription description = this.Channel.MessageDescriptions.Get(signedMessage);
var signedParts = from part in description.Mapping.Values
where (part.RequiredProtection & System.Net.Security.ProtectionLevel.Sign) != 0
- && part.GetValue(signedMessage) != null
+ && part.GetValue(signedMessage) != null
select part.Name;
string prefix = Protocol.V20.openid.Prefix;
ErrorUtilities.VerifyInternal(signedParts.All(name => name.StartsWith(prefix, StringComparison.Ordinal)), "All signed message parts must start with 'openid.'.");
@@ -378,8 +378,8 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
// Since we have an association handle, we're either signing with a smart association,
// or verifying a dumb one.
bool signing = string.IsNullOrEmpty(signedMessage.Signature);
- AssociationRelyingPartyType type = signing ? AssociationRelyingPartyType.Smart : AssociationRelyingPartyType.Dumb;
- association = this.opAssociations.GetAssociation(type, signedMessage.AssociationHandle);
+ bool isPrivateAssociation = !signing;
+ association = this.opAssociations.Deserialize(signedMessage, isPrivateAssociation, signedMessage.AssociationHandle);
if (association == null) {
// There was no valid association with the requested handle.
// Let's tell the RP to forget about that association.
@@ -403,12 +403,7 @@ namespace DotNetOpenAuth.OpenId.ChannelElements {
// If no assoc_handle was given or it was invalid, the only thing
// left to do is sign a message using a 'dumb' mode association.
Protocol protocol = Protocol.Default;
- Association association = this.opAssociations.GetAssociation(AssociationRelyingPartyType.Dumb, this.opSecuritySettings);
- if (association == null) {
- association = HmacShaAssociation.Create(protocol, protocol.Args.SignatureAlgorithm.HMAC_SHA256, AssociationRelyingPartyType.Dumb, this.opSecuritySettings);
- this.opAssociations.StoreAssociation(AssociationRelyingPartyType.Dumb, association);
- }
-
+ Association association = HmacShaAssociation.Create(protocol, protocol.Args.SignatureAlgorithm.HMAC_SHA256, AssociationRelyingPartyType.Dumb, this.opAssociations, this.opSecuritySettings);
return association;
}
}
diff --git a/src/DotNetOpenAuth/OpenId/DiffieHellman/DHKeyGeneration.cs b/src/DotNetOpenAuth/OpenId/DiffieHellman/DHKeyGeneration.cs
index c48151b..6eca6a0 100644
--- a/src/DotNetOpenAuth/OpenId/DiffieHellman/DHKeyGeneration.cs
+++ b/src/DotNetOpenAuth/OpenId/DiffieHellman/DHKeyGeneration.cs
@@ -8,6 +8,14 @@
//
// (C) 2003 The Mentalis.org Team (http://www.mentalis.org/)
//
+// Source Code License
+// Copyright 2002-2007, The Mentalis.org Team
+// All rights reserved.
+// http://www.mentalis.org/
+// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+// - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+// - Neither the name of the Mentalis.org Team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace Org.Mentalis.Security.Cryptography {
diff --git a/src/DotNetOpenAuth/OpenId/DiffieHellman/DHParameters.cs b/src/DotNetOpenAuth/OpenId/DiffieHellman/DHParameters.cs
index 2772d7a..8105125 100644
--- a/src/DotNetOpenAuth/OpenId/DiffieHellman/DHParameters.cs
+++ b/src/DotNetOpenAuth/OpenId/DiffieHellman/DHParameters.cs
@@ -8,7 +8,14 @@
//
// (C) 2003 The Mentalis.org Team (http://www.mentalis.org/)
//
-
+// Source Code License
+// Copyright 2002-2007, The Mentalis.org Team
+// All rights reserved.
+// http://www.mentalis.org/
+// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+// - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+// - Neither the name of the Mentalis.org Team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace Org.Mentalis.Security.Cryptography {
/// <summary>
diff --git a/src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellman.cs b/src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellman.cs
index 6438135..5019f70 100644
--- a/src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellman.cs
+++ b/src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellman.cs
@@ -8,6 +8,15 @@
//
// (C) 2003 The Mentalis.org Team (http://www.mentalis.org/)
//
+//
+// Source Code License
+// Copyright 2002-2007, The Mentalis.org Team
+// All rights reserved.
+// http://www.mentalis.org/
+// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+// - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+// - Neither the name of the Mentalis.org Team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Security.Cryptography;
diff --git a/src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellmanManaged.cs b/src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellmanManaged.cs
index 75787c3..6ac28df 100644
--- a/src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellmanManaged.cs
+++ b/src/DotNetOpenAuth/OpenId/DiffieHellman/DiffieHellmanManaged.cs
@@ -11,6 +11,15 @@
// References:
// - PKCS#3 [http://www.rsasecurity.com/rsalabs/pkcs/pkcs-3/]
//
+//
+// Source Code License
+// Copyright 2002-2007, The Mentalis.org Team
+// All rights reserved.
+// http://www.mentalis.org/
+// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
+// - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+// - Neither the name of the Mentalis.org Team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Security.Cryptography;
diff --git a/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Gender.cs b/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Gender.cs
index 3cc47c6..979c481 100644
--- a/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Gender.cs
+++ b/src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Gender.cs
@@ -38,7 +38,7 @@ namespace DotNetOpenAuth.OpenId.Extensions.SimpleRegistration {
/// The <paramref name="value"/> in string form, ready for message transport.
/// </returns>
public string Encode(object value) {
- Gender? gender = (Gender?)value;
+ var gender = (Gender?)value;
if (gender.HasValue) {
switch (gender.Value) {
case Gender.Male: return Constants.Genders.Male;
diff --git a/src/DotNetOpenAuth/OpenId/HmacShaAssociation.cs b/src/DotNetOpenAuth/OpenId/HmacShaAssociation.cs
index edc08ee..29da1be 100644
--- a/src/DotNetOpenAuth/OpenId/HmacShaAssociation.cs
+++ b/src/DotNetOpenAuth/OpenId/HmacShaAssociation.cs
@@ -102,7 +102,6 @@ namespace DotNetOpenAuth.OpenId {
Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(associationType));
Contract.Requires<ArgumentNullException>(secret != null);
Contract.Ensures(Contract.Result<HmacShaAssociation>() != null);
-
HmacSha match = hmacShaAssociationTypes.FirstOrDefault(sha => String.Equals(sha.GetAssociationType(protocol), associationType, StringComparison.Ordinal));
ErrorUtilities.VerifyProtocol(match != null, OpenIdStrings.NoAssociationTypeFoundByName, associationType);
return new HmacShaAssociation(match, handle, secret, totalLifeLength);
@@ -139,35 +138,29 @@ namespace DotNetOpenAuth.OpenId {
}
/// <summary>
- /// Creates a new association of a given type.
+ /// Creates a new association of a given type at an OpenID Provider.
/// </summary>
/// <param name="protocol">The protocol.</param>
/// <param name="associationType">Type of the association (i.e. HMAC-SHA1 or HMAC-SHA256)</param>
/// <param name="associationUse">A value indicating whether the new association will be used privately by the Provider for "dumb mode" authentication
/// or shared with the Relying Party for "smart mode" authentication.</param>
+ /// <param name="associationStore">The Provider's association store.</param>
/// <param name="securitySettings">The security settings of the Provider.</param>
- /// <returns>The newly created association.</returns>
+ /// <returns>
+ /// The newly created association.
+ /// </returns>
/// <remarks>
/// The new association is NOT automatically put into an association store. This must be done by the caller.
/// </remarks>
- internal static HmacShaAssociation Create(Protocol protocol, string associationType, AssociationRelyingPartyType associationUse, ProviderSecuritySettings securitySettings) {
+ internal static HmacShaAssociation Create(Protocol protocol, string associationType, AssociationRelyingPartyType associationUse, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) {
Contract.Requires<ArgumentNullException>(protocol != null);
Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(associationType));
+ Contract.Requires<ArgumentNullException>(associationStore != null);
Contract.Requires<ArgumentNullException>(securitySettings != null);
Contract.Ensures(Contract.Result<HmacShaAssociation>() != null);
int secretLength = GetSecretLength(protocol, associationType);
- // Generate the handle. It must be unique, and preferably unpredictable,
- // so we use a time element and a random data element to generate it.
- string uniq = MessagingUtilities.GetCryptoRandomDataAsBase64(4);
- string handle = string.Format(
- CultureInfo.InvariantCulture,
- "{{{0}}}{{{1}}}{{{2}}}",
- DateTime.UtcNow.Ticks,
- uniq,
- secretLength);
-
// Generate the secret that will be used for signing
byte[] secret = MessagingUtilities.GetCryptoRandomData(secretLength);
@@ -180,10 +173,13 @@ namespace DotNetOpenAuth.OpenId {
lifetime = DumbSecretLifetime;
}
+ string handle = associationStore.Serialize(secret, DateTime.UtcNow + lifetime, associationUse == AssociationRelyingPartyType.Dumb);
+
Contract.Assert(protocol != null); // All the way up to the method call, the condition holds, yet we get a Requires failure next
Contract.Assert(secret != null);
Contract.Assert(!String.IsNullOrEmpty(associationType));
- return Create(protocol, associationType, handle, secret, lifetime);
+ var result = Create(protocol, associationType, handle, secret, lifetime);
+ return result;
}
/// <summary>
diff --git a/src/DotNetOpenAuth/OpenId/IAssociationStore.cs b/src/DotNetOpenAuth/OpenId/IAssociationStore.cs
deleted file mode 100644
index fb4487c..0000000
--- a/src/DotNetOpenAuth/OpenId/IAssociationStore.cs
+++ /dev/null
@@ -1,189 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="IAssociationStore.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId {
- using System;
- using System.Diagnostics.Contracts;
-
- /// <summary>
- /// An enumeration that can specify how a given <see cref="Association"/> is used.
- /// </summary>
- public enum AssociationRelyingPartyType {
- /// <summary>
- /// The <see cref="Association"/> manages a shared secret between
- /// Provider and Relying Party sites that allows the RP to verify
- /// the signature on a message from an OP.
- /// </summary>
- Smart,
-
- /// <summary>
- /// The <see cref="Association"/> manages a secret known alone by
- /// a Provider that allows the Provider to verify its own signatures
- /// for "dumb" (stateless) relying parties.
- /// </summary>
- Dumb
- }
-
- /// <summary>
- /// Stores <see cref="Association"/>s for lookup by their handle, keeping
- /// associations separated by a given distinguishing factor (like which server the
- /// association is with).
- /// </summary>
- /// <typeparam name="TKey">
- /// <see cref="System.Uri"/> for consumers (to distinguish associations across servers) or
- /// <see cref="AssociationRelyingPartyType"/> for providers (to distinguish dumb and smart client associations).
- /// </typeparam>
- /// <remarks>
- /// Expired associations should be periodically cleared out of an association store.
- /// This should be done frequently enough to avoid a memory leak, but sparingly enough
- /// to not be a performance drain. Because this balance can vary by host, it is the
- /// responsibility of the host to initiate this cleaning.
- /// </remarks>
- ////[ContractClass(typeof(IAssociationStoreContract<>))]
- public interface IAssociationStore<TKey> {
- /// <summary>
- /// Saves an <see cref="Association"/> for later recall.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for providers).</param>
- /// <param name="association">The association to store.</param>
- /// <remarks>
- /// TODO: what should implementations do on association handle conflict?
- /// </remarks>
- void StoreAssociation(TKey distinguishingFactor, Association association);
-
- /// <summary>
- /// Gets the best association (the one with the longest remaining life) for a given key.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="securityRequirements">The security requirements that the returned association must meet.</param>
- /// <returns>
- /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
- /// </returns>
- /// <remarks>
- /// In the event that multiple associations exist for the given
- /// <paramref name="distinguishingFactor"/>, it is important for the
- /// implementation for this method to use the <paramref name="securityRequirements"/>
- /// to pick the best (highest grade or longest living as the host's policy may dictate)
- /// association that fits the security requirements.
- /// Associations that are returned that do not meet the security requirements will be
- /// ignored and a new association created.
- /// </remarks>
- Association GetAssociation(TKey distinguishingFactor, SecuritySettings securityRequirements);
-
- /// <summary>
- /// Gets the association for a given key and handle.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be recalled.</param>
- /// <returns>The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.</returns>
- Association GetAssociation(TKey distinguishingFactor, string handle);
-
- /// <summary>Removes a specified handle that may exist in the store.</summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be deleted.</param>
- /// <returns>True if the association existed in this store previous to this call.</returns>
- /// <remarks>
- /// No exception should be thrown if the association does not exist in the store
- /// before this call.
- /// </remarks>
- bool RemoveAssociation(TKey distinguishingFactor, string handle);
- }
-
- // For some odd reason, having this next class causes our test project to fail to build with this error:
- // Error 42 Method 'StoreAssociation' in type 'DotNetOpenAuth.OpenId.IAssociationStoreContract_Accessor`1' from assembly 'DotNetOpenAuth_Accessor, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation. DotNetOpenAuth.Test
- /////// <summary>
- /////// Code Contract for the <see cref="IAssociationStore&lt;TKey&gt;"/> class.
- /////// </summary>
- /////// <typeparam name="TKey">The type of the key.</typeparam>
- ////[ContractClassFor(typeof(IAssociationStore<>))]
- ////internal abstract class IAssociationStoreContract<TKey> : IAssociationStore<TKey> {
- //// #region IAssociationStore<TKey> Members
-
- //// /// <summary>
- //// /// Saves an <see cref="Association"/> for later recall.
- //// /// </summary>
- //// /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for providers).</param>
- //// /// <param name="association">The association to store.</param>
- //// /// <remarks>
- //// /// TODO: what should implementations do on association handle conflict?
- //// /// </remarks>
- //// void IAssociationStore<TKey>.StoreAssociation(TKey distinguishingFactor, Association association) {
- //// Contract.Requires<ArgumentNullException>(distinguishingFactor != null);
- //// Contract.Requires<ArgumentNullException>(association != null);
- //// throw new NotImplementedException();
- //// }
-
- //// /// <summary>
- //// /// Gets the best association (the one with the longest remaining life) for a given key.
- //// /// </summary>
- //// /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- //// /// <param name="securityRequirements">The security requirements that the returned association must meet.</param>
- //// /// <returns>
- //// /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
- //// /// </returns>
- //// /// <remarks>
- //// /// In the event that multiple associations exist for the given
- //// /// <paramref name="distinguishingFactor"/>, it is important for the
- //// /// implementation for this method to use the <paramref name="securityRequirements"/>
- //// /// to pick the best (highest grade or longest living as the host's policy may dictate)
- //// /// association that fits the security requirements.
- //// /// Associations that are returned that do not meet the security requirements will be
- //// /// ignored and a new association created.
- //// /// </remarks>
- //// Association IAssociationStore<TKey>.GetAssociation(TKey distinguishingFactor, SecuritySettings securityRequirements) {
- //// Contract.Requires<ArgumentNullException>(distinguishingFactor != null);
- //// Contract.Requires<ArgumentNullException>(securityRequirements != null);
- //// throw new NotImplementedException();
- //// }
-
- //// /// <summary>
- //// /// Gets the association for a given key and handle.
- //// /// </summary>
- //// /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- //// /// <param name="handle">The handle of the specific association that must be recalled.</param>
- //// /// <returns>
- //// /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.
- //// /// </returns>
- //// Association IAssociationStore<TKey>.GetAssociation(TKey distinguishingFactor, string handle) {
- //// Contract.Requires<ArgumentNullException>(distinguishingFactor != null);
- //// Contract.Requires(!String.IsNullOrEmpty(handle));
- //// throw new NotImplementedException();
- //// }
-
- //// /// <summary>
- //// /// Removes a specified handle that may exist in the store.
- //// /// </summary>
- //// /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- //// /// <param name="handle">The handle of the specific association that must be deleted.</param>
- //// /// <returns>
- //// /// True if the association existed in this store previous to this call.
- //// /// </returns>
- //// /// <remarks>
- //// /// No exception should be thrown if the association does not exist in the store
- //// /// before this call.
- //// /// </remarks>
- //// bool IAssociationStore<TKey>.RemoveAssociation(TKey distinguishingFactor, string handle) {
- //// Contract.Requires<ArgumentNullException>(distinguishingFactor != null);
- //// Contract.Requires(!String.IsNullOrEmpty(handle));
- //// throw new NotImplementedException();
- //// }
-
- //// /// <summary>
- //// /// Clears all expired associations from the store.
- //// /// </summary>
- //// /// <remarks>
- //// /// If another algorithm is in place to periodically clear out expired associations,
- //// /// this method call may be ignored.
- //// /// This should be done frequently enough to avoid a memory leak, but sparingly enough
- //// /// to not be a performance drain.
- //// /// </remarks>
- //// void IAssociationStore<TKey>.ClearExpiredAssociations() {
- //// throw new NotImplementedException();
- //// }
-
- //// #endregion
- ////}
-}
diff --git a/src/DotNetOpenAuth/OpenId/IOpenIdApplicationStore.cs b/src/DotNetOpenAuth/OpenId/IOpenIdApplicationStore.cs
new file mode 100644
index 0000000..6c04a81
--- /dev/null
+++ b/src/DotNetOpenAuth/OpenId/IOpenIdApplicationStore.cs
@@ -0,0 +1,16 @@
+//-----------------------------------------------------------------------
+// <copyright file="IOpenIdApplicationStore.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId {
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// A hybrid of the store interfaces that an OpenID Provider must implement, and
+ /// an OpenID Relying Party may implement to operate in stateful (smart) mode.
+ /// </summary>
+ public interface IOpenIdApplicationStore : ICryptoKeyStore, INonceStore {
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Messages/AssociateDiffieHellmanResponse.cs b/src/DotNetOpenAuth/OpenId/Messages/AssociateDiffieHellmanResponse.cs
index a4fdf49..5237826 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/AssociateDiffieHellmanResponse.cs
+++ b/src/DotNetOpenAuth/OpenId/Messages/AssociateDiffieHellmanResponse.cs
@@ -66,20 +66,23 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// Creates the association at the provider side after the association request has been received.
/// </summary>
/// <param name="request">The association request.</param>
+ /// <param name="associationStore">The OpenID Provider's association store or handle encoder.</param>
/// <param name="securitySettings">The security settings of the Provider.</param>
- /// <returns>The newly created association.</returns>
+ /// <returns>
+ /// The newly created association.
+ /// </returns>
/// <remarks>
/// The response message is updated to include the details of the created association by this method,
/// but the resulting association is <i>not</i> added to the association store and must be done by the caller.
/// </remarks>
- protected override Association CreateAssociationAtProvider(AssociateRequest request, ProviderSecuritySettings securitySettings) {
+ protected override Association CreateAssociationAtProvider(AssociateRequest request, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) {
var diffieHellmanRequest = request as AssociateDiffieHellmanRequest;
ErrorUtilities.VerifyInternal(diffieHellmanRequest != null, "Expected a DH request type.");
this.SessionType = this.SessionType ?? request.SessionType;
// Go ahead and create the association first, complete with its secret that we're about to share.
- Association association = HmacShaAssociation.Create(this.Protocol, this.AssociationType, AssociationRelyingPartyType.Smart, securitySettings);
+ Association association = HmacShaAssociation.Create(this.Protocol, this.AssociationType, AssociationRelyingPartyType.Smart, associationStore, securitySettings);
// We now need to securely communicate the secret to the relying party using Diffie-Hellman.
// We do this by performing a DH algorithm on the secret and setting a couple of properties
diff --git a/src/DotNetOpenAuth/OpenId/Messages/AssociateRequest.cs b/src/DotNetOpenAuth/OpenId/Messages/AssociateRequest.cs
index 3fd9424..2a0dc7a 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/AssociateRequest.cs
+++ b/src/DotNetOpenAuth/OpenId/Messages/AssociateRequest.cs
@@ -129,18 +129,18 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// <summary>
/// Creates a Provider's response to an incoming association request.
/// </summary>
- /// <param name="associationStore">The association store where a new association (if created) will be stored. Must not be null.</param>
+ /// <param name="associationStore">The association store.</param>
/// <param name="securitySettings">The security settings on the Provider.</param>
/// <returns>
/// The appropriate association response that is ready to be sent back to the Relying Party.
/// </returns>
/// <remarks>
- /// <para>If an association is created, it will be automatically be added to the provided
+ /// <para>If an association is created, it will be automatically be added to the provided
/// association store.</para>
- /// <para>Successful association response messages will derive from <see cref="AssociateSuccessfulResponse"/>.
+ /// <para>Successful association response messages will derive from <see cref="AssociateSuccessfulResponse"/>.
/// Failed association response messages will derive from <see cref="AssociateUnsuccessfulResponse"/>.</para>
/// </remarks>
- internal IProtocolMessage CreateResponse(IAssociationStore<AssociationRelyingPartyType> associationStore, ProviderSecuritySettings securitySettings) {
+ internal IProtocolMessage CreateResponse(IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) {
Contract.Requires<ArgumentNullException>(associationStore != null);
Contract.Requires<ArgumentNullException>(securitySettings != null);
@@ -152,8 +152,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
// Create and store the association if this is a successful response.
var successResponse = response as AssociateSuccessfulResponse;
if (successResponse != null) {
- Association association = successResponse.CreateAssociation(this, securitySettings);
- associationStore.StoreAssociation(AssociationRelyingPartyType.Smart, association);
+ successResponse.CreateAssociation(this, associationStore, securitySettings);
}
} else {
response = this.CreateUnsuccessfulResponse(securitySettings);
diff --git a/src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponse.cs b/src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponse.cs
index 137cd60..42d8816 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponse.cs
+++ b/src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponse.cs
@@ -99,15 +99,17 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// Called to create the Association based on a request previously given by the Relying Party.
/// </summary>
/// <param name="request">The prior request for an association.</param>
+ /// <param name="associationStore">The Provider's association store.</param>
/// <param name="securitySettings">The security settings for the Provider. Should be <c>null</c> for Relying Parties.</param>
- /// <returns>The created association.</returns>
+ /// <returns>
+ /// The created association.
+ /// </returns>
/// <remarks>
- /// <para>The response message is updated to include the details of the created association by this method,
- /// but the resulting association is <i>not</i> added to the association store and must be done by the caller.</para>
- /// <para>This method is called by both the Provider and the Relying Party, but actually performs
- /// quite different operations in either scenario.</para>
+ /// The response message is updated to include the details of the created association by this method.
+ /// This method is called by both the Provider and the Relying Party, but actually performs
+ /// quite different operations in either scenario.
/// </remarks>
- internal Association CreateAssociation(AssociateRequest request, ProviderSecuritySettings securitySettings) {
+ internal Association CreateAssociation(AssociateRequest request, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) {
Contract.Requires<ArgumentNullException>(request != null);
ErrorUtilities.VerifyInternal(!this.associationCreated, "The association has already been created.");
@@ -119,7 +121,7 @@ namespace DotNetOpenAuth.OpenId.Messages {
association = this.CreateAssociationAtRelyingParty(request);
} else {
ErrorUtilities.VerifyArgumentNotNull(securitySettings, "securitySettings");
- association = this.CreateAssociationAtProvider(request, securitySettings);
+ association = this.CreateAssociationAtProvider(request, associationStore, securitySettings);
this.ExpiresIn = association.SecondsTillExpiration;
this.AssociationHandle = association.Handle;
}
@@ -133,16 +135,19 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// Called to create the Association based on a request previously given by the Relying Party.
/// </summary>
/// <param name="request">The prior request for an association.</param>
+ /// <param name="associationStore">The Provider's association store.</param>
/// <param name="securitySettings">The security settings of the Provider.</param>
- /// <returns>The created association.</returns>
+ /// <returns>
+ /// The created association.
+ /// </returns>
/// <remarks>
- /// <para>The caller will update this message's <see cref="ExpiresIn"/> and <see cref="AssociationHandle"/>
+ /// <para>The caller will update this message's <see cref="ExpiresIn"/> and <see cref="AssociationHandle"/>
/// properties based on the <see cref="Association"/> returned by this method, but any other
/// association type specific properties must be set by this method.</para>
- /// <para>The response message is updated to include the details of the created association by this method,
+ /// <para>The response message is updated to include the details of the created association by this method,
/// but the resulting association is <i>not</i> added to the association store and must be done by the caller.</para>
/// </remarks>
- protected abstract Association CreateAssociationAtProvider(AssociateRequest request, ProviderSecuritySettings securitySettings);
+ protected abstract Association CreateAssociationAtProvider(AssociateRequest request, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings);
/// <summary>
/// Called to create the Association based on a request previously given by the Relying Party.
diff --git a/src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponseContract.cs b/src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponseContract.cs
index dd37da6..d474608 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponseContract.cs
+++ b/src/DotNetOpenAuth/OpenId/Messages/AssociateSuccessfulResponseContract.cs
@@ -15,8 +15,9 @@ namespace DotNetOpenAuth.OpenId.Messages {
protected AssociateSuccessfulResponseContract() : base(null, null) {
}
- protected override Association CreateAssociationAtProvider(AssociateRequest request, ProviderSecuritySettings securitySettings) {
+ protected override Association CreateAssociationAtProvider(AssociateRequest request, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) {
Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<ArgumentNullException>(associationStore != null);
Contract.Requires<ArgumentNullException>(securitySettings != null);
throw new NotImplementedException();
}
diff --git a/src/DotNetOpenAuth/OpenId/Messages/AssociateUnencryptedResponse.cs b/src/DotNetOpenAuth/OpenId/Messages/AssociateUnencryptedResponse.cs
index 493fe6b..7e2194a 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/AssociateUnencryptedResponse.cs
+++ b/src/DotNetOpenAuth/OpenId/Messages/AssociateUnencryptedResponse.cs
@@ -37,19 +37,22 @@ namespace DotNetOpenAuth.OpenId.Messages {
/// Called to create the Association based on a request previously given by the Relying Party.
/// </summary>
/// <param name="request">The prior request for an association.</param>
+ /// <param name="associationStore">The Provider's association store.</param>
/// <param name="securitySettings">The security settings of the Provider.</param>
- /// <returns>The created association.</returns>
+ /// <returns>
+ /// The created association.
+ /// </returns>
/// <remarks>
- /// <para>The caller will update this message's
- /// <see cref="AssociateSuccessfulResponse.ExpiresIn"/> and
- /// <see cref="AssociateSuccessfulResponse.AssociationHandle"/>
+ /// <para>The caller will update this message's
+ /// <see cref="AssociateSuccessfulResponse.ExpiresIn"/> and
+ /// <see cref="AssociateSuccessfulResponse.AssociationHandle"/>
/// properties based on the <see cref="Association"/> returned by this method, but any other
/// association type specific properties must be set by this method.</para>
- /// <para>The response message is updated to include the details of the created association by this method,
+ /// <para>The response message is updated to include the details of the created association by this method,
/// but the resulting association is <i>not</i> added to the association store and must be done by the caller.</para>
/// </remarks>
- protected override Association CreateAssociationAtProvider(AssociateRequest request, ProviderSecuritySettings securitySettings) {
- Association association = HmacShaAssociation.Create(Protocol, this.AssociationType, AssociationRelyingPartyType.Smart, securitySettings);
+ protected override Association CreateAssociationAtProvider(AssociateRequest request, IProviderAssociationStore associationStore, ProviderSecuritySettings securitySettings) {
+ Association association = HmacShaAssociation.Create(Protocol, this.AssociationType, AssociationRelyingPartyType.Smart, associationStore, securitySettings);
this.MacKey = association.SecretKey;
return association;
}
diff --git a/src/DotNetOpenAuth/OpenId/Messages/CheckAuthenticationResponse.cs b/src/DotNetOpenAuth/OpenId/Messages/CheckAuthenticationResponse.cs
index f1bb5ac..f4d5243 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/CheckAuthenticationResponse.cs
+++ b/src/DotNetOpenAuth/OpenId/Messages/CheckAuthenticationResponse.cs
@@ -44,10 +44,10 @@ namespace DotNetOpenAuth.OpenId.Messages {
this.IsValid = request.IsValid;
// Confirm the RP should invalidate the association handle only if the association
- // really doesn't exist. OpenID 2.0 section 11.4.2.2.
+ // is not valid (any longer). OpenID 2.0 section 11.4.2.2.
IndirectSignedResponse signedResponse = new IndirectSignedResponse(request, provider.Channel);
string invalidateHandle = ((ITamperResistantOpenIdMessage)signedResponse).InvalidateHandle;
- if (!string.IsNullOrEmpty(invalidateHandle) && provider.AssociationStore.GetAssociation(AssociationRelyingPartyType.Smart, invalidateHandle) == null) {
+ if (!string.IsNullOrEmpty(invalidateHandle) && !provider.AssociationStore.IsValid(signedResponse, false, invalidateHandle)) {
this.InvalidateHandle = invalidateHandle;
}
}
diff --git a/src/DotNetOpenAuth/OpenId/Messages/DirectErrorResponse.cs b/src/DotNetOpenAuth/OpenId/Messages/DirectErrorResponse.cs
index ad20ff7..607a139 100644
--- a/src/DotNetOpenAuth/OpenId/Messages/DirectErrorResponse.cs
+++ b/src/DotNetOpenAuth/OpenId/Messages/DirectErrorResponse.cs
@@ -36,6 +36,14 @@ namespace DotNetOpenAuth.OpenId.Messages {
get { return HttpStatusCode.BadRequest; }
}
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ /// <value>May be an empty collection, but must not be <c>null</c>.</value>
+ WebHeaderCollection IHttpDirectResponse.Headers {
+ get { return new WebHeaderCollection(); }
+ }
+
#endregion
/// <summary>
diff --git a/src/DotNetOpenAuth/OpenId/OpenIdUtilities.cs b/src/DotNetOpenAuth/OpenId/OpenIdUtilities.cs
index 04eb23c..68babd9 100644
--- a/src/DotNetOpenAuth/OpenId/OpenIdUtilities.cs
+++ b/src/DotNetOpenAuth/OpenId/OpenIdUtilities.cs
@@ -9,6 +9,7 @@ namespace DotNetOpenAuth.OpenId {
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
+ using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
@@ -30,6 +31,19 @@ namespace DotNetOpenAuth.OpenId {
internal const string CustomParameterPrefix = "dnoa.";
/// <summary>
+ /// Creates a random association handle.
+ /// </summary>
+ /// <returns>The association handle.</returns>
+ public static string GenerateRandomAssociationHandle() {
+ Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
+
+ // Generate the handle. It must be unique, and preferably unpredictable,
+ // so we use a time element and a random data element to generate it.
+ string uniq = MessagingUtilities.GetCryptoRandomDataAsBase64(4);
+ return string.Format(CultureInfo.InvariantCulture, "{{{0}}}{{{1}}}", DateTime.UtcNow.Ticks, uniq);
+ }
+
+ /// <summary>
/// Gets the OpenID protocol instance for the version in a message.
/// </summary>
/// <param name="message">The message.</param>
@@ -156,5 +170,26 @@ namespace DotNetOpenAuth.OpenId {
ErrorUtilities.VerifyOperation(aggregator != null, OpenIdStrings.UnsupportedChannelConfiguration);
return aggregator.Factories;
}
+
+ /// <summary>
+ /// Determines whether the association with the specified handle is (still) valid.
+ /// </summary>
+ /// <param name="associationStore">The association store.</param>
+ /// <param name="containingMessage">The OpenID message that referenced this association handle.</param>
+ /// <param name="isPrivateAssociation">A value indicating whether a private association is expected.</param>
+ /// <param name="handle">The association handle.</param>
+ /// <returns>
+ /// <c>true</c> if the specified containing message is valid; otherwise, <c>false</c>.
+ /// </returns>
+ internal static bool IsValid(this IProviderAssociationStore associationStore, IProtocolMessage containingMessage, bool isPrivateAssociation, string handle) {
+ Contract.Requires<ArgumentNullException>(associationStore != null);
+ Contract.Requires<ArgumentNullException>(containingMessage != null);
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(handle));
+ try {
+ return associationStore.Deserialize(containingMessage, isPrivateAssociation, handle) != null;
+ } catch (ProtocolException) {
+ return false;
+ }
+ }
}
}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/AnonymousRequest.cs b/src/DotNetOpenAuth/OpenId/Provider/AnonymousRequest.cs
index c5e6bba..974d729 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/AnonymousRequest.cs
+++ b/src/DotNetOpenAuth/OpenId/Provider/AnonymousRequest.cs
@@ -31,7 +31,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
internal AnonymousRequest(OpenIdProvider provider, SignedResponseRequest request)
: base(provider, request) {
Contract.Requires<ArgumentNullException>(provider != null);
- Contract.Requires<ArgumentException>(!(request is CheckIdRequest), "Instantiate AuthenticationRequest to handle this kind of message.");
+ Contract.Requires<ArgumentException>(!(request is CheckIdRequest));
this.positiveResponse = new IndirectSignedResponse(request);
}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/AssociationDataBag.cs b/src/DotNetOpenAuth/OpenId/Provider/AssociationDataBag.cs
new file mode 100644
index 0000000..a8ac41e
--- /dev/null
+++ b/src/DotNetOpenAuth/OpenId/Provider/AssociationDataBag.cs
@@ -0,0 +1,95 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociationDataBag.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Provider {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.IO;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// A signed and encrypted serialization of an association.
+ /// </summary>
+ internal class AssociationDataBag : DataBag, IStreamSerializingDataBag {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AssociationDataBag"/> class.
+ /// </summary>
+ public AssociationDataBag() {
+ }
+
+ /// <summary>
+ /// Gets or sets the association secret.
+ /// </summary>
+ [MessagePart(IsRequired = true)]
+ internal byte[] Secret { get; set; }
+
+ /// <summary>
+ /// Gets or sets the UTC time that this association expires.
+ /// </summary>
+ [MessagePart(IsRequired = true)]
+ internal DateTime ExpiresUtc { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether this instance is for "dumb" mode RPs.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if this instance is private association; otherwise, <c>false</c>.
+ /// </value>
+ [MessagePart(IsRequired = true)]
+ internal bool IsPrivateAssociation {
+ get { return this.AssociationType == AssociationRelyingPartyType.Dumb; }
+ set { this.AssociationType = value ? AssociationRelyingPartyType.Dumb : AssociationRelyingPartyType.Smart; }
+ }
+
+ /// <summary>
+ /// Gets or sets the type of the association (shared or private, a.k.a. smart or dumb).
+ /// </summary>
+ internal AssociationRelyingPartyType AssociationType { get; set; }
+
+ /// <summary>
+ /// Serializes the instance to the specified stream.
+ /// </summary>
+ /// <param name="stream">The stream.</param>
+ public void Serialize(Stream stream) {
+ var writer = new BinaryWriter(stream);
+ writer.Write(this.IsPrivateAssociation);
+ writer.WriteBuffer(this.Secret);
+ writer.Write((int)(this.ExpiresUtc - TimestampEncoder.Epoch).TotalSeconds);
+ writer.Flush();
+ }
+
+ /// <summary>
+ /// Initializes the fields on this instance from the specified stream.
+ /// </summary>
+ /// <param name="stream">The stream.</param>
+ public void Deserialize(Stream stream) {
+ var reader = new BinaryReader(stream);
+ this.IsPrivateAssociation = reader.ReadBoolean();
+ this.Secret = reader.ReadBuffer();
+ this.ExpiresUtc = TimestampEncoder.Epoch + TimeSpan.FromSeconds(reader.ReadInt32());
+ }
+
+ /// <summary>
+ /// Creates the formatter used for serialization of this type.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store used when signing or encrypting.</param>
+ /// <param name="bucket">The bucket in which symmetric keys are stored for signing/encrypting data.</param>
+ /// <param name="minimumAge">The minimum age.</param>
+ /// <returns>
+ /// A formatter for serialization.
+ /// </returns>
+ internal static IDataBagFormatter<AssociationDataBag> CreateFormatter(ICryptoKeyStore cryptoKeyStore, string bucket, TimeSpan? minimumAge = null) {
+ Contract.Requires<ArgumentNullException>(cryptoKeyStore != null);
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(bucket));
+ Contract.Ensures(Contract.Result<IDataBagFormatter<AssociationDataBag>>() != null);
+ return new BinaryDataBagFormatter<AssociationDataBag>(cryptoKeyStore, bucket, signed: true, encrypted: true, minimumAge: minimumAge);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/AssociationRelyingPartyType.cs b/src/DotNetOpenAuth/OpenId/Provider/AssociationRelyingPartyType.cs
new file mode 100644
index 0000000..4d121b1
--- /dev/null
+++ b/src/DotNetOpenAuth/OpenId/Provider/AssociationRelyingPartyType.cs
@@ -0,0 +1,26 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssociationRelyingPartyType.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Provider {
+ /// <summary>
+ /// An enumeration that can specify how a given <see cref="Association"/> is used.
+ /// </summary>
+ public enum AssociationRelyingPartyType {
+ /// <summary>
+ /// The <see cref="Association"/> manages a shared secret between
+ /// Provider and Relying Party sites that allows the RP to verify
+ /// the signature on a message from an OP.
+ /// </summary>
+ Smart,
+
+ /// <summary>
+ /// The <see cref="Association"/> manages a secret known alone by
+ /// a Provider that allows the Provider to verify its own signatures
+ /// for "dumb" (stateless) relying parties.
+ /// </summary>
+ Dumb
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/IProviderApplicationStore.cs b/src/DotNetOpenAuth/OpenId/Provider/IProviderApplicationStore.cs
deleted file mode 100644
index c16f1f9..0000000
--- a/src/DotNetOpenAuth/OpenId/Provider/IProviderApplicationStore.cs
+++ /dev/null
@@ -1,20 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="IProviderApplicationStore.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId.Provider {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOpenAuth.Messaging.Bindings;
-
- /// <summary>
- /// A hybrid of all the store interfaces that a Provider requires in order
- /// to operate in "smart" mode.
- /// </summary>
- public interface IProviderApplicationStore : IAssociationStore<AssociationRelyingPartyType>, INonceStore {
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/IProviderAssociationStore.cs b/src/DotNetOpenAuth/OpenId/Provider/IProviderAssociationStore.cs
new file mode 100644
index 0000000..5a554c1
--- /dev/null
+++ b/src/DotNetOpenAuth/OpenId/Provider/IProviderAssociationStore.cs
@@ -0,0 +1,90 @@
+//-----------------------------------------------------------------------
+// <copyright file="IProviderAssociationStore.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Provider {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// Provides association serialization and deserialization.
+ /// </summary>
+ /// <remarks>
+ /// Implementations may choose to store the association details in memory or a database table and simply return a
+ /// short, randomly generated string that is the key to that data. Alternatively, an implementation may
+ /// sign and encrypt the association details and then encode the results as a base64 string and return that value
+ /// as the association handle, thereby avoiding any association persistence at the OpenID Provider.
+ /// When taking the latter approach however, it is of course imperative that the association be encrypted
+ /// to avoid disclosing the secret to anyone who sees the association handle, which itself isn't considered to
+ /// be confidential.
+ /// </remarks>
+ [ContractClass(typeof(IProviderAssociationStoreContract))]
+ internal interface IProviderAssociationStore {
+ /// <summary>
+ /// Stores an association and returns a handle for it.
+ /// </summary>
+ /// <param name="secret">The association secret.</param>
+ /// <param name="expiresUtc">The UTC time that the association should expire.</param>
+ /// <param name="privateAssociation">A value indicating whether this is a private association.</param>
+ /// <returns>
+ /// The association handle that represents this association.
+ /// </returns>
+ string Serialize(byte[] secret, DateTime expiresUtc, bool privateAssociation);
+
+ /// <summary>
+ /// Retrieves an association given an association handle.
+ /// </summary>
+ /// <param name="containingMessage">The OpenID message that referenced this association handle.</param>
+ /// <param name="privateAssociation">A value indicating whether a private association is expected.</param>
+ /// <param name="handle">The association handle.</param>
+ /// <returns>
+ /// An association instance, or <c>null</c> if the association has expired or the signature is incorrect (which may be because the OP's symmetric key has changed).
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown if the association is not of the expected type.</exception>
+ Association Deserialize(IProtocolMessage containingMessage, bool privateAssociation, string handle);
+ }
+
+ /// <summary>
+ /// Code contract for the <see cref="IProviderAssociationStore"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IProviderAssociationStore))]
+ internal abstract class IProviderAssociationStoreContract : IProviderAssociationStore {
+ /// <summary>
+ /// Stores an association and returns a handle for it.
+ /// </summary>
+ /// <param name="secret">The association secret.</param>
+ /// <param name="expiresUtc">The expires UTC.</param>
+ /// <param name="privateAssociation">A value indicating whether this is a private association.</param>
+ /// <returns>
+ /// The association handle that represents this association.
+ /// </returns>
+ string IProviderAssociationStore.Serialize(byte[] secret, DateTime expiresUtc, bool privateAssociation) {
+ Contract.Requires<ArgumentNullException>(secret != null);
+ Contract.Requires<ArgumentException>(expiresUtc.Kind == DateTimeKind.Utc);
+ Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Retrieves an association given an association handle.
+ /// </summary>
+ /// <param name="containingMessage">The OpenID message that referenced this association handle.</param>
+ /// <param name="privateAssociation">A value indicating whether a private association is expected.</param>
+ /// <param name="handle">The association handle.</param>
+ /// <returns>
+ /// An association instance, or <c>null</c> if the association has expired or the signature is incorrect (which may be because the OP's symmetric key has changed).
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown if the association is not of the expected type.</exception>
+ Association IProviderAssociationStore.Deserialize(IProtocolMessage containingMessage, bool privateAssociation, string handle) {
+ Contract.Requires<ArgumentNullException>(containingMessage != null);
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(handle));
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/OpenIdProvider.cs b/src/DotNetOpenAuth/OpenId/Provider/OpenIdProvider.cs
index 3b4cb56..58dfc2f 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/OpenIdProvider.cs
+++ b/src/DotNetOpenAuth/OpenId/Provider/OpenIdProvider.cs
@@ -55,7 +55,6 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// </summary>
public OpenIdProvider()
: this(DotNetOpenAuthSection.Configuration.OpenId.Provider.ApplicationStore.CreateInstance(HttpApplicationStore)) {
- Contract.Ensures(this.AssociationStore != null);
Contract.Ensures(this.SecuritySettings != null);
Contract.Ensures(this.Channel != null);
}
@@ -64,10 +63,9 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// Initializes a new instance of the <see cref="OpenIdProvider"/> class.
/// </summary>
/// <param name="applicationStore">The application store to use. Cannot be null.</param>
- public OpenIdProvider(IProviderApplicationStore applicationStore)
- : this(applicationStore, applicationStore) {
+ public OpenIdProvider(IOpenIdApplicationStore applicationStore)
+ : this((INonceStore)applicationStore, (ICryptoKeyStore)applicationStore) {
Contract.Requires<ArgumentNullException>(applicationStore != null);
- Contract.Ensures(this.AssociationStore == applicationStore);
Contract.Ensures(this.SecuritySettings != null);
Contract.Ensures(this.Channel != null);
}
@@ -75,25 +73,25 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// <summary>
/// Initializes a new instance of the <see cref="OpenIdProvider"/> class.
/// </summary>
- /// <param name="associationStore">The association store to use. Cannot be null.</param>
/// <param name="nonceStore">The nonce store to use. Cannot be null.</param>
- private OpenIdProvider(IAssociationStore<AssociationRelyingPartyType> associationStore, INonceStore nonceStore) {
- Contract.Requires<ArgumentNullException>(associationStore != null);
+ /// <param name="cryptoKeyStore">The crypto key store. Cannot be null.</param>
+ private OpenIdProvider(INonceStore nonceStore, ICryptoKeyStore cryptoKeyStore) {
Contract.Requires<ArgumentNullException>(nonceStore != null);
- Contract.Ensures(this.AssociationStore == associationStore);
+ Contract.Requires<ArgumentNullException>(cryptoKeyStore != null);
Contract.Ensures(this.SecuritySettings != null);
Contract.Ensures(this.Channel != null);
- this.AssociationStore = associationStore;
this.SecuritySettings = DotNetOpenAuthSection.Configuration.OpenId.Provider.SecuritySettings.CreateSecuritySettings();
this.behaviors.CollectionChanged += this.OnBehaviorsChanged;
foreach (var behavior in DotNetOpenAuthSection.Configuration.OpenId.Provider.Behaviors.CreateInstances(false)) {
this.behaviors.Add(behavior);
}
+ this.AssociationStore = new SwitchingAssociationStore(cryptoKeyStore, this.SecuritySettings);
this.Channel = new OpenIdChannel(this.AssociationStore, nonceStore, this.SecuritySettings);
+ this.CryptoKeyStore = cryptoKeyStore;
- Reporting.RecordFeatureAndDependencyUse(this, associationStore, nonceStore);
+ Reporting.RecordFeatureAndDependencyUse(this, nonceStore);
}
/// <summary>
@@ -101,16 +99,16 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// HttpApplication state dictionary to store associations and nonces.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
- public static IProviderApplicationStore HttpApplicationStore {
+ public static IOpenIdApplicationStore HttpApplicationStore {
get {
Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
- Contract.Ensures(Contract.Result<IProviderApplicationStore>() != null);
+ Contract.Ensures(Contract.Result<IOpenIdApplicationStore>() != null);
HttpContext context = HttpContext.Current;
- var store = (IProviderApplicationStore)context.Application[ApplicationStoreKey];
+ var store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey];
if (store == null) {
context.Application.Lock();
try {
- if ((store = (IProviderApplicationStore)context.Application[ApplicationStoreKey]) == null) {
+ if ((store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey]) == null) {
context.Application[ApplicationStoreKey] = store = new StandardProviderApplicationStore();
}
} finally {
@@ -168,16 +166,28 @@ namespace DotNetOpenAuth.OpenId.Provider {
}
/// <summary>
- /// Gets the list of services that can perform discovery on identifiers given to this relying party.
+ /// Gets the crypto key store.
/// </summary>
- internal IList<IIdentifierDiscoveryService> DiscoveryServices {
- get { return this.RelyingParty.DiscoveryServices; }
- }
+ public ICryptoKeyStore CryptoKeyStore { get; private set; }
/// <summary>
/// Gets the association store.
/// </summary>
- internal IAssociationStore<AssociationRelyingPartyType> AssociationStore { get; private set; }
+ internal IProviderAssociationStore AssociationStore { get; private set; }
+
+ /// <summary>
+ /// Gets the channel.
+ /// </summary>
+ internal OpenIdChannel OpenIdChannel {
+ get { return (OpenIdChannel)this.Channel; }
+ }
+
+ /// <summary>
+ /// Gets the list of services that can perform discovery on identifiers given to this relying party.
+ /// </summary>
+ internal IList<IIdentifierDiscoveryService> DiscoveryServices {
+ get { return this.RelyingParty.DiscoveryServices; }
+ }
/// <summary>
/// Gets the web request handler to use for discovery and the part of
@@ -316,6 +326,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// </remarks>
/// <exception cref="InvalidOperationException">Thrown if <see cref="IRequest.IsResponseReady"/> is <c>false</c>.</exception>
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Code Contract requires that we cast early.")]
+ [EditorBrowsable(EditorBrowsableState.Never), Obsolete("Use the Respond method instead, and prepare for execution to continue on this page beyond the call to Respond.")]
public void SendResponse(IRequest request) {
Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired);
Contract.Requires<ArgumentNullException>(request != null);
@@ -327,6 +338,27 @@ namespace DotNetOpenAuth.OpenId.Provider {
}
/// <summary>
+ /// Sends the response to a received request.
+ /// </summary>
+ /// <param name="request">The incoming OpenID request whose response is to be sent.</param>
+ /// <remarks>
+ /// <para>Requires an HttpContext.Current context. If one is not available, the caller should use
+ /// <see cref="PrepareResponse"/> instead and manually send the <see cref="OutgoingWebResponse"/>
+ /// to the client.</para>
+ /// </remarks>
+ /// <exception cref="InvalidOperationException">Thrown if <see cref="IRequest.IsResponseReady"/> is <c>false</c>.</exception>
+ [SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "Code Contract requires that we cast early.")]
+ public void Respond(IRequest request) {
+ Contract.Requires<InvalidOperationException>(HttpContext.Current != null, MessagingStrings.CurrentHttpContextRequired);
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<ArgumentException>(request.IsResponseReady);
+
+ this.ApplyBehaviorsToResponse(request);
+ Request requestInternal = (Request)request;
+ this.Channel.Respond(requestInternal.Response);
+ }
+
+ /// <summary>
/// Gets the response to a received request.
/// </summary>
/// <param name="request">The request.</param>
@@ -365,7 +397,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
Contract.Requires<ArgumentNullException>(claimedIdentifier != null);
Contract.Requires<ArgumentNullException>(localIdentifier != null);
- this.PrepareUnsolicitedAssertion(providerEndpoint, relyingPartyRealm, claimedIdentifier, localIdentifier, extensions).Send();
+ this.PrepareUnsolicitedAssertion(providerEndpoint, relyingPartyRealm, claimedIdentifier, localIdentifier, extensions).Respond();
}
/// <summary>
@@ -557,5 +589,74 @@ namespace DotNetOpenAuth.OpenId.Provider {
Reporting.RecordFeatureUse(profile);
}
}
+
+ /// <summary>
+ /// Provides a single OP association store instance that can handle switching between
+ /// association handle encoding modes.
+ /// </summary>
+ private class SwitchingAssociationStore : IProviderAssociationStore {
+ /// <summary>
+ /// The security settings of the Provider.
+ /// </summary>
+ private readonly ProviderSecuritySettings securitySettings;
+
+ /// <summary>
+ /// The association store that records association secrets in the association handles themselves.
+ /// </summary>
+ private IProviderAssociationStore associationHandleEncoder;
+
+ /// <summary>
+ /// The association store that records association secrets in a secret store.
+ /// </summary>
+ private IProviderAssociationStore associationSecretStorage;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="SwitchingAssociationStore"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store.</param>
+ /// <param name="securitySettings">The security settings.</param>
+ internal SwitchingAssociationStore(ICryptoKeyStore cryptoKeyStore, ProviderSecuritySettings securitySettings) {
+ Contract.Requires<ArgumentNullException>(cryptoKeyStore != null);
+ Contract.Requires<ArgumentNullException>(securitySettings != null);
+ this.securitySettings = securitySettings;
+
+ this.associationHandleEncoder = new ProviderAssociationHandleEncoder(cryptoKeyStore);
+ this.associationSecretStorage = new ProviderAssociationKeyStorage(cryptoKeyStore);
+ }
+
+ /// <summary>
+ /// Gets the association store that applies given the Provider's current security settings.
+ /// </summary>
+ internal IProviderAssociationStore AssociationStore {
+ get { return this.securitySettings.EncodeAssociationSecretsInHandles ? this.associationHandleEncoder : this.associationSecretStorage; }
+ }
+
+ /// <summary>
+ /// Stores an association and returns a handle for it.
+ /// </summary>
+ /// <param name="secret">The association secret.</param>
+ /// <param name="expiresUtc">The UTC time that the association should expire.</param>
+ /// <param name="privateAssociation">A value indicating whether this is a private association.</param>
+ /// <returns>
+ /// The association handle that represents this association.
+ /// </returns>
+ public string Serialize(byte[] secret, DateTime expiresUtc, bool privateAssociation) {
+ return this.AssociationStore.Serialize(secret, expiresUtc, privateAssociation);
+ }
+
+ /// <summary>
+ /// Retrieves an association given an association handle.
+ /// </summary>
+ /// <param name="containingMessage">The OpenID message that referenced this association handle.</param>
+ /// <param name="isPrivateAssociation">A value indicating whether a private association is expected.</param>
+ /// <param name="handle">The association handle.</param>
+ /// <returns>
+ /// An association instance, or <c>null</c> if the association has expired or the signature is incorrect (which may be because the OP's symmetric key has changed).
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown if the association is not of the expected type.</exception>
+ public Association Deserialize(IProtocolMessage containingMessage, bool isPrivateAssociation, string handle) {
+ return this.AssociationStore.Deserialize(containingMessage, isPrivateAssociation, handle);
+ }
+ }
}
}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/ProviderAssociationHandleEncoder.cs b/src/DotNetOpenAuth/OpenId/Provider/ProviderAssociationHandleEncoder.cs
new file mode 100644
index 0000000..5de560c
--- /dev/null
+++ b/src/DotNetOpenAuth/OpenId/Provider/ProviderAssociationHandleEncoder.cs
@@ -0,0 +1,84 @@
+//-----------------------------------------------------------------------
+// <copyright file="ProviderAssociationHandleEncoder.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Provider {
+ using System;
+ using System.Diagnostics.Contracts;
+ using System.Threading;
+ using DotNetOpenAuth.Configuration;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// Provides association storage in the association handle itself, but embedding signed and encrypted association
+ /// details in the handle.
+ /// </summary>
+ public class ProviderAssociationHandleEncoder : IProviderAssociationStore {
+ /// <summary>
+ /// The name of the bucket in which to store keys that encrypt association data into association handles.
+ /// </summary>
+ internal const string AssociationHandleEncodingSecretBucket = "https://localhost/dnoa/association_handles";
+
+ /// <summary>
+ /// The crypto key store used to persist encryption keys.
+ /// </summary>
+ private readonly ICryptoKeyStore cryptoKeyStore;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ProviderAssociationHandleEncoder"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The crypto key store.</param>
+ public ProviderAssociationHandleEncoder(ICryptoKeyStore cryptoKeyStore) {
+ Contract.Requires<ArgumentNullException>(cryptoKeyStore != null);
+ this.cryptoKeyStore = cryptoKeyStore;
+ }
+
+ /// <summary>
+ /// Encodes the specified association data bag.
+ /// </summary>
+ /// <param name="secret">The symmetric secret.</param>
+ /// <param name="expiresUtc">The UTC time that the association should expire.</param>
+ /// <param name="privateAssociation">A value indicating whether this is a private association.</param>
+ /// <returns>
+ /// The association handle that represents this association.
+ /// </returns>
+ public string Serialize(byte[] secret, DateTime expiresUtc, bool privateAssociation) {
+ var associationDataBag = new AssociationDataBag {
+ Secret = secret,
+ IsPrivateAssociation = privateAssociation,
+ ExpiresUtc = expiresUtc,
+ };
+
+ var formatter = AssociationDataBag.CreateFormatter(this.cryptoKeyStore, AssociationHandleEncodingSecretBucket, expiresUtc - DateTime.UtcNow);
+ return formatter.Serialize(associationDataBag);
+ }
+
+ /// <summary>
+ /// Retrieves an association given an association handle.
+ /// </summary>
+ /// <param name="containingMessage">The OpenID message that referenced this association handle.</param>
+ /// <param name="privateAssociation">A value indicating whether a private association is expected.</param>
+ /// <param name="handle">The association handle.</param>
+ /// <returns>
+ /// An association instance, or <c>null</c> if the association has expired or the signature is incorrect (which may be because the OP's symmetric key has changed).
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown if the association is not of the expected type.</exception>
+ public Association Deserialize(IProtocolMessage containingMessage, bool privateAssociation, string handle) {
+ var formatter = AssociationDataBag.CreateFormatter(this.cryptoKeyStore, AssociationHandleEncodingSecretBucket);
+ AssociationDataBag bag;
+ try {
+ bag = formatter.Deserialize(containingMessage, handle);
+ } catch (ProtocolException ex) {
+ Logger.OpenId.Error("Rejecting an association because deserialization of the encoded handle failed.", ex);
+ return null;
+ }
+
+ ErrorUtilities.VerifyProtocol(bag.IsPrivateAssociation == privateAssociation, "Unexpected association type.");
+ Association assoc = Association.Deserialize(handle, bag.ExpiresUtc, bag.Secret);
+ return assoc.IsExpired ? null : assoc;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/ProviderAssociationKeyStorage.cs b/src/DotNetOpenAuth/OpenId/Provider/ProviderAssociationKeyStorage.cs
new file mode 100644
index 0000000..9801aac
--- /dev/null
+++ b/src/DotNetOpenAuth/OpenId/Provider/ProviderAssociationKeyStorage.cs
@@ -0,0 +1,79 @@
+//-----------------------------------------------------------------------
+// <copyright file="ProviderAssociationKeyStorage.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.Provider {
+ using System;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// An association storage mechanism that stores the association secrets in a private store,
+ /// and returns randomly generated association handles to refer to these secrets.
+ /// </summary>
+ internal class ProviderAssociationKeyStorage : IProviderAssociationStore {
+ /// <summary>
+ /// The bucket to use when recording shared associations.
+ /// </summary>
+ internal const string SharedAssociationBucket = "https://localhost/dnoa/shared_associations";
+
+ /// <summary>
+ /// The bucket to use when recording private associations.
+ /// </summary>
+ internal const string PrivateAssociationBucket = "https://localhost/dnoa/private_associations";
+
+ /// <summary>
+ /// The backing crypto key store.
+ /// </summary>
+ private readonly ICryptoKeyStore cryptoKeyStore;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ProviderAssociationKeyStorage"/> class.
+ /// </summary>
+ /// <param name="cryptoKeyStore">The store where association secrets will be recorded.</param>
+ internal ProviderAssociationKeyStorage(ICryptoKeyStore cryptoKeyStore) {
+ Contract.Requires<ArgumentNullException>(cryptoKeyStore != null);
+ this.cryptoKeyStore = cryptoKeyStore;
+ }
+
+ /// <summary>
+ /// Stores an association and returns a handle for it.
+ /// </summary>
+ /// <param name="secret">The association secret.</param>
+ /// <param name="expiresUtc">The UTC time that the association should expire.</param>
+ /// <param name="privateAssociation">A value indicating whether this is a private association.</param>
+ /// <returns>
+ /// The association handle that represents this association.
+ /// </returns>
+ public string Serialize(byte[] secret, DateTime expiresUtc, bool privateAssociation) {
+ string handle;
+ this.cryptoKeyStore.StoreKey(
+ privateAssociation ? PrivateAssociationBucket : SharedAssociationBucket,
+ handle = OpenIdUtilities.GenerateRandomAssociationHandle(),
+ new CryptoKey(secret, expiresUtc));
+ return handle;
+ }
+
+ /// <summary>
+ /// Retrieves an association given an association handle.
+ /// </summary>
+ /// <param name="containingMessage">The OpenID message that referenced this association handle.</param>
+ /// <param name="isPrivateAssociation">A value indicating whether a private association is expected.</param>
+ /// <param name="handle">The association handle.</param>
+ /// <returns>
+ /// An association instance, or <c>null</c> if the association has expired or the signature is incorrect (which may be because the OP's symmetric key has changed).
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown if the association is not of the expected type.</exception>
+ public Association Deserialize(IProtocolMessage containingMessage, bool isPrivateAssociation, string handle) {
+ var key = this.cryptoKeyStore.GetKey(isPrivateAssociation ? PrivateAssociationBucket : SharedAssociationBucket, handle);
+ if (key != null) {
+ return Association.Deserialize(handle, key.ExpiresUtc, key.Key);
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/ProviderEndpoint.cs b/src/DotNetOpenAuth/OpenId/Provider/ProviderEndpoint.cs
index e792a81..821d95c 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/ProviderEndpoint.cs
+++ b/src/DotNetOpenAuth/OpenId/Provider/ProviderEndpoint.cs
@@ -180,7 +180,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
public static void SendResponse() {
var pendingRequest = PendingRequest;
PendingRequest = null;
- Provider.SendResponse(pendingRequest);
+ Provider.Respond(pendingRequest);
}
/// <summary>
@@ -222,8 +222,7 @@ namespace DotNetOpenAuth.OpenId.Provider {
}
}
if (request.IsResponseReady) {
- Provider.SendResponse(request);
- Page.Response.End();
+ Provider.Respond(request);
PendingAuthenticationRequest = null;
}
}
diff --git a/src/DotNetOpenAuth/OpenId/Provider/ProviderSecuritySettings.cs b/src/DotNetOpenAuth/OpenId/Provider/ProviderSecuritySettings.cs
index d5fa4a9..130e6dd 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/ProviderSecuritySettings.cs
+++ b/src/DotNetOpenAuth/OpenId/Provider/ProviderSecuritySettings.cs
@@ -24,6 +24,11 @@ namespace DotNetOpenAuth.OpenId.Provider {
internal const bool ProtectDownlevelReplayAttacksDefault = true;
/// <summary>
+ /// The default value for the <see cref="EncodeAssociationSecretsInHandles"/> property.
+ /// </summary>
+ internal const bool EncodeAssociationSecretsInHandlesDefault = true;
+
+ /// <summary>
/// The default value for the <see cref="SignOutgoingExtensions"/> property.
/// </summary>
internal const bool SignOutgoingExtensionsDefault = true;
@@ -102,6 +107,14 @@ namespace DotNetOpenAuth.OpenId.Provider {
public UnsolicitedAssertionVerificationLevel UnsolicitedAssertionVerification { get; set; }
/// <summary>
+ /// Gets or sets a value indicating whether the Provider should ease the burden of storing associations
+ /// by encoding them in signed, encrypted form into the association handles themselves, storing only
+ /// a few rotating, private symmetric keys in the Provider's store instead.
+ /// </summary>
+ /// <value>The default value for this property is <c>true</c>.</value>
+ public bool EncodeAssociationSecretsInHandles { get; set; }
+
+ /// <summary>
/// Gets or sets a value indicating whether OpenID 1.x relying parties that may not be
/// protecting their users from replay attacks are protected from
/// replay attacks by this provider.
diff --git a/src/DotNetOpenAuth/OpenId/Provider/StandardProviderApplicationStore.cs b/src/DotNetOpenAuth/OpenId/Provider/StandardProviderApplicationStore.cs
index 4fa2d64..c13c4bc 100644
--- a/src/DotNetOpenAuth/OpenId/Provider/StandardProviderApplicationStore.cs
+++ b/src/DotNetOpenAuth/OpenId/Provider/StandardProviderApplicationStore.cs
@@ -6,6 +6,7 @@
namespace DotNetOpenAuth.OpenId.Provider {
using System;
+ using System.Collections.Generic;
using DotNetOpenAuth.Configuration;
using DotNetOpenAuth.Messaging.Bindings;
@@ -18,112 +19,97 @@ namespace DotNetOpenAuth.OpenId.Provider {
/// out of the box on most single-server web sites. It is highly recommended
/// that high traffic web sites consider using a database to store the information
/// used by an OpenID Provider and write a custom implementation of the
- /// <see cref="IProviderApplicationStore"/> interface to use instead of this
+ /// <see cref="IOpenIdApplicationStore"/> interface to use instead of this
/// class.
/// </remarks>
- public class StandardProviderApplicationStore : IProviderApplicationStore {
+ public class StandardProviderApplicationStore : IOpenIdApplicationStore {
/// <summary>
/// The nonce store to use.
/// </summary>
private readonly INonceStore nonceStore;
/// <summary>
- /// The association store to use.
+ /// The crypto key store where symmetric keys are persisted.
/// </summary>
- private readonly IAssociationStore<AssociationRelyingPartyType> associationStore;
+ private readonly ICryptoKeyStore cryptoKeyStore;
/// <summary>
/// Initializes a new instance of the <see cref="StandardProviderApplicationStore"/> class.
/// </summary>
public StandardProviderApplicationStore() {
this.nonceStore = new NonceMemoryStore(DotNetOpenAuthSection.Configuration.OpenId.MaxAuthenticationTime);
- this.associationStore = new AssociationMemoryStore<AssociationRelyingPartyType>();
+ this.cryptoKeyStore = new MemoryCryptoKeyStore();
}
- #region IAssociationStore<AssociationRelyingPartyType> Members
-
- /// <summary>
- /// Saves an <see cref="Association"/> for later recall.
- /// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for providers).</param>
- /// <param name="association">The association to store.</param>
- public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association association) {
- this.associationStore.StoreAssociation(distinguishingFactor, association);
- }
+ #region INonceStore Members
/// <summary>
- /// Gets the best association (the one with the longest remaining life) for a given key.
+ /// Stores a given nonce and timestamp.
/// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="securityRequirements">The security requirements that the returned association must meet.</param>
+ /// <param name="context">The context, or namespace, within which the <paramref name="nonce"/> must be unique.</param>
+ /// <param name="nonce">A series of random characters.</param>
+ /// <param name="timestampUtc">The timestamp that together with the nonce string make it unique.
+ /// The timestamp may also be used by the data store to clear out old nonces.</param>
/// <returns>
- /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
+ /// True if the nonce+timestamp (combination) was not previously in the database.
+ /// False if the nonce was stored previously with the same timestamp.
/// </returns>
/// <remarks>
- /// In the event that multiple associations exist for the given
- /// <paramref name="distinguishingFactor"/>, it is important for the
- /// implementation for this method to use the <paramref name="securityRequirements"/>
- /// to pick the best (highest grade or longest living as the host's policy may dictate)
- /// association that fits the security requirements.
- /// Associations that are returned that do not meet the security requirements will be
- /// ignored and a new association created.
+ /// The nonce must be stored for no less than the maximum time window a message may
+ /// be processed within before being discarded as an expired message.
+ /// If the binding element is applicable to your channel, this expiration window
+ /// is retrieved or set using the
+ /// <see cref="StandardExpirationBindingElement.MaximumMessageAge"/> property.
/// </remarks>
- public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, SecuritySettings securityRequirements) {
- return this.associationStore.GetAssociation(distinguishingFactor, securityRequirements);
+ public bool StoreNonce(string context, string nonce, DateTime timestampUtc) {
+ return this.nonceStore.StoreNonce(context, nonce, timestampUtc);
}
+ #endregion
+
+ #region ICryptoKeyStore
+
/// <summary>
- /// Gets the association for a given key and handle.
+ /// Gets the key in a given bucket and handle.
/// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be recalled.</param>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
/// <returns>
- /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.
+ /// The cryptographic key, or <c>null</c> if no matching key was found.
/// </returns>
- public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) {
- return this.associationStore.GetAssociation(distinguishingFactor, handle);
+ public CryptoKey GetKey(string bucket, string handle) {
+ return this.cryptoKeyStore.GetKey(bucket, handle);
}
/// <summary>
- /// Removes a specified handle that may exist in the store.
+ /// Gets a sequence of existing keys within a given bucket.
/// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be deleted.</param>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
/// <returns>
- /// True if the association existed in this store previous to this call.
+ /// A sequence of handles and keys, ordered by descending <see cref="CryptoKey.ExpiresUtc"/>.
/// </returns>
- /// <remarks>
- /// No exception should be thrown if the association does not exist in the store
- /// before this call.
- /// </remarks>
- public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) {
- return this.associationStore.RemoveAssociation(distinguishingFactor, handle);
+ public IEnumerable<KeyValuePair<string, CryptoKey>> GetKeys(string bucket) {
+ return this.cryptoKeyStore.GetKeys(bucket);
}
- #endregion
-
- #region INonceStore Members
+ /// <summary>
+ /// Stores a cryptographic key.
+ /// </summary>
+ /// <param name="bucket">The name of the bucket to store the key in. Case sensitive.</param>
+ /// <param name="handle">The handle to the key, unique within the bucket. Case sensitive.</param>
+ /// <param name="key">The key to store.</param>
+ /// <exception cref="CryptoKeyCollisionException">Thrown in the event of a conflict with an existing key in the same bucket and with the same handle.</exception>
+ public void StoreKey(string bucket, string handle, CryptoKey key) {
+ this.cryptoKeyStore.StoreKey(bucket, handle, key);
+ }
/// <summary>
- /// Stores a given nonce and timestamp.
+ /// Removes the key.
/// </summary>
- /// <param name="context">The context, or namespace, within which the <paramref name="nonce"/> must be unique.</param>
- /// <param name="nonce">A series of random characters.</param>
- /// <param name="timestampUtc">The timestamp that together with the nonce string make it unique.
- /// The timestamp may also be used by the data store to clear out old nonces.</param>
- /// <returns>
- /// True if the nonce+timestamp (combination) was not previously in the database.
- /// False if the nonce was stored previously with the same timestamp.
- /// </returns>
- /// <remarks>
- /// The nonce must be stored for no less than the maximum time window a message may
- /// be processed within before being discarded as an expired message.
- /// If the binding element is applicable to your channel, this expiration window
- /// is retrieved or set using the
- /// <see cref="StandardExpirationBindingElement.MaximumMessageAge"/> property.
- /// </remarks>
- public bool StoreNonce(string context, string nonce, DateTime timestampUtc) {
- return this.nonceStore.StoreNonce(context, nonce, timestampUtc);
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ public void RemoveKey(string bucket, string handle) {
+ this.cryptoKeyStore.RemoveKey(bucket, handle);
}
#endregion
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/AssociationManager.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/AssociationManager.cs
index 1ae2726..9a43506 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/AssociationManager.cs
+++ b/src/DotNetOpenAuth/OpenId/RelyingParty/AssociationManager.cs
@@ -23,7 +23,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <summary>
/// The storage to use for saving and retrieving associations. May be null.
/// </summary>
- private readonly IAssociationStore<Uri> associationStore;
+ private readonly IRelyingPartyAssociationStore associationStore;
/// <summary>
/// Backing field for the <see cref="Channel"/> property.
@@ -41,7 +41,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <param name="channel">The channel the relying party is using.</param>
/// <param name="associationStore">The association store. May be null for dumb mode relying parties.</param>
/// <param name="securitySettings">The security settings.</param>
- internal AssociationManager(Channel channel, IAssociationStore<Uri> associationStore, RelyingPartySecuritySettings securitySettings) {
+ internal AssociationManager(Channel channel, IRelyingPartyAssociationStore associationStore, RelyingPartySecuritySettings securitySettings) {
Contract.Requires<ArgumentNullException>(channel != null);
Contract.Requires<ArgumentNullException>(securitySettings != null);
@@ -93,7 +93,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <summary>
/// Gets the storage to use for saving and retrieving associations. May be null.
/// </summary>
- internal IAssociationStore<Uri> AssociationStoreTestHook {
+ internal IRelyingPartyAssociationStore AssociationStoreTestHook {
get { return this.associationStore; }
}
@@ -196,7 +196,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
var associateSuccessfulResponse = associateResponse as AssociateSuccessfulResponse;
var associateUnsuccessfulResponse = associateResponse as AssociateUnsuccessfulResponse;
if (associateSuccessfulResponse != null) {
- Association association = associateSuccessfulResponse.CreateAssociation(associateRequest, null);
+ Association association = associateSuccessfulResponse.CreateAssociation(associateRequest, null, null);
this.associationStore.StoreAssociation(provider.Uri, association);
return association;
} else if (associateUnsuccessfulResponse != null) {
diff --git a/src/DotNetOpenAuth/OpenId/Associations.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/Associations.cs
index cf49d1c..b171bec 100644
--- a/src/DotNetOpenAuth/OpenId/Associations.cs
+++ b/src/DotNetOpenAuth/OpenId/RelyingParty/Associations.cs
@@ -4,7 +4,7 @@
// </copyright>
//-----------------------------------------------------------------------
-namespace DotNetOpenAuth.OpenId {
+namespace DotNetOpenAuth.OpenId.RelyingParty {
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/AuthenticationRequest.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/AuthenticationRequest.cs
index 3a17263..8bbf04f 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/AuthenticationRequest.cs
+++ b/src/DotNetOpenAuth/OpenId/RelyingParty/AuthenticationRequest.cs
@@ -212,7 +212,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// small to ensure successful authentication. About 1.5KB is about all that should be stored.</para>
/// </remarks>
public void AddCallbackArguments(IDictionary<string, string> arguments) {
- ErrorUtilities.VerifyOperation(this.RelyingParty.CanSignCallbackArguments, OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IAssociationStore<Uri>).Name, typeof(OpenIdRelyingParty).Name);
+ ErrorUtilities.VerifyOperation(this.RelyingParty.CanSignCallbackArguments, OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IRelyingPartyAssociationStore).Name, typeof(OpenIdRelyingParty).Name);
this.returnToArgsMustBeSigned = true;
foreach (var pair in arguments) {
@@ -239,7 +239,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// small to ensure successful authentication. About 1.5KB is about all that should be stored.</para>
/// </remarks>
public void AddCallbackArguments(string key, string value) {
- ErrorUtilities.VerifyOperation(this.RelyingParty.CanSignCallbackArguments, OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IAssociationStore<Uri>).Name, typeof(OpenIdRelyingParty).Name);
+ ErrorUtilities.VerifyOperation(this.RelyingParty.CanSignCallbackArguments, OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IRelyingPartyAssociationStore).Name, typeof(OpenIdRelyingParty).Name);
this.returnToArgsMustBeSigned = true;
this.returnToArgs.Add(key, value);
@@ -260,7 +260,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// small to ensure successful authentication. About 1.5KB is about all that should be stored.</para>
/// </remarks>
public void SetCallbackArgument(string key, string value) {
- ErrorUtilities.VerifyOperation(this.RelyingParty.CanSignCallbackArguments, OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IAssociationStore<Uri>).Name, typeof(OpenIdRelyingParty).Name);
+ ErrorUtilities.VerifyOperation(this.RelyingParty.CanSignCallbackArguments, OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IRelyingPartyAssociationStore).Name, typeof(OpenIdRelyingParty).Name);
this.returnToArgsMustBeSigned = true;
this.returnToArgs[key] = value;
@@ -295,14 +295,12 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <summary>
/// Redirects the user agent to the provider for authentication.
- /// Execution of the current page terminates after this call.
/// </summary>
/// <remarks>
/// This method requires an ASP.NET HttpContext.
/// </remarks>
- /// <exception cref="ThreadAbortException">Typically thrown by ASP.NET in order to prevent additional data from the page being sent to the client and corrupting the response.</exception>
public void RedirectToProvider() {
- this.RedirectingResponse.Send();
+ this.RedirectingResponse.Respond();
}
#endregion
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/CryptoKeyStoreAsRelyingPartyAssociationStore.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/CryptoKeyStoreAsRelyingPartyAssociationStore.cs
new file mode 100644
index 0000000..02ed3b0
--- /dev/null
+++ b/src/DotNetOpenAuth/OpenId/RelyingParty/CryptoKeyStoreAsRelyingPartyAssociationStore.cs
@@ -0,0 +1,87 @@
+//-----------------------------------------------------------------------
+// <copyright file="CryptoKeyStoreAsRelyingPartyAssociationStore.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.RelyingParty {
+ using System;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <summary>
+ /// Wraps a standard <see cref="ICryptoKeyStore"/> so that it behaves as an association store.
+ /// </summary>
+ internal class CryptoKeyStoreAsRelyingPartyAssociationStore : IRelyingPartyAssociationStore {
+ /// <summary>
+ /// The underlying key store.
+ /// </summary>
+ private readonly ICryptoKeyStore keyStore;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="CryptoKeyStoreAsRelyingPartyAssociationStore"/> class.
+ /// </summary>
+ /// <param name="keyStore">The key store.</param>
+ internal CryptoKeyStoreAsRelyingPartyAssociationStore(ICryptoKeyStore keyStore) {
+ Contract.Requires<ArgumentNullException>(keyStore != null);
+ Contract.Ensures(this.keyStore == keyStore);
+ this.keyStore = keyStore;
+ }
+
+ /// <summary>
+ /// Saves an <see cref="Association"/> for later recall.
+ /// </summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="association">The association to store.</param>
+ public void StoreAssociation(Uri providerEndpoint, Association association) {
+ var cryptoKey = new CryptoKey(association.SerializePrivateData(), association.Expires);
+ this.keyStore.StoreKey(providerEndpoint.AbsoluteUri, association.Handle, cryptoKey);
+ }
+
+ /// <summary>
+ /// Gets the best association (the one with the longest remaining life) for a given key.
+ /// </summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="securityRequirements">The security requirements that the returned association must meet.</param>
+ /// <returns>
+ /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
+ /// </returns>
+ public Association GetAssociation(Uri providerEndpoint, SecuritySettings securityRequirements) {
+ var matches = from cryptoKey in this.keyStore.GetKeys(providerEndpoint.AbsoluteUri)
+ where cryptoKey.Value.ExpiresUtc > DateTime.UtcNow
+ orderby cryptoKey.Value.ExpiresUtc descending
+ let assoc = Association.Deserialize(cryptoKey.Key, cryptoKey.Value.ExpiresUtc, cryptoKey.Value.Key)
+ where assoc.HashBitLength >= securityRequirements.MinimumHashBitLength
+ where assoc.HashBitLength <= securityRequirements.MaximumHashBitLength
+ select assoc;
+ return matches.FirstOrDefault();
+ }
+
+ /// <summary>
+ /// Gets the association for a given key and handle.
+ /// </summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="handle">The handle of the specific association that must be recalled.</param>
+ /// <returns>
+ /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.
+ /// </returns>
+ public Association GetAssociation(Uri providerEndpoint, string handle) {
+ var cryptoKey = this.keyStore.GetKey(providerEndpoint.AbsoluteUri, handle);
+ return cryptoKey != null ? Association.Deserialize(handle, cryptoKey.ExpiresUtc, cryptoKey.Key) : null;
+ }
+
+ /// <summary>
+ /// Removes a specified handle that may exist in the store.
+ /// </summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="handle">The handle of the specific association that must be deleted.</param>
+ /// <returns>
+ /// True if the association existed in this store previous to this call.
+ /// </returns>
+ public bool RemoveAssociation(Uri providerEndpoint, string handle) {
+ this.keyStore.RemoveKey(providerEndpoint.AbsoluteUri, handle);
+ return true; // return value isn't used by DNOA.
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/IRelyingPartyApplicationStore.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/IRelyingPartyApplicationStore.cs
deleted file mode 100644
index 77838c8..0000000
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/IRelyingPartyApplicationStore.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="IRelyingPartyApplicationStore.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId.RelyingParty {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using DotNetOpenAuth.Messaging.Bindings;
- using DotNetOpenAuth.OpenId.ChannelElements;
-
- /// <summary>
- /// A hybrid of all the store interfaces that a Relying Party requires in order
- /// to operate in "smart" mode.
- /// </summary>
- public interface IRelyingPartyApplicationStore : IAssociationStore<Uri>, INonceStore {
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/IRelyingPartyAssociationStore.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/IRelyingPartyAssociationStore.cs
new file mode 100644
index 0000000..21a2c53
--- /dev/null
+++ b/src/DotNetOpenAuth/OpenId/RelyingParty/IRelyingPartyAssociationStore.cs
@@ -0,0 +1,153 @@
+//-----------------------------------------------------------------------
+// <copyright file="IRelyingPartyAssociationStore.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OpenId.RelyingParty {
+ using System;
+ using System.Diagnostics.Contracts;
+
+ /// <summary>
+ /// Stores <see cref="Association"/>s for lookup by their handle, keeping
+ /// associations separated by a given OP Endpoint.
+ /// </summary>
+ /// <remarks>
+ /// Expired associations should be periodically cleared out of an association store.
+ /// This should be done frequently enough to avoid a memory leak, but sparingly enough
+ /// to not be a performance drain. Because this balance can vary by host, it is the
+ /// responsibility of the host to initiate this cleaning.
+ /// </remarks>
+ [ContractClass(typeof(IRelyingPartyAssociationStoreContract))]
+ public interface IRelyingPartyAssociationStore {
+ /// <summary>
+ /// Saves an <see cref="Association"/> for later recall.
+ /// </summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="association">The association to store.</param>
+ /// <remarks>
+ /// If the new association conflicts (in OP endpoint and association handle) with an existing association,
+ /// (which should never happen by the way) implementations may overwrite the previously saved association.
+ /// </remarks>
+ void StoreAssociation(Uri providerEndpoint, Association association);
+
+ /// <summary>
+ /// Gets the best association (the one with the longest remaining life) for a given key.
+ /// </summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="securityRequirements">The security requirements that the returned association must meet.</param>
+ /// <returns>
+ /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
+ /// </returns>
+ /// <remarks>
+ /// In the event that multiple associations exist for the given
+ /// <paramref name="providerEndpoint"/>, it is important for the
+ /// implementation for this method to use the <paramref name="securityRequirements"/>
+ /// to pick the best (highest grade or longest living as the host's policy may dictate)
+ /// association that fits the security requirements.
+ /// Associations that are returned that do not meet the security requirements will be
+ /// ignored and a new association created.
+ /// </remarks>
+ Association GetAssociation(Uri providerEndpoint, SecuritySettings securityRequirements);
+
+ /// <summary>
+ /// Gets the association for a given key and handle.
+ /// </summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="handle">The handle of the specific association that must be recalled.</param>
+ /// <returns>The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.</returns>
+ Association GetAssociation(Uri providerEndpoint, string handle);
+
+ /// <summary>Removes a specified handle that may exist in the store.</summary>
+ /// <param name="providerEndpoint">The OP Endpoint with which the association is established.</param>
+ /// <param name="handle">The handle of the specific association that must be deleted.</param>
+ /// <returns>
+ /// Deprecated. The return value is insignificant.
+ /// Previously: True if the association existed in this store previous to this call.
+ /// </returns>
+ /// <remarks>
+ /// No exception should be thrown if the association does not exist in the store
+ /// before this call.
+ /// </remarks>
+ bool RemoveAssociation(Uri providerEndpoint, string handle);
+ }
+
+ /// <summary>
+ /// Code Contract for the <see cref="IRelyingPartyAssociationStore"/> class.
+ /// </summary>
+ [ContractClassFor(typeof(IRelyingPartyAssociationStore))]
+ internal abstract class IRelyingPartyAssociationStoreContract : IRelyingPartyAssociationStore {
+ #region IAssociationStore Members
+
+ /// <summary>
+ /// Saves an <see cref="Association"/> for later recall.
+ /// </summary>
+ /// <param name="providerEndpoint">The Uri (for relying parties) or Smart/Dumb (for providers).</param>
+ /// <param name="association">The association to store.</param>
+ /// <remarks>
+ /// TODO: what should implementations do on association handle conflict?
+ /// </remarks>
+ void IRelyingPartyAssociationStore.StoreAssociation(Uri providerEndpoint, Association association) {
+ Contract.Requires<ArgumentNullException>(providerEndpoint != null);
+ Contract.Requires<ArgumentNullException>(association != null);
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Gets the best association (the one with the longest remaining life) for a given key.
+ /// </summary>
+ /// <param name="providerEndpoint">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
+ /// <param name="securityRequirements">The security requirements that the returned association must meet.</param>
+ /// <returns>
+ /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
+ /// </returns>
+ /// <remarks>
+ /// In the event that multiple associations exist for the given
+ /// <paramref name="providerEndpoint"/>, it is important for the
+ /// implementation for this method to use the <paramref name="securityRequirements"/>
+ /// to pick the best (highest grade or longest living as the host's policy may dictate)
+ /// association that fits the security requirements.
+ /// Associations that are returned that do not meet the security requirements will be
+ /// ignored and a new association created.
+ /// </remarks>
+ Association IRelyingPartyAssociationStore.GetAssociation(Uri providerEndpoint, SecuritySettings securityRequirements) {
+ Contract.Requires<ArgumentNullException>(providerEndpoint != null);
+ Contract.Requires<ArgumentNullException>(securityRequirements != null);
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Gets the association for a given key and handle.
+ /// </summary>
+ /// <param name="providerEndpoint">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
+ /// <param name="handle">The handle of the specific association that must be recalled.</param>
+ /// <returns>
+ /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.
+ /// </returns>
+ Association IRelyingPartyAssociationStore.GetAssociation(Uri providerEndpoint, string handle) {
+ Contract.Requires<ArgumentNullException>(providerEndpoint != null);
+ Contract.Requires(!String.IsNullOrEmpty(handle));
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Removes a specified handle that may exist in the store.
+ /// </summary>
+ /// <param name="providerEndpoint">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
+ /// <param name="handle">The handle of the specific association that must be deleted.</param>
+ /// <returns>
+ /// True if the association existed in this store previous to this call.
+ /// </returns>
+ /// <remarks>
+ /// No exception should be thrown if the association does not exist in the store
+ /// before this call.
+ /// </remarks>
+ bool IRelyingPartyAssociationStore.RemoveAssociation(Uri providerEndpoint, string handle) {
+ Contract.Requires<ArgumentNullException>(providerEndpoint != null);
+ Contract.Requires(!String.IsNullOrEmpty(handle));
+ throw new NotImplementedException();
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs
index 5978c21..652fa6b 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs
+++ b/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdAjaxRelyingParty.cs
@@ -37,7 +37,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// Initializes a new instance of the <see cref="OpenIdAjaxRelyingParty"/> class.
/// </summary>
/// <param name="applicationStore">The application store. If <c>null</c>, the relying party will always operate in "dumb mode".</param>
- public OpenIdAjaxRelyingParty(IRelyingPartyApplicationStore applicationStore)
+ public OpenIdAjaxRelyingParty(IOpenIdApplicationStore applicationStore)
: base(applicationStore) {
Reporting.RecordFeatureUse(this);
}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdMobileTextBox.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdMobileTextBox.cs
index 8684bd1..9cafb74 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdMobileTextBox.cs
+++ b/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdMobileTextBox.cs
@@ -524,7 +524,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// If set, this property must be set in each Page Load event
/// as it is not persisted across postbacks.
/// </remarks>
- public IRelyingPartyApplicationStore CustomApplicationStore { get; set; }
+ public IOpenIdApplicationStore CustomApplicationStore { get; set; }
#endregion
@@ -759,7 +759,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
// If we're in stateful mode, first use the explicitly given one on this control if there
// is one. Then try the configuration file specified one. Finally, use the default
// in-memory one that's built into OpenIdRelyingParty.
- IRelyingPartyApplicationStore store = this.Stateless ? null :
+ IOpenIdApplicationStore store = this.Stateless ? null :
(this.CustomApplicationStore ?? DotNetOpenAuthSection.Configuration.OpenId.RelyingParty.ApplicationStore.CreateInstance(OpenIdRelyingParty.HttpApplicationStore));
var rp = new OpenIdRelyingParty(store);
try {
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingParty.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingParty.cs
index 57c1f05..aec59b8 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingParty.cs
+++ b/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingParty.cs
@@ -100,21 +100,21 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// Initializes a new instance of the <see cref="OpenIdRelyingParty"/> class.
/// </summary>
/// <param name="applicationStore">The application store. If <c>null</c>, the relying party will always operate in "dumb mode".</param>
- public OpenIdRelyingParty(IRelyingPartyApplicationStore applicationStore)
+ public OpenIdRelyingParty(IOpenIdApplicationStore applicationStore)
: this(applicationStore, applicationStore) {
}
/// <summary>
/// Initializes a new instance of the <see cref="OpenIdRelyingParty"/> class.
/// </summary>
- /// <param name="associationStore">The association store. If null, the relying party will always operate in "dumb mode".</param>
+ /// <param name="cryptoKeyStore">The association store. If null, the relying party will always operate in "dumb mode".</param>
/// <param name="nonceStore">The nonce store to use. If null, the relying party will always operate in "dumb mode".</param>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Unavoidable")]
- private OpenIdRelyingParty(IAssociationStore<Uri> associationStore, INonceStore nonceStore) {
+ private OpenIdRelyingParty(ICryptoKeyStore cryptoKeyStore, INonceStore nonceStore) {
// If we are a smart-mode RP (supporting associations), then we MUST also be
// capable of storing nonces to prevent replay attacks.
// If we're a dumb-mode RP, then 2.0 OPs are responsible for preventing replays.
- Contract.Requires<ArgumentException>(associationStore == null || nonceStore != null, OpenIdStrings.AssociationStoreRequiresNonceStore);
+ Contract.Requires<ArgumentException>(cryptoKeyStore == null || nonceStore != null, OpenIdStrings.AssociationStoreRequiresNonceStore);
this.securitySettings = DotNetOpenAuthSection.Configuration.OpenId.RelyingParty.SecuritySettings.CreateSecuritySettings();
@@ -137,10 +137,14 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
this.SecuritySettings.MinimumRequiredOpenIdVersion = ProtocolVersion.V20;
}
- this.channel = new OpenIdChannel(associationStore, nonceStore, this.SecuritySettings);
- this.AssociationManager = new AssociationManager(this.Channel, associationStore, this.SecuritySettings);
+ if (cryptoKeyStore == null) {
+ cryptoKeyStore = new MemoryCryptoKeyStore();
+ }
+
+ this.channel = new OpenIdChannel(cryptoKeyStore, nonceStore, this.SecuritySettings);
+ this.AssociationManager = new AssociationManager(this.Channel, new CryptoKeyStoreAsRelyingPartyAssociationStore(cryptoKeyStore), this.SecuritySettings);
- Reporting.RecordFeatureAndDependencyUse(this, associationStore, nonceStore);
+ Reporting.RecordFeatureAndDependencyUse(this, cryptoKeyStore, nonceStore);
}
/// <summary>
@@ -160,17 +164,17 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// HttpApplication state dictionary to store associations and nonces.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
- public static IRelyingPartyApplicationStore HttpApplicationStore {
+ public static IOpenIdApplicationStore HttpApplicationStore {
get {
- Contract.Ensures(Contract.Result<IRelyingPartyApplicationStore>() != null);
+ Contract.Ensures(Contract.Result<IOpenIdApplicationStore>() != null);
HttpContext context = HttpContext.Current;
- ErrorUtilities.VerifyOperation(context != null, Strings.StoreRequiredWhenNoHttpContextAvailable, typeof(IRelyingPartyApplicationStore).Name);
- var store = (IRelyingPartyApplicationStore)context.Application[ApplicationStoreKey];
+ ErrorUtilities.VerifyOperation(context != null, Strings.StoreRequiredWhenNoHttpContextAvailable, typeof(IOpenIdApplicationStore).Name);
+ var store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey];
if (store == null) {
context.Application.Lock();
try {
- if ((store = (IRelyingPartyApplicationStore)context.Application[ApplicationStoreKey]) == null) {
+ if ((store = (IOpenIdApplicationStore)context.Application[ApplicationStoreKey]) == null) {
context.Application[ApplicationStoreKey] = store = new StandardRelyingPartyApplicationStore();
}
} finally {
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs
index f22645f..551534a 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs
+++ b/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyAjaxControlBase.cs
@@ -301,7 +301,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="store">The store to pass to the relying party constructor.</param>
/// <returns>The instantiated relying party.</returns>
- protected override OpenIdRelyingParty CreateRelyingParty(IRelyingPartyApplicationStore store) {
+ protected override OpenIdRelyingParty CreateRelyingParty(IOpenIdApplicationStore store) {
return new OpenIdAjaxRelyingParty(store);
}
@@ -428,7 +428,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
this.RelyingParty.Channel.GetRequestFromContext(),
callback);
- response.Send();
+ response.Respond();
}
/// <summary>
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs
index 7cda8e0..b1106e6 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs
+++ b/src/DotNetOpenAuth/OpenId/RelyingParty/OpenIdRelyingPartyControlBase.cs
@@ -792,7 +792,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <returns>The instantiated relying party.</returns>
protected OpenIdRelyingParty CreateRelyingParty() {
- IRelyingPartyApplicationStore store = this.Stateless ? null : DotNetOpenAuthSection.Configuration.OpenId.RelyingParty.ApplicationStore.CreateInstance(OpenIdRelyingParty.HttpApplicationStore);
+ IOpenIdApplicationStore store = this.Stateless ? null : DotNetOpenAuthSection.Configuration.OpenId.RelyingParty.ApplicationStore.CreateInstance(OpenIdRelyingParty.HttpApplicationStore);
return this.CreateRelyingParty(store);
}
@@ -801,7 +801,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// </summary>
/// <param name="store">The store to pass to the relying party constructor.</param>
/// <returns>The instantiated relying party.</returns>
- protected virtual OpenIdRelyingParty CreateRelyingParty(IRelyingPartyApplicationStore store) {
+ protected virtual OpenIdRelyingParty CreateRelyingParty(IOpenIdApplicationStore store) {
return new OpenIdRelyingParty(store);
}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/PositiveAnonymousResponse.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/PositiveAnonymousResponse.cs
index 5cfa191..fc334b0 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/PositiveAnonymousResponse.cs
+++ b/src/DotNetOpenAuth/OpenId/RelyingParty/PositiveAnonymousResponse.cs
@@ -174,7 +174,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
if (this.response.ReturnToParametersSignatureValidated) {
return this.GetUntrustedCallbackArgument(key);
} else {
- Logger.OpenId.WarnFormat(OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IAssociationStore<Uri>).Name, typeof(OpenIdRelyingParty).Name);
+ Logger.OpenId.WarnFormat(OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IRelyingPartyAssociationStore).Name, typeof(OpenIdRelyingParty).Name);
return null;
}
}
@@ -214,7 +214,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
if (this.response.ReturnToParametersSignatureValidated) {
return this.GetUntrustedCallbackArguments();
} else {
- Logger.OpenId.WarnFormat(OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IAssociationStore<Uri>).Name, typeof(OpenIdRelyingParty).Name);
+ Logger.OpenId.WarnFormat(OpenIdStrings.CallbackArgumentsRequireSecretStore, typeof(IRelyingPartyAssociationStore).Name, typeof(OpenIdRelyingParty).Name);
return EmptyDictionary<string, string>.Instance;
}
}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/PrivateSecretManager.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/PrivateSecretManager.cs
deleted file mode 100644
index 6d55e39..0000000
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/PrivateSecretManager.cs
+++ /dev/null
@@ -1,122 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="PrivateSecretManager.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-namespace DotNetOpenAuth.OpenId.RelyingParty {
- using System;
- using System.Diagnostics.Contracts;
- using DotNetOpenAuth.Configuration;
- using DotNetOpenAuth.Messaging;
-
- /// <summary>
- /// Manages signing at the RP using private secrets.
- /// </summary>
- internal class PrivateSecretManager {
- /// <summary>
- /// The optimal length for a private secret used for signing using the HMACSHA256 class.
- /// </summary>
- /// <remarks>
- /// The 64-byte length is optimized for highest security when used with HMACSHA256.
- /// See HMACSHA256.HMACSHA256(byte[]) documentation for more information.
- /// </remarks>
- private const int OptimalPrivateSecretLength = 64;
-
- /// <summary>
- /// The URI to use for private associations at this RP.
- /// </summary>
- private static readonly Uri SecretUri = new Uri("https://localhost/dnoa/secret");
-
- /// <summary>
- /// The security settings that apply to this Relying Party.
- /// </summary>
- private RelyingPartySecuritySettings securitySettings;
-
- /// <summary>
- /// The association store
- /// </summary>
- private IAssociationStore<Uri> store;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="PrivateSecretManager"/> class.
- /// </summary>
- /// <param name="securitySettings">The security settings.</param>
- /// <param name="store">The association store.</param>
- internal PrivateSecretManager(RelyingPartySecuritySettings securitySettings, IAssociationStore<Uri> store) {
- Contract.Requires<ArgumentNullException>(securitySettings != null);
- Contract.Requires<ArgumentNullException>(store != null);
-
- this.securitySettings = securitySettings;
- this.store = store;
- }
-
- /// <summary>
- /// Gets the handle of the association to use for private signatures.
- /// </summary>
- /// <returns>
- /// An string made up of plain ASCII characters.
- /// </returns>
- internal string CurrentHandle {
- get {
- Association association = this.GetAssociation();
- return association.Handle;
- }
- }
-
- /// <summary>
- /// Used to verify a signature previously written.
- /// </summary>
- /// <param name="buffer">The data whose signature is to be verified.</param>
- /// <param name="handle">The handle to the private association used to sign the data.</param>
- /// <returns>
- /// The signature for the given buffer using the provided handle.
- /// </returns>
- /// <exception cref="ProtocolException">Thrown when an association with the given handle could not be found.
- /// This most likely happens if the association was near the end of its life and the user took too long to log in.</exception>
- internal byte[] Sign(byte[] buffer, string handle) {
- Contract.Requires<ArgumentNullException>(buffer != null);
- Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(handle));
-
- Association association = this.store.GetAssociation(SecretUri, handle);
- ErrorUtilities.VerifyProtocol(association != null, OpenIdStrings.PrivateRPSecretNotFound, handle);
- return association.Sign(buffer);
- }
-
- /// <summary>
- /// Creates the new association handle.
- /// </summary>
- /// <returns>The ASCII-encoded handle name.</returns>
- private static string CreateNewAssociationHandle() {
- string uniq = MessagingUtilities.GetCryptoRandomDataAsBase64(4);
- string handle = "{" + DateTime.UtcNow.Ticks + "}{" + uniq + "}";
- return handle;
- }
-
- /// <summary>
- /// Gets an association to use for signing new data.
- /// </summary>
- /// <returns>
- /// The association, which may have previously existed or
- /// may have been created as a result of this call.
- /// </returns>
- private Association GetAssociation() {
- Association privateAssociation = this.store.GetAssociation(SecretUri, this.securitySettings);
- if (privateAssociation == null || !privateAssociation.HasUsefulLifeRemaining) {
- int secretLength = HmacShaAssociation.GetSecretLength(Protocol.Default, Protocol.Default.Args.SignatureAlgorithm.Best);
- byte[] secret = MessagingUtilities.GetCryptoRandomData(secretLength);
- privateAssociation = HmacShaAssociation.Create(CreateNewAssociationHandle(), secret, this.securitySettings.PrivateSecretMaximumAge);
- if (!privateAssociation.HasUsefulLifeRemaining) {
- Logger.OpenId.WarnFormat(
- "Brand new private association has a shorter lifespan ({0}) than the maximum allowed authentication time for a user ({1}). This may lead to login failures.",
- this.securitySettings.PrivateSecretMaximumAge,
- DotNetOpenAuthSection.Configuration.OpenId.MaxAuthenticationTime);
- }
-
- this.store.StoreAssociation(SecretUri, privateAssociation);
- }
-
- return privateAssociation;
- }
- }
-}
diff --git a/src/DotNetOpenAuth/OpenId/RelyingParty/StandardRelyingPartyApplicationStore.cs b/src/DotNetOpenAuth/OpenId/RelyingParty/StandardRelyingPartyApplicationStore.cs
index fdb6931..f17b260 100644
--- a/src/DotNetOpenAuth/OpenId/RelyingParty/StandardRelyingPartyApplicationStore.cs
+++ b/src/DotNetOpenAuth/OpenId/RelyingParty/StandardRelyingPartyApplicationStore.cs
@@ -6,6 +6,7 @@
namespace DotNetOpenAuth.OpenId.RelyingParty {
using System;
+ using System.Collections.Generic;
using DotNetOpenAuth.Configuration;
using DotNetOpenAuth.Messaging.Bindings;
using DotNetOpenAuth.OpenId.ChannelElements;
@@ -14,7 +15,7 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// An in-memory store for Relying Parties, suitable for single server, single process
/// ASP.NET web sites.
/// </summary>
- public class StandardRelyingPartyApplicationStore : IRelyingPartyApplicationStore {
+ public class StandardRelyingPartyApplicationStore : IOpenIdApplicationStore {
/// <summary>
/// The nonce store to use.
/// </summary>
@@ -23,65 +24,59 @@ namespace DotNetOpenAuth.OpenId.RelyingParty {
/// <summary>
/// The association store to use.
/// </summary>
- private readonly IAssociationStore<Uri> associationStore;
+ private readonly ICryptoKeyStore keyStore;
/// <summary>
/// Initializes a new instance of the <see cref="StandardRelyingPartyApplicationStore"/> class.
/// </summary>
public StandardRelyingPartyApplicationStore() {
this.nonceStore = new NonceMemoryStore(DotNetOpenAuthSection.Configuration.OpenId.MaxAuthenticationTime);
- this.associationStore = new AssociationMemoryStore<Uri>();
+ this.keyStore = new MemoryCryptoKeyStore();
}
- #region IAssociationStore<Uri> Members
+ #region ICryptoKeyStore Members
/// <summary>
- /// Saves an <see cref="Association"/> for later recall.
+ /// Gets the key in a given bucket and handle.
/// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for providers).</param>
- /// <param name="association">The association to store.</param>
- public void StoreAssociation(Uri distinguishingFactor, Association association) {
- this.associationStore.StoreAssociation(distinguishingFactor, association);
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ /// <returns>
+ /// The cryptographic key, or <c>null</c> if no matching key was found.
+ /// </returns>
+ public CryptoKey GetKey(string bucket, string handle) {
+ return this.keyStore.GetKey(bucket, handle);
}
/// <summary>
- /// Gets the best association (the one with the longest remaining life) for a given key.
+ /// Gets a sequence of existing keys within a given bucket.
/// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="securityRequirements">The security settings.</param>
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
/// <returns>
- /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key.
+ /// A sequence of handles and keys, ordered by descending <see cref="CryptoKey.ExpiresUtc"/>.
/// </returns>
- public Association GetAssociation(Uri distinguishingFactor, SecuritySettings securityRequirements) {
- return this.associationStore.GetAssociation(distinguishingFactor, securityRequirements);
+ public IEnumerable<KeyValuePair<string, CryptoKey>> GetKeys(string bucket) {
+ return this.keyStore.GetKeys(bucket);
}
/// <summary>
- /// Gets the association for a given key and handle.
+ /// Stores a cryptographic key.
/// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be recalled.</param>
- /// <returns>
- /// The requested association, or null if no unexpired <see cref="Association"/>s exist for the given key and handle.
- /// </returns>
- public Association GetAssociation(Uri distinguishingFactor, string handle) {
- return this.associationStore.GetAssociation(distinguishingFactor, handle);
+ /// <param name="bucket">The name of the bucket to store the key in. Case sensitive.</param>
+ /// <param name="handle">The handle to the key, unique within the bucket. Case sensitive.</param>
+ /// <param name="key">The key to store.</param>
+ /// <exception cref="CryptoKeyCollisionException">Thrown in the event of a conflict with an existing key in the same bucket and with the same handle.</exception>
+ public void StoreKey(string bucket, string handle, CryptoKey key) {
+ this.keyStore.StoreKey(bucket, handle, key);
}
/// <summary>
- /// Removes a specified handle that may exist in the store.
+ /// Removes the key.
/// </summary>
- /// <param name="distinguishingFactor">The Uri (for relying parties) or Smart/Dumb (for Providers).</param>
- /// <param name="handle">The handle of the specific association that must be deleted.</param>
- /// <returns>
- /// True if the association existed in this store previous to this call.
- /// </returns>
- /// <remarks>
- /// No exception should be thrown if the association does not exist in the store
- /// before this call.
- /// </remarks>
- public bool RemoveAssociation(Uri distinguishingFactor, string handle) {
- return this.associationStore.RemoveAssociation(distinguishingFactor, handle);
+ /// <param name="bucket">The bucket name. Case sensitive.</param>
+ /// <param name="handle">The key handle. Case sensitive.</param>
+ public void RemoveKey(string bucket, string handle) {
+ this.keyStore.RemoveKey(bucket, handle);
}
#endregion
diff --git a/src/DotNetOpenAuth/Reporting.cs b/src/DotNetOpenAuth/Reporting.cs
index 2f93416..03565b8 100644
--- a/src/DotNetOpenAuth/Reporting.cs
+++ b/src/DotNetOpenAuth/Reporting.cs
@@ -237,6 +237,29 @@ namespace DotNetOpenAuth {
/// </summary>
/// <param name="value">The object whose type is the feature to set as used.</param>
/// <param name="dependency1">Some dependency used by <paramref name="value"/>.</param>
+ internal static void RecordFeatureAndDependencyUse(object value, object dependency1) {
+ Contract.Requires(value != null);
+
+ // In release builds, just quietly return.
+ if (value == null) {
+ return;
+ }
+
+ if (Enabled && Configuration.IncludeFeatureUsage) {
+ StringBuilder builder = new StringBuilder();
+ builder.Append(value.GetType().Name);
+ builder.Append(" ");
+ builder.Append(dependency1 != null ? dependency1.GetType().Name : "(null)");
+ observedFeatures.Add(builder.ToString());
+ Touch();
+ }
+ }
+
+ /// <summary>
+ /// Records the use of a feature by object type.
+ /// </summary>
+ /// <param name="value">The object whose type is the feature to set as used.</param>
+ /// <param name="dependency1">Some dependency used by <paramref name="value"/>.</param>
/// <param name="dependency2">Some dependency used by <paramref name="value"/>.</param>
internal static void RecordFeatureAndDependencyUse(object value, object dependency1, object dependency2) {
Contract.Requires(value != null);
diff --git a/src/version.txt b/src/version.txt
index 7921bd0..fcdb2e1 100644
--- a/src/version.txt
+++ b/src/version.txt
@@ -1 +1 @@
-3.4.8
+4.0.0