summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj6
-rw-r--r--src/DotNetOpenAuth.Test/Messaging/MessageSerializerTests.cs31
-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/StandardMessageFactoryTests.cs178
-rw-r--r--src/DotNetOpenAuth.Test/Mocks/TestDirectResponseMessageWithHttpStatus.cs12
-rw-r--r--src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs139
-rw-r--r--src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs21
-rw-r--r--src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs15
-rw-r--r--src/DotNetOpenAuth.sln1
-rw-r--r--src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd8
-rw-r--r--src/DotNetOpenAuth/Configuration/MessagingElement.cs15
-rw-r--r--src/DotNetOpenAuth/DotNetOpenAuth.csproj117
-rw-r--r--src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs1
-rw-r--r--src/DotNetOpenAuth/Messaging/Channel.cs111
-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/MessageSerializer.cs111
-rw-r--r--src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs27
-rw-r--r--src/DotNetOpenAuth/Messaging/MessagingStrings.resx9
-rw-r--r--src/DotNetOpenAuth/Messaging/MessagingUtilities.cs463
-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.cs30
-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/OAuth/ChannelElements/OAuthChannel.cs43
-rw-r--r--src/DotNetOpenAuth/OAuth/ChannelElements/OAuthPrincipal.cs18
-rw-r--r--src/DotNetOpenAuth/OAuth/Protocol.cs2
-rw-r--r--src/DotNetOpenAuth/OAuth2/AuthorizationServer.cs154
-rw-r--r--src/DotNetOpenAuth/OAuth2/AuthorizationServerBase.cs83
-rw-r--r--src/DotNetOpenAuth/OAuth2/AuthorizationServerDescription.cs62
-rw-r--r--src/DotNetOpenAuth/OAuth2/AuthorizationState.cs92
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AccessRequestBindingElement.cs144
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AccessToken.cs80
-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.cs92
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs100
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationDataBag.cs55
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/DataBag.cs71
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs67
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/GrantTypeEncoder.cs75
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/IAuthorizationDescription.cs90
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/IDataBagFormatter.cs54
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/ITokenCarryingRequest.cs54
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs107
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ChannelBase.cs48
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ClientChannel.cs91
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs152
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/RefreshToken.cs47
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/ScopeEncoder.cs51
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/TimestampEncoder.cs61
-rw-r--r--src/DotNetOpenAuth/OAuth2/ChannelElements/UriStyleMessageFormatter.cs306
-rw-r--r--src/DotNetOpenAuth/OAuth2/ClientBase.cs226
-rw-r--r--src/DotNetOpenAuth/OAuth2/IAccessTokenAnalyzer.cs61
-rw-r--r--src/DotNetOpenAuth/OAuth2/IAuthorizationServer.cs169
-rw-r--r--src/DotNetOpenAuth/OAuth2/IAuthorizationState.cs67
-rw-r--r--src/DotNetOpenAuth/OAuth2/IClientAuthorizationTracker.cs53
-rw-r--r--src/DotNetOpenAuth/OAuth2/IConsumerDescription.cs25
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessProtectedResourceRequest.cs119
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAssertionRequest.cs37
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs77
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs54
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenFailedResponse.cs86
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRefreshRequest.cs71
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRequestBase.cs60
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs42
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AccessTokenSuccessResponse.cs83
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/AuthenticatedClientRequestBase.cs42
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs70
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationRequest.cs93
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationResponseType.cs31
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs64
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs67
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs76
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/GrantType.cs42
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/IMessageWithClientState.cs21
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/MessageBase.cs210
-rw-r--r--src/DotNetOpenAuth/OAuth2/Messages/UnauthorizedResponse.cs115
-rw-r--r--src/DotNetOpenAuth/OAuth2/OAuthStrings.Designer.cs135
-rw-r--r--src/DotNetOpenAuth/OAuth2/OAuthStrings.resx144
-rw-r--r--src/DotNetOpenAuth/OAuth2/OAuthUtilities.cs117
-rw-r--r--src/DotNetOpenAuth/OAuth2/Protocol.cs330
-rw-r--r--src/DotNetOpenAuth/OAuth2/ResourceServer.cs144
-rw-r--r--src/DotNetOpenAuth/OAuth2/StandardAccessTokenAnalyzer.cs62
-rw-r--r--src/DotNetOpenAuth/OAuth2/UserAgentClient.cs107
-rw-r--r--src/DotNetOpenAuth/OAuth2/WebServerClient.cs126
-rw-r--r--src/DotNetOpenAuth/OpenId/Behaviors/GsaIcamProfile.cs8
-rw-r--r--src/DotNetOpenAuth/OpenId/Extensions/SimpleRegistration/Gender.cs2
-rw-r--r--src/DotNetOpenAuth/OpenId/Messages/DirectErrorResponse.cs8
-rw-r--r--src/version.txt2
96 files changed, 7770 insertions, 156 deletions
diff --git a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
index d7f97e5..f4d0bb3 100644
--- a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
+++ b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
@@ -171,6 +171,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">
@@ -202,6 +203,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" />
@@ -227,6 +229,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" />
@@ -354,6 +359,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..d07cf32 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,6 +55,34 @@ 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);
+ serializer.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);
+ serializer.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));
diff --git a/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs b/src/DotNetOpenAuth.Test/Messaging/MessagingUtilitiesTests.cs
index 10084b6..2c2da64 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/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/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..2514f68
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuth2/MessageFactoryTests.cs
@@ -0,0 +1,139 @@
+//-----------------------------------------------------------------------
+// <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);
+ }
+
+ [TestCase]
+ public void AccessTokenAssertionRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.assertion_type, "abc" },
+ { Protocol.assertion, "abc" },
+ { Protocol.grant_type, "assertion" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(AccessTokenAssertionRequest), request);
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs b/src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs
new file mode 100644
index 0000000..51d0656
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuth2/OAuth2ChannelTests.cs
@@ -0,0 +1,21 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthWrapChannelTests.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..fa1ed40
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuth2/OAuth2TestBase.cs
@@ -0,0 +1,15 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthWrapTestBase.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.sln b/src/DotNetOpenAuth.sln
index 2cef1b2..8353bac 100644
--- a/src/DotNetOpenAuth.sln
+++ b/src/DotNetOpenAuth.sln
@@ -13,6 +13,7 @@ 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.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
diff --git a/src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd b/src/DotNetOpenAuth/Configuration/DotNetOpenAuth.xsd
index a3c5de4..6265706 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:complexType>
</xs:element>
<xs:element name="openid">
diff --git a/src/DotNetOpenAuth/Configuration/MessagingElement.cs b/src/DotNetOpenAuth/Configuration/MessagingElement.cs
index f130dbc..fae18ec 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";
@@ -88,6 +93,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/DotNetOpenAuth.csproj b/src/DotNetOpenAuth/DotNetOpenAuth.csproj
index c9900ea..f402c95 100644
--- a/src/DotNetOpenAuth/DotNetOpenAuth.csproj
+++ b/src/DotNetOpenAuth/DotNetOpenAuth.csproj
@@ -216,6 +216,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>
@@ -315,11 +316,13 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="InfoCard\WellKnownIssuers.cs" />
<Compile Include="Messaging\CachedDirectWebResponse.cs" />
<Compile Include="Messaging\ChannelContract.cs" />
+ <Compile Include="Messaging\IHttpIndirectResponse.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" />
@@ -340,6 +343,58 @@ 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\AuthorizationServerBase.cs" />
+ <Compile Include="OAuth2\AuthorizationState.cs" />
+ <Compile Include="OAuth2\ChannelElements\AccessRequestBindingElement.cs" />
+ <Compile Include="OAuth2\ChannelElements\AccessToken.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="OAuth2\ChannelElements\IDataBagFormatter.cs" />
+ <Compile Include="OAuth2\ChannelElements\OAuth2ChannelBase.cs" />
+ <Compile Include="OAuth2\ChannelElements\OAuth2ClientChannel.cs" />
+ <Compile Include="OAuth2\ChannelElements\ScopeEncoder.cs" />
+ <Compile Include="OAuth2\ChannelElements\UriStyleMessageFormatter.cs" />
+ <Compile Include="OAuth2\ChannelElements\IAuthorizationDescription.cs" />
+ <Compile Include="OAuth2\ChannelElements\ITokenCarryingRequest.cs" />
+ <Compile Include="OAuth2\ChannelElements\OAuth2ResourceServerChannel.cs" />
+ <Compile Include="Messaging\StandardMessageFactoryChannel.cs" />
+ <Compile Include="OAuth2\ChannelElements\RefreshToken.cs" />
+ <Compile Include="OAuth2\ChannelElements\DataBag.cs" />
+ <Compile Include="OAuth2\ChannelElements\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\AccessTokenAssertionRequest.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\IMessageWithClientState.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" />
@@ -483,7 +538,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" />
@@ -610,6 +665,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" />
@@ -636,28 +703,28 @@ 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" />
@@ -745,6 +812,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>
diff --git a/src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs b/src/DotNetOpenAuth/Messaging/Bindings/ExpiredMessageException.cs
index 73ce289..31b053e 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, "faultedMessage");
}
/// <summary>
diff --git a/src/DotNetOpenAuth/Messaging/Channel.cs b/src/DotNetOpenAuth/Messaging/Channel.cs
index 3d56f02..f168f6f 100644
--- a/src/DotNetOpenAuth/Messaging/Channel.cs
+++ b/src/DotNetOpenAuth/Messaging/Channel.cs
@@ -17,9 +17,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>
@@ -40,6 +42,16 @@ 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 content-type for plain text.
+ /// </summary>
+ 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.
@@ -124,6 +136,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();
@@ -151,7 +170,7 @@ namespace DotNetOpenAuth.Messaging {
/// <summary>
/// Gets or sets the message descriptions.
/// </summary>
- internal MessageDescriptionCollection MessageDescriptions {
+ internal virtual MessageDescriptionCollection MessageDescriptions {
get {
return this.messageDescriptions;
}
@@ -209,11 +228,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>
@@ -232,6 +252,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.
@@ -660,7 +686,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;
}
@@ -702,6 +728,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, "Neither GET nor POST are allowed for this message.");
Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
Contract.Assert(message != null && message.Recipient != null);
@@ -709,10 +736,31 @@ 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 > IndirectMessageGetToPostThreshold) {
+ 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 > IndirectMessageGetToPostThreshold;
+ }
+
+ // 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);
}
@@ -725,9 +773,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);
@@ -735,7 +784,12 @@ namespace DotNetOpenAuth.Messaging {
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);
Logger.Http.DebugFormat("Redirecting to {0}", builder.Uri.AbsoluteUri);
OutgoingWebResponse response = new OutgoingWebResponse {
@@ -801,7 +855,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) {
@@ -823,6 +877,39 @@ 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>
+ protected virtual string SerializeAsJson(IMessage message) {
+ Contract.Requires<ArgumentNullException>(message != null, "message");
+
+ MessageDictionary messageDictionary = this.MessageDescriptions.GetAccessor(message);
+ var memoryStream = new MemoryStream();
+ var jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(memoryStream, Encoding.UTF8);
+ var serializer = MessageSerializer.Get(message.GetType());
+ serializer.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>();
+ 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>
@@ -938,7 +1025,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";
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/MessageSerializer.cs b/src/DotNetOpenAuth/Messaging/MessageSerializer.cs
index ccda5d5..d6448ae 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,29 @@ 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, "messageDictionary");
+ Contract.Requires<ArgumentNullException>(reader != null, "reader");
+
+ 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 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 +90,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;
@@ -85,6 +109,52 @@ namespace DotNetOpenAuth.Messaging {
}
/// <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 void Serialize(MessageDictionary messageDictionary, XmlDictionaryWriter writer) {
+ Contract.Requires<ArgumentNullException>(messageDictionary != null);
+ Contract.Requires<ArgumentNullException>(writer != null, "writer");
+
+ 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 name=value pairs into a message.
/// </summary>
/// <param name="fields">The name=value pairs that were read in from the transport.</param>
@@ -109,6 +179,45 @@ namespace DotNetOpenAuth.Messaging {
messageDictionary.Message.EnsureValidMessage();
}
+ /// <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 void Deserialize(MessageDictionary messageDictionary, XmlDictionaryReader reader) {
+ Contract.Requires<ArgumentNullException>(messageDictionary != null);
+ Contract.Requires<ArgumentNullException>(reader != null, "reader");
+
+ DeserializeJsonAsFlatDictionary(messageDictionary, reader);
+
+ // Make sure all the required parts are present and valid.
+ messageDictionary.Description.EnsureMessagePartsPassBasicValidation(messageDictionary);
+ messageDictionary.Message.EnsureValidMessage();
+ }
+
+ /// <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 ca69f5f..f600330 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 {
@@ -358,6 +367,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 {
@@ -430,6 +448,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 {
diff --git a/src/DotNetOpenAuth/Messaging/MessagingStrings.resx b/src/DotNetOpenAuth/Messaging/MessagingStrings.resx
index 102f044..7f9d91b 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingStrings.resx
+++ b/src/DotNetOpenAuth/Messaging/MessagingStrings.resx
@@ -303,6 +303,15 @@
<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>
diff --git a/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs b/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs
index 7c25f73..9dbd1b9 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;
@@ -59,6 +60,21 @@ namespace DotNetOpenAuth.Messaging {
internal const string AlphaNumericNoLookAlikes = "23456789abcdefghjkmnpqrstwxyzABCDEFGHJKMNPQRSTWXYZ";
/// <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 +209,85 @@ 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, "collection");
+ Contract.Requires<ArgumentNullException>(values != null, "values");
+
+ foreach (var value in values) {
+ collection.Add(value);
+ }
+ }
+
+ /// <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");
+
+ 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, "uri");
+ Contract.Requires<ArgumentNullException>(messageDescription != null, "messageDescription");
+
+ 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 +341,61 @@ 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, "fields");
+
+ 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 = authorizationHeader.Split(';'); // TODO: is this the right delimiter?
+ foreach (string authorization in authorizationSections) {
+ string trimmedAuth = authorization.Trim();
+ if (trimmedAuth.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) {
+ 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>
/// Gets a buffer of random data (not cryptographically strong).
/// </summary>
/// <param name="length">The length of the sequence to generate.</param>
@@ -298,6 +448,240 @@ 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, "algorithm");
+ Contract.Requires<ArgumentNullException>(value != null, "value");
+ 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, "algorithm");
+ Contract.Requires<ArgumentNullException>(data != null, "data");
+ 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, "algorithm");
+ Contract.Requires<ArgumentNullException>(sortedData != null, "sortedData");
+ 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, and 256.</param>
+ /// <returns>The encrypted buffer</returns>
+ internal static byte[] Encrypt(byte[] buffer, byte[] key) {
+ SymmetricAlgorithm crypto = CreateSymmetricAlgorithm(key);
+
+ var ms = new MemoryStream();
+ var binaryWriter = new BinaryWriter(ms);
+ binaryWriter.Write(crypto.IV.Length);
+ 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>
+ internal static byte[] Decrypt(byte[] buffer, byte[] key) {
+ SymmetricAlgorithm crypto = CreateSymmetricAlgorithm(key);
+
+ var ms = new MemoryStream(buffer);
+ var binaryReader = new BinaryReader(ms);
+ int ivLength = binaryReader.ReadInt32();
+ crypto.IV = binaryReader.ReadBytes(ivLength);
+
+ // 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, "crypto");
+ Contract.Requires<ArgumentNullException>(buffer != null, "buffer");
+
+ var symmetricCrypto = new RijndaelManaged {
+ Mode = CipherMode.CBC,
+ };
+
+ 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>
+ internal static byte[] DecryptWithRandomSymmetricKey(this RSACryptoServiceProvider crypto, byte[] buffer) {
+ Contract.Requires<ArgumentNullException>(crypto != null, "crypto");
+ Contract.Requires<ArgumentNullException>(buffer != null, "buffer");
+
+ var encryptedStream = new MemoryStream(buffer);
+ var encryptedStreamReader = new BinaryReader(encryptedStream);
+
+ byte[] encryptedPrequel = encryptedStreamReader.ReadBytes(encryptedStreamReader.ReadInt32());
+ byte[] prequel = crypto.Decrypt(encryptedPrequel, false);
+
+ var symmetricCrypto = new RijndaelManaged {
+ 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>
+ /// Compresses a given buffer.
+ /// </summary>
+ /// <param name="buffer">The buffer to compress.</param>
+ /// <returns>The compressed data.</returns>
+ internal static byte[] Compress(byte[] buffer) {
+ var ms = new MemoryStream();
+ using (var compressingStream = new GZipStream(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) {
+ var compressedDataStream = new MemoryStream(buffer);
+ var decompressedDataStream = new MemoryStream();
+ using (var decompressingStream = new GZipStream(compressedDataStream, CompressionMode.Decompress, true)) {
+ decompressingStream.CopyTo(decompressedDataStream);
+ }
+
+ return decompressedDataStream.ToArray();
+ }
+
+ /// <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>
@@ -548,6 +932,32 @@ 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>
+ /// <typeparam name="T">The type of elements in the arrays.</typeparam>
+ /// <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>
@@ -688,6 +1098,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>
@@ -780,6 +1219,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, "sequence");
+ 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>
@@ -985,6 +1436,18 @@ 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) {
+ return new RijndaelManaged {
+ Mode = CipherMode.CBC,
+ Key = key,
+ };
+ }
+
+ /// <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/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 125742c..754b9d0 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 b876ec4..df6dc73 100644
--- a/src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs
+++ b/src/DotNetOpenAuth/Messaging/Reflection/MessagePart.cs
@@ -93,6 +93,7 @@ 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);
@@ -163,6 +164,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 +200,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>
@@ -337,7 +361,11 @@ 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;
diff --git a/src/DotNetOpenAuth/Messaging/StandardMessageFactory.cs b/src/DotNetOpenAuth/Messaging/StandardMessageFactory.cs
new file mode 100644
index 0000000..d5aeba4
--- /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 => this.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()),
+ this.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, "assignableType");
+ Contract.Requires<ArgumentNullException>(derivedType != null, "derivedType");
+ 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>
+ /// 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);
+ }
+
+ /// <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 int CountInCommon(ICollection<string> collection1, ICollection<string> collection2, StringComparison comparison = StringComparison.Ordinal) {
+ Contract.Requires<ArgumentNullException>(collection1 != null, "collection1");
+ Contract.Requires<ArgumentNullException>(collection2 != null, "collection2");
+ 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)));
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/Messaging/StandardMessageFactoryChannel.cs b/src/DotNetOpenAuth/Messaging/StandardMessageFactoryChannel.cs
new file mode 100644
index 0000000..147b420
--- /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, "messageTypes");
+ Contract.Requires<ArgumentNullException>(versions != null, "versions");
+
+ 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 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 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, "messageTypes");
+ 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/OAuth/ChannelElements/OAuthChannel.cs b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs
index f2d69f5..d1d4f18 100644
--- a/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs
+++ b/src/DotNetOpenAuth/OAuth/ChannelElements/OAuthChannel.cs
@@ -116,36 +116,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) {
@@ -346,20 +324,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..83954bf 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/Protocol.cs b/src/DotNetOpenAuth/OAuth/Protocol.cs
index a524ba7..71a25f8 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..37be337
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/AuthorizationServer.cs
@@ -0,0 +1,154 @@
+//-----------------------------------------------------------------------
+// <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 : AuthorizationServerBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationServer"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ public AuthorizationServer(IAuthorizationServer authorizationServer)
+ : base(authorizationServer) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null, "authorizationServer");
+ }
+
+ /// <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;
+ this.Channel.TryReadFromRequest(request, out message);
+ return message;
+ }
+
+ public void ApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string username, IEnumerable<string> scopes = null, Uri callback = null) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+
+ var response = this.PrepareApproveAuthorizationRequest(authorizationRequest, username, callback);
+
+ // Customize the approved scope if the authorization server has decided to do so.
+ if (scopes != null) {
+ response.Scope.ResetContents(scopes);
+ }
+
+ this.Channel.Send(response);
+ }
+
+ public void RejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+
+ var response = this.PrepareRejectAuthorizationRequest(authorizationRequest, callback);
+ this.Channel.Send(response);
+ }
+
+ public bool TryPrepareAccessTokenResponse(out IDirectResponseProtocolMessage response) {
+ return this.TryPrepareAccessTokenResponse(this.Channel.GetRequestFromContext(), out response);
+ }
+
+ public bool TryPrepareAccessTokenResponse(HttpRequestInfo httpRequestInfo, out IDirectResponseProtocolMessage response) {
+ Contract.Requires<ArgumentNullException>(httpRequestInfo != null, "httpRequestInfo");
+
+ var request = this.ReadAccessTokenRequest(httpRequestInfo);
+ if (request != null) {
+ // This convenience method only encrypts access tokens assuming that this auth server
+ // doubles as the resource server.
+ RSAParameters resourceServerPublicKey = this.AuthorizationServer.AccessTokenSigningPrivateKey;
+ response = this.PrepareAccessTokenResponse(request, resourceServerPublicKey);
+ return true;
+ }
+
+ response = null;
+ return false;
+ }
+
+ public AccessTokenRequestBase ReadAccessTokenRequest(HttpRequestInfo requestInfo = null) {
+ if (requestInfo == null) {
+ requestInfo = this.Channel.GetRequestFromContext();
+ }
+
+ AccessTokenRequestBase request;
+ this.Channel.TryReadFromRequest(requestInfo, out request);
+ return request;
+ }
+
+ public EndUserAuthorizationFailedResponse PrepareRejectAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, Uri callback = null) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+ Contract.Ensures(Contract.Result<EndUserAuthorizationFailedResponse>() != null);
+
+ if (callback == null) {
+ callback = this.GetCallback(authorizationRequest);
+ }
+
+ var response = new EndUserAuthorizationFailedResponse(callback, authorizationRequest);
+ return response;
+ }
+
+ public EndUserAuthorizationSuccessResponseBase PrepareApproveAuthorizationRequest(EndUserAuthorizationRequest authorizationRequest, string username, Uri callback = null) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(username));
+ Contract.Ensures(Contract.Result<EndUserAuthorizationSuccessResponseBase>() != null);
+
+ if (callback == null) {
+ callback = this.GetCallback(authorizationRequest);
+ }
+
+ var client = this.AuthorizationServer.GetClientOrThrow(authorizationRequest.ClientIdentifier);
+ EndUserAuthorizationSuccessResponseBase response;
+ switch (authorizationRequest.ResponseType) {
+ case EndUserAuthorizationResponseType.AccessToken:
+ response = new EndUserAuthorizationSuccessAccessTokenResponse(callback, authorizationRequest);
+ break;
+ case EndUserAuthorizationResponseType.Both:
+ case EndUserAuthorizationResponseType.AuthorizationCode:
+ response = new EndUserAuthorizationSuccessAuthCodeResponse(callback, authorizationRequest);
+ break;
+ default:
+ throw ErrorUtilities.ThrowInternal("Unexpected response type.");
+ }
+
+ response.AuthorizingUsername = username;
+ return response;
+ }
+
+ protected Uri GetCallback(EndUserAuthorizationRequest authorizationRequest) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+ Contract.Ensures(Contract.Result<Uri>() != null);
+
+ // Prefer a request-specific callback to the pre-registered one (if any).
+ if (authorizationRequest.Callback != null) {
+ return authorizationRequest.Callback;
+ }
+
+ var client = this.AuthorizationServer.GetClient(authorizationRequest.ClientIdentifier);
+ if (client.Callback != null) {
+ return client.Callback;
+ }
+
+ throw ErrorUtilities.ThrowProtocol(OAuthStrings.NoCallback);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/AuthorizationServerBase.cs b/src/DotNetOpenAuth/OAuth2/AuthorizationServerBase.cs
new file mode 100644
index 0000000..9078326
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/AuthorizationServerBase.cs
@@ -0,0 +1,83 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationServerBase.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 ChannelElements;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuth2.Messages;
+ using OAuth.ChannelElements;
+
+ /// <summary>
+ /// A base class for authorization server facade classes.
+ /// </summary>
+ public abstract class AuthorizationServerBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationServerBase"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ protected AuthorizationServerBase(IAuthorizationServer authorizationServer) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null, "authorizationServer");
+ 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 AuthorizationServer {
+ get { return this.OAuthChannel.AuthorizationServer; }
+ }
+
+ /// <summary>
+ /// Gets the channel.
+ /// </summary>
+ internal OAuth2AuthorizationServerChannel OAuthChannel { get; private set; }
+
+ /// <summary>
+ /// Prepares the response to an access token request.
+ /// </summary>
+ /// <param name="request">The request for an access token.</param>
+ /// <param name="accessTokenEncryptingPublicKey">The public key to encrypt the access token to, such that the resource server will be able to decrypt it.</param>
+ /// <param name="accessTokenLifetime">The access token's lifetime.</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, RSAParameters accessTokenEncryptingPublicKey, TimeSpan? accessTokenLifetime = null, bool includeRefreshToken = true) {
+ Contract.Requires<ArgumentNullException>(request != null, "request");
+
+ var tokenRequest = (ITokenCarryingRequest)request;
+ var accessTokenFormatter = AccessToken.CreateFormatter(this.AuthorizationServer.AccessTokenSigningPrivateKey, accessTokenEncryptingPublicKey);
+ var accessToken = new AccessToken(tokenRequest.AuthorizationDescription, accessTokenLifetime);
+
+ var response = new AccessTokenSuccessResponse(request) {
+ AccessToken = accessTokenFormatter.Serialize(accessToken),
+ Lifetime = accessToken.Lifetime,
+ };
+ response.Scope.ResetContents(tokenRequest.AuthorizationDescription.Scope);
+
+ if (includeRefreshToken) {
+ var refreshTokenFormatter = RefreshToken.CreateFormatter(this.AuthorizationServer.Secret);
+ var refreshToken = new RefreshToken(tokenRequest.AuthorizationDescription);
+ response.RefreshToken = refreshTokenFormatter.Serialize(refreshToken);
+ }
+
+ return response;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/AuthorizationServerDescription.cs b/src/DotNetOpenAuth/OAuth2/AuthorizationServerDescription.cs
new file mode 100644
index 0000000..756c980
--- /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.
+ /// </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 HTTP or 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..7682900
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/AuthorizationState.cs
@@ -0,0 +1,92 @@
+//-----------------------------------------------------------------------
+// <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 memory-only copy of an authorization state.
+ /// </summary>
+ [Serializable]
+ public class AuthorizationState : IAuthorizationState {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationState"/> class.
+ /// </summary>
+ 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 or sets 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..2404963
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AccessRequestBindingElement.cs
@@ -0,0 +1,144 @@
+//-----------------------------------------------------------------------
+// <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.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 ITokenCarryingRequest;
+ 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;
+ 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.None || 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 ITokenCarryingRequest;
+ 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.Secret);
+ 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);
+ ErrorUtilities.VerifyProtocol(string.Equals(client.Secret, accessRequest.ClientSecret, StringComparison.Ordinal), Protocol.incorrect_client_credentials);
+
+ // Make sure the scope the client is requesting does not exceed the scope in the grant.
+ ErrorUtilities.VerifyProtocol(accessRequest.Scope.IsSubsetOf(tokenRequest.AuthorizationDescription.Scope), OAuthStrings.AccessScopeExceedsGrantScope, accessRequest.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..de24428
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AccessToken.cs
@@ -0,0 +1,80 @@
+//-----------------------------------------------------------------------
+// <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.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ 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, "authorization");
+
+ this.ClientIdentifier = authorization.ClientIdentifier;
+ this.UtcCreationDate = authorization.UtcIssued;
+ this.User = authorization.User;
+ this.Scope.ResetContents(authorization.Scope);
+ this.Lifetime = lifetime;
+ }
+
+ /// <summary>
+ /// Gets or sets the lifetime of the access token.
+ /// </summary>
+ /// <value>The lifetime.</value>
+ [MessagePart]
+ internal TimeSpan? Lifetime { get; set; }
+
+ internal static IDataBagFormatter<AccessToken> CreateFormatter(RSAParameters signingKey, RSAParameters encryptingKey)
+ {
+ 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/AuthServerAllFlowsBindingElement.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthServerAllFlowsBindingElement.cs
new file mode 100644
index 0000000..1bf8c79
--- /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(client.Callback == null || client.Callback == authorizationRequest.Callback, OAuthStrings.CallbackMismatch, client.Callback, authorizationRequest.Callback);
+ ErrorUtilities.VerifyProtocol(client.Callback != null || authorizationRequest.Callback != 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..1ec6b41
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCode.cs
@@ -0,0 +1,92 @@
+//-----------------------------------------------------------------------
+// <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;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <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 hash algorithm used on the callback URI.
+ /// </summary>
+ private readonly HashAlgorithm hasher = new SHA256Managed();
+
+ /// <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, "callback");
+
+ this.ClientIdentifier = clientIdentifier;
+ this.CallbackHash = this.CalculateCallbackHash(callback);
+ this.Scope.ResetContents(scopes);
+ this.User = username;
+ }
+
+ /// <summary>
+ /// Gets or sets the hash of the callback URL.
+ /// </summary>
+ [MessagePart("cb")]
+ private byte[] CallbackHash { get; set; }
+
+ internal static IDataBagFormatter<AuthorizationCode> CreateFormatter(IAuthorizationServer authorizationServer) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null, "authorizationServer");
+ Contract.Ensures(Contract.Result<IDataBagFormatter<AuthorizationCode>>() != null);
+
+ return new UriStyleMessageFormatter<AuthorizationCode>(
+ authorizationServer.Secret,
+ true,
+ true,
+ false,
+ AuthorizationCodeBindingElement.MaximumMessageAge,
+ 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, this.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 byte[] CalculateCallbackHash(Uri callback) {
+ return this.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..21fc258
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationCodeBindingElement.cs
@@ -0,0 +1,100 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebServerVerificationCodeBindingElement.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>
+ internal static TimeSpan MaximumMessageAge {
+ get { return StandardExpirationBindingElement.MaximumMessageAge; }
+ }
+
+ /// <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;
+ ITokenCarryingRequest tokenCarryingResponse = response;
+ tokenCarryingResponse.AuthorizationDescription = new AuthorizationCode(request.ClientIdentifier, request.Callback, request.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) {
+ ITokenCarryingRequest 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..2ca8c34
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/AuthorizationDataBag.cs
@@ -0,0 +1,55 @@
+//-----------------------------------------------------------------------
+// <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 System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Security.Cryptography;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+
+ /// <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 or sets 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/DataBag.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/DataBag.cs
new file mode 100644
index 0000000..cefd24d
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/DataBag.cs
@@ -0,0 +1,71 @@
+//-----------------------------------------------------------------------
+// <copyright file="DataBag.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.Security.Cryptography;
+ using System.Security.Cryptography.X509Certificates;
+ using System.Text;
+ using System.Web;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.Messaging.Bindings;
+ using DotNetOpenAuth.Messaging.Reflection;
+ using DotNetOpenAuth.OAuth2.Messages;
+
+ /// <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 : MessageBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="DataBag"/> class.
+ /// </summary>
+ protected DataBag()
+ : base(Protocol.Default.Version) {
+ }
+
+ /// <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("timestamp", IsRequired = true, Encoder = typeof(TimestampEncoder))]
+ internal DateTime UtcCreationDate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the signature.
+ /// </summary>
+ /// <value>The signature.</value>
+ [MessagePart("sig")]
+ 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>
+ [MessagePart("t", IsRequired = true, AllowEmpty = false)]
+ private string BagType {
+ get { return this.GetType().Name; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs
new file mode 100644
index 0000000..7ad6940
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/EndUserAuthorizationResponseTypeEncoder.cs
@@ -0,0 +1,67 @@
+//-----------------------------------------------------------------------
+// <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;
+
+ 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.Both:
+ return Protocol.ResponseTypes.CodeAndToken;
+ 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.CodeAndToken:
+ return EndUserAuthorizationResponseType.Both;
+ 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..f39eecd
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/GrantTypeEncoder.cs
@@ -0,0 +1,75 @@
+//-----------------------------------------------------------------------
+// <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;
+
+ 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.None:
+ return Protocol.GrantTypes.None;
+ case GrantType.AuthorizationCode:
+ return Protocol.GrantTypes.AuthorizationCode;
+ case GrantType.RefreshToken:
+ return Protocol.GrantTypes.RefreshToken;
+ case GrantType.BasicCredentials:
+ return Protocol.GrantTypes.BasicCredentials;
+ 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.None:
+ return GrantType.None;
+ case Protocol.GrantTypes.Assertion:
+ return GrantType.Assertion;
+ case Protocol.GrantTypes.BasicCredentials:
+ return GrantType.BasicCredentials;
+ 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/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/IDataBagFormatter.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/IDataBagFormatter.cs
new file mode 100644
index 0000000..a9c1875
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/IDataBagFormatter.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <copyright file="IDataBagFormatter.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;
+
+ /// <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() {
+ string Serialize(T message);
+
+ 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
+
+ string IDataBagFormatter<T>.Serialize(T message) {
+ Contract.Requires<ArgumentNullException>(message != null, "message");
+ Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
+
+ throw new System.NotImplementedException();
+ }
+
+ T IDataBagFormatter<T>.Deserialize(IProtocolMessage containingMessage, string data) {
+ Contract.Requires<ArgumentNullException>(containingMessage != null, "containingMessage");
+ 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/OAuth2/ChannelElements/ITokenCarryingRequest.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/ITokenCarryingRequest.cs
new file mode 100644
index 0000000..4c8d33f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/ITokenCarryingRequest.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <copyright file="ITokenCarryingRequest.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 ITokenCarryingRequest : 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/OAuth2AuthorizationServerChannel.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs
new file mode 100644
index 0000000..5ecf01c
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2AuthorizationServerChannel.cs
@@ -0,0 +1,107 @@
+//-----------------------------------------------------------------------
+// <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, "authorizationServer");
+ 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, "authorizationServer");
+ var bindingElements = new List<IChannelBindingElement>();
+
+ bindingElements.Add(new AuthServerAllFlowsBindingElement());
+ bindingElements.Add(new AuthorizationCodeBindingElement());
+ 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..2a959ff
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ChannelBase.cs
@@ -0,0 +1,48 @@
+//-----------------------------------------------------------------------
+// <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;
+
+ 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(AccessTokenAssertionRequest),
+ 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) {
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ClientChannel.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ClientChannel.cs
new file mode 100644
index 0000000..256a28d
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ClientChannel.cs
@@ -0,0 +1,91 @@
+//-----------------------------------------------------------------------
+// <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;
+
+ 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;
+ }
+
+ 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
+ string body = response.GetResponseReader().ReadToEnd();
+ if (response.ContentType.MediaType == JsonEncoded) {
+ 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);
+ }
+ }
+
+ 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);
+ }
+
+ protected override OutgoingWebResponse PrepareDirectResponse(IProtocolMessage response) {
+ 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..60e464c
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/OAuth2ResourceServerChannel.cs
@@ -0,0 +1,152 @@
+//-----------------------------------------------------------------------
+// <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) {
+ // First search the Authorization header.
+ var fields = MessagingUtilities.ParseAuthorizationHeader(
+ Protocol.HttpAuthorizationScheme,
+ request.Headers[HttpRequestHeader.Authorization]).ToDictionary();
+
+ // Failing that, try the query string (for GET or POST or any other method)
+ if (fields.Count == 0) {
+ if (request.QueryStringBeforeRewriting["oauth_token"] != null) {
+ // We're only interested in the oauth_token parameter -- not the others that can appear in an Authorization header.
+ // Note that we intentionally change the name of the key here
+ // because depending on the method used to obtain the token, the token's key changes
+ // but we need to consolidate to one name so it works with the rest of the system.
+ fields.Add("token", request.QueryStringBeforeRewriting["oauth_token"]);
+ }
+ }
+
+ // Failing that, scan the entity
+ if (fields.Count == 0) {
+ // The spec calls out that this is allowed only for these three HTTP methods.
+ if (request.HttpMethod == "POST" || request.HttpMethod == "DELETE" || request.HttpMethod == "PUT") {
+ 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["oauth_token"] != null) {
+ // We're only interested in the oauth_token parameter -- not the others that can appear in an Authorization header.
+ // Note that we intentionally change the name of the key here
+ // because depending on the method used to obtain the token, the token's key changes
+ // but we need to consolidate to one name so it works with the rest of the system.
+ fields.Add("token", request.Form["oauth_token"]);
+ }
+ }
+ }
+ }
+ }
+
+ if (fields.Count > 0) {
+ MessageReceivingEndpoint recipient;
+ try {
+ recipient = request.GetRecipient();
+ } catch (ArgumentException ex) {
+ Logger.OAuth.WarnFormat("Unrecognized HTTP request: " + ex.ToString());
+ return null;
+ }
+
+ // TODO: remove this after signatures are supported.
+ ErrorUtilities.VerifyProtocol(!fields.ContainsKey("signature"), "OAuth signatures not supported yet.");
+
+ // 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.HttpAuthorizationScheme, fields);
+ return webResponse;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/RefreshToken.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/RefreshToken.cs
new file mode 100644
index 0000000..a88bf9f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/RefreshToken.cs
@@ -0,0 +1,47 @@
+//-----------------------------------------------------------------------
+// <copyright file="RefreshToken.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.Messaging;
+
+ /// <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>
+ /// 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, "authorization");
+
+ this.ClientIdentifier = authorization.ClientIdentifier;
+ this.UtcCreationDate = authorization.UtcIssued;
+ this.User = authorization.User;
+ this.Scope.ResetContents(authorization.Scope);
+ }
+
+ internal static IDataBagFormatter<RefreshToken> CreateFormatter(byte[] symmetricSecret)
+ {
+ Contract.Requires<ArgumentNullException>(symmetricSecret != null, "symmetricSecret");
+ Contract.Ensures(Contract.Result<IDataBagFormatter<RefreshToken>>() != null);
+
+ return new UriStyleMessageFormatter<RefreshToken>(symmetricSecret, true, true);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ChannelElements/ScopeEncoder.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/ScopeEncoder.cs
new file mode 100644
index 0000000..d35f982
--- /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 ? 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/ChannelElements/TimestampEncoder.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/TimestampEncoder.cs
new file mode 100644
index 0000000..7c6aafb
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/TimestampEncoder.cs
@@ -0,0 +1,61 @@
+//-----------------------------------------------------------------------
+// <copyright file="TimestampEncoder.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.ChannelElements {
+ 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>
+ private 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/OAuth2/ChannelElements/UriStyleMessageFormatter.cs b/src/DotNetOpenAuth/OAuth2/ChannelElements/UriStyleMessageFormatter.cs
new file mode 100644
index 0000000..cf1b522
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ChannelElements/UriStyleMessageFormatter.cs
@@ -0,0 +1,306 @@
+//-----------------------------------------------------------------------
+// <copyright file="UriStyleMessageFormatter.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.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> : IDataBagFormatter<T> where T : DataBag, new() {
+ /// <summary>
+ /// The length of the nonce to include in tokens that can be decoded once only.
+ /// </summary>
+ private const int NonceLength = 6;
+
+ /// <summary>
+ /// The message description cache to use for data bag types.
+ /// </summary>
+ private static readonly MessageDescriptionCollection MessageDescriptions = new MessageDescriptionCollection();
+
+ /// <summary>
+ /// The symmetric secret used for signing/encryption of verification codes and refresh tokens.
+ /// </summary>
+ private readonly byte[] symmetricSecret;
+
+ /// <summary>
+ /// The hashing algorithm to use while signing when using a symmetric secret.
+ /// </summary>
+ private readonly HashAlgorithm symmetricHasher;
+
+ /// <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>
+ /// The hashing algorithm to use for asymmetric signatures.
+ /// </summary>
+ private readonly HashAlgorithm hasherForAsymmetricSigning;
+
+ /// <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="UriStyleMessageFormatter&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 <see cref="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ internal UriStyleMessageFormatter(bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null) {
+ Contract.Requires<ArgumentException>(signed || decodeOnceOnly == null, "A signature must be applied if this data is meant to be decoded only once.");
+ Contract.Requires<ArgumentException>(maximumAge.HasValue || decodeOnceOnly == null, "A maximum age must be given if a message can only be decoded once.");
+
+ this.signed = signed;
+ this.maximumAge = maximumAge;
+ this.decodeOnceOnly = decodeOnceOnly;
+ this.encrypted = encrypted;
+ this.compressed = compressed;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UriStyleMessageFormatter&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="signingKey">The asymmetric private key to use for signing the token.</param>
+ /// <param name="encryptingKey">The asymmetric public key to use for encrypting 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 <see cref="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ internal UriStyleMessageFormatter(RSAParameters? signingKey = null, RSAParameters? encryptingKey = null, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : this(signingKey.HasValue, encryptingKey.HasValue, compressed, maximumAge, decodeOnceOnly) {
+ if (signingKey.HasValue) {
+ this.asymmetricSigning = new RSACryptoServiceProvider();
+ this.asymmetricSigning.ImportParameters(signingKey.Value);
+ }
+
+ if (encryptingKey.HasValue) {
+ this.asymmetricEncrypting = new RSACryptoServiceProvider();
+ this.asymmetricEncrypting.ImportParameters(encryptingKey.Value);
+ }
+
+ this.hasherForAsymmetricSigning = new SHA1CryptoServiceProvider();
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UriStyleMessageFormatter&lt;T&gt;"/> class.
+ /// </summary>
+ /// <param name="symmetricSecret">The symmetric secret to use for signing and encrypting.</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="maximumAge">The maximum age of a token that can be decoded; useful only when <see cref="decodeOnceOnly"/> is <c>true</c>.</param>
+ /// <param name="decodeOnceOnly">The nonce store to use to ensure that this instance is only decoded once.</param>
+ internal UriStyleMessageFormatter(byte[] symmetricSecret = null, bool signed = false, bool encrypted = false, bool compressed = false, TimeSpan? maximumAge = null, INonceStore decodeOnceOnly = null)
+ : this(signed, encrypted, compressed, maximumAge, decodeOnceOnly) {
+ Contract.Requires<ArgumentException>(symmetricSecret != null || (!signed && !encrypted), "A secret is required when signing or encrypting is required.");
+
+ if (symmetricSecret != null) {
+ this.symmetricHasher = new HMACSHA256(symmetricSecret);
+ }
+
+ this.symmetricSecret = symmetricSecret;
+ }
+
+ public string Serialize(T message) {
+ message.UtcCreationDate = DateTime.UtcNow;
+
+ if (this.decodeOnceOnly != null) {
+ message.Nonce = MessagingUtilities.GetNonCryptoRandomData(NonceLength);
+ }
+
+ if (this.signed) {
+ message.Signature = this.CalculateSignature(message);
+ }
+
+ var fields = MessageSerializer.Get(message.GetType()).Serialize(MessageDescriptions.GetAccessor(message));
+ string value = MessagingUtilities.CreateQueryString(fields);
+
+ byte[] encoded = Encoding.UTF8.GetBytes(value);
+
+ if (this.compressed) {
+ encoded = MessagingUtilities.Compress(encoded);
+ }
+
+ if (this.encrypted) {
+ encoded = this.Encrypt(encoded);
+ }
+
+ return Convert.ToBase64String(encoded);
+ }
+
+ public T Deserialize(IProtocolMessage containingMessage, string value) {
+ var message = new T();
+ message.ContainingMessage = containingMessage;
+ byte[] data = Convert.FromBase64String(value);
+
+ if (this.encrypted) {
+ data = this.Decrypt(data);
+ }
+
+ if (this.compressed) {
+ data = MessagingUtilities.Decompress(data);
+ }
+
+ 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);
+
+ if (this.signed) {
+ // Verify that the verification code was issued by message authorization server.
+ ErrorUtilities.VerifyProtocol(this.IsSignatureValid(message), Protocol.bad_verification_code);
+ }
+
+ 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>
+ /// Determines whether the signature on this instance is valid.
+ /// </summary>
+ /// <param name="message">The message whose signature is to be checked.</param>
+ /// <returns>
+ /// <c>true</c> if the signature is valid; otherwise, <c>false</c>.
+ /// </returns>
+ private bool IsSignatureValid(DataBag message) {
+ Contract.Requires<ArgumentNullException>(message != null, "message");
+
+ if (this.asymmetricSigning != null) {
+ byte[] bytesToSign = this.GetBytesToSign(message);
+ return this.asymmetricSigning.VerifyData(bytesToSign, this.hasherForAsymmetricSigning, message.Signature);
+ } else {
+ return MessagingUtilities.AreEquivalentConstantTime(message.Signature, this.CalculateSignature(message));
+ }
+ }
+
+ /// <summary>
+ /// Calculates the signature for the data in this verification code.
+ /// </summary>
+ /// <param name="message">The message whose signature is to be calculated.</param>
+ /// <returns>The calculated signature.</returns>
+ private byte[] CalculateSignature(DataBag message) {
+ Contract.Requires<ArgumentNullException>(message != null, "message");
+ Contract.Requires<InvalidOperationException>(this.asymmetricSigning != null || this.symmetricHasher != null);
+ Contract.Ensures(Contract.Result<byte[]>() != null);
+
+ byte[] bytesToSign = this.GetBytesToSign(message);
+ if (this.asymmetricSigning != null) {
+ return this.asymmetricSigning.SignData(bytesToSign, this.hasherForAsymmetricSigning);
+ } else {
+ return this.symmetricHasher.ComputeHash(bytesToSign);
+ }
+ }
+
+ /// <summary>
+ /// Gets the bytes to sign.
+ /// </summary>
+ /// <param name="message">The message to be encoded as normalized bytes for signing.</param>
+ /// <returns>A buffer of the bytes to sign.</returns>
+ private byte[] GetBytesToSign(DataBag message) {
+ Contract.Requires<ArgumentNullException>(message != null, "message");
+
+ // Sign the data, being sure to avoid any impact of the signature field itself.
+ var fields = MessageDescriptions.GetAccessor(message);
+ var fieldsCopy = fields.ToDictionary();
+ fieldsCopy.Remove("sig");
+
+ var sortedData = new SortedDictionary<string, string>(fieldsCopy, StringComparer.OrdinalIgnoreCase);
+ string value = MessagingUtilities.CreateQueryString(sortedData);
+ byte[] bytesToSign = Encoding.UTF8.GetBytes(value);
+ return bytesToSign;
+ }
+
+ /// <summary>
+ /// Encrypts the specified value using either the symmetric or asymmetric encryption algorithm as appropriate.
+ /// </summary>
+ /// <param name="value">The value.</param>
+ /// <returns>The encrypted value.</returns>
+ private byte[] Encrypt(byte[] value) {
+ Contract.Requires<InvalidOperationException>(this.asymmetricEncrypting != null || this.symmetricSecret != null);
+
+ if (this.asymmetricEncrypting != null) {
+ return this.asymmetricEncrypting.EncryptWithRandomSymmetricKey(value);
+ } else {
+ return MessagingUtilities.Encrypt(value, this.symmetricSecret);
+ }
+ }
+
+ /// <summary>
+ /// Decrypts the specified value using either the symmetric or asymmetric encryption algorithm as appropriate.
+ /// </summary>
+ /// <param name="value">The value.</param>
+ /// <returns>The decrypted value.</returns>
+ private byte[] Decrypt(byte[] value) {
+ Contract.Requires<InvalidOperationException>(this.asymmetricEncrypting != null || this.symmetricSecret != null);
+
+ if (this.asymmetricEncrypting != null) {
+ return this.asymmetricEncrypting.DecryptWithRandomSymmetricKey(value);
+ } else {
+ return MessagingUtilities.Decrypt(value, this.symmetricSecret);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ClientBase.cs b/src/DotNetOpenAuth/OAuth2/ClientBase.cs
new file mode 100644
index 0000000..d9d9232
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ClientBase.cs
@@ -0,0 +1,226 @@
+//-----------------------------------------------------------------------
+// <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 void AuthorizeRequest(HttpWebRequest request, string accessToken) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(accessToken));
+
+ OAuthUtilities.AuthorizeWithOAuthWrap(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);
+ }
+
+ this.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>
+ public void RefreshToken(IAuthorizationState authorization, TimeSpan? skipIfUsefulLifeExceeds = null) {
+ Contract.Requires<ArgumentNullException>(authorization != null, "authorization");
+ 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;
+ }
+ }
+
+ 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();
+ }
+
+ /// <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 void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, AccessTokenSuccessResponse accessTokenSuccess) {
+ Contract.Requires<ArgumentNullException>(authorizationState != null, "authorizationState");
+ Contract.Requires<ArgumentNullException>(accessTokenSuccess != null, "accessTokenSuccess");
+
+ 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 void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAccessTokenResponse accessTokenSuccess) {
+ Contract.Requires<ArgumentNullException>(authorizationState != null, "authorizationState");
+ Contract.Requires<ArgumentNullException>(accessTokenSuccess != null, "accessTokenSuccess");
+
+ 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();
+ }
+
+ internal void UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAuthCodeResponse authorizationSuccess) {
+ Contract.Requires<ArgumentNullException>(authorizationState != null, "authorizationState");
+ Contract.Requires<ArgumentNullException>(authorizationSuccess != null, "authorizationSuccess");
+
+ 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) {
+ this.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 double ProportionalLifeRemaining(IAuthorizationState authorization) {
+ Contract.Requires<ArgumentNullException>(authorization != null, "authorization");
+ 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..ed6cd63
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/IAccessTokenAnalyzer.cs
@@ -0,0 +1,61 @@
+//-----------------------------------------------------------------------
+// <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.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>
+ 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, "message");
+ 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..83b5191
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/IAuthorizationServer.cs
@@ -0,0 +1,169 @@
+//-----------------------------------------------------------------------
+// <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.Bindings;
+ using DotNetOpenAuth.OAuth2.ChannelElements;
+
+ /// <summary>
+ /// Provides host-specific authorization server services needed by this library.
+ /// </summary>
+ [ContractClass(typeof(IAuthorizationServerContract))]
+ public interface IAuthorizationServer {
+ /// <summary>
+ /// Gets the secret used to symmetrically encrypt and sign authorization codes and refresh tokens.
+ /// </summary>
+ /// <remarks>
+ /// This secret should be kept strictly confidential in the authorization server(s)
+ /// and NOT shared with the resource server. Anyone with this secret can mint
+ /// tokens to essentially grant themselves access to anything they want.
+ /// </remarks>
+ byte[] Secret { get; }
+
+ /// <summary>
+ /// Gets the asymmetric private key to use for signing access tokens.
+ /// </summary>
+ /// <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>
+ RSAParameters AccessTokenSigningPrivateKey { 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 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 secret used to symmetrically encrypt and sign authorization codes and refresh tokens.
+ /// </summary>
+ /// <value></value>
+ /// <remarks>
+ /// This secret should be kept strictly confidential in the authorization server(s)
+ /// and NOT shared with the resource server. Anyone with this secret can mint
+ /// tokens to essentially grant themselves access to anything they want.
+ /// </remarks>
+ byte[] IAuthorizationServer.Secret {
+ get {
+ Contract.Ensures(Contract.Result<byte[]>() != null);
+ throw new NotImplementedException();
+ }
+ }
+
+ /// <summary>
+ /// Gets the asymmetric private key to use for signing access tokens.
+ /// </summary>
+ /// <value></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>
+ RSAParameters IAuthorizationServer.AccessTokenSigningPrivateKey {
+ get { 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 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, "authorization");
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/IAuthorizationState.cs b/src/DotNetOpenAuth/OAuth2/IAuthorizationState.cs
new file mode 100644
index 0000000..68a109b
--- /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 or sets 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..4e2bc4f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/IConsumerDescription.cs
@@ -0,0 +1,25 @@
+//-----------------------------------------------------------------------
+// <copyright file="IConsumerDescription.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2 {
+ using System;
+
+ /// <summary>
+ /// A description of a client from an Authorization Server's point of view.
+ /// </summary>
+ public interface IConsumerDescription {
+ /// <summary>
+ /// Gets the client secret.
+ /// </summary>
+ string Secret { get; }
+
+ /// <summary>
+ /// Gets the callback URI that this client has pre-registered with the service provider, if any.
+ /// </summary>
+ /// <value>A URI that user authorization responses should be directed to; or <c>null</c> if no preregistered callback was arranged.</value>
+ Uri Callback { get; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessProtectedResourceRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessProtectedResourceRequest.cs
new file mode 100644
index 0000000..f49efce
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessProtectedResourceRequest.cs
@@ -0,0 +1,119 @@
+//-----------------------------------------------------------------------
+// <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>
+ internal class AccessProtectedResourceRequest : MessageBase, ITokenCarryingRequest {
+ /// <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 ITokenCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AccessToken; }
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string ITokenCarryingRequest.CodeOrToken {
+ get { return this.AccessToken; }
+ set { this.AccessToken = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription ITokenCarryingRequest.AuthorizationDescription { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ [MessagePart("token", IsRequired = true, AllowEmpty = false)]
+ internal string AccessToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the nonce.
+ /// </summary>
+ /// <value>The nonce.</value>
+ [MessagePart("nonce")]
+ internal string Nonce { get; set; }
+
+ /// <summary>
+ /// Gets or sets the timestamp.
+ /// </summary>
+ /// <value>The timestamp.</value>
+ [MessagePart("timestamp", Encoder = typeof(TimestampEncoder))]
+ internal DateTime? Timestamp { get; set; }
+
+ /// <summary>
+ /// Gets or sets the signature.
+ /// </summary>
+ /// <value>The signature.</value>
+ [MessagePart("signature")]
+ internal string Signature { get; set; }
+
+ /// <summary>
+ /// Gets or sets the algorithm.
+ /// </summary>
+ /// <value>The algorithm.</value>
+ [MessagePart("algorithm")]
+ internal string Algorithm { get; set; }
+
+ /// <summary>
+ /// Gets a value indicating whether this request is signed.
+ /// </summary>
+ internal bool SignedRequest {
+ get { return this.Signature != null; }
+ }
+
+ /// <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();
+
+ // If any of the optional parameters are present, all of them are required.
+ if (this.Signature == null) {
+ ErrorUtilities.VerifyProtocol(this.Algorithm == null, this, MessagingStrings.UnexpectedMessagePartValue, "algorithm", this.Algorithm);
+ ErrorUtilities.VerifyProtocol(!this.Timestamp.HasValue, this, MessagingStrings.UnexpectedMessagePartValue, "timestamp", this.Timestamp);
+ ErrorUtilities.VerifyProtocol(this.Nonce == null, this, MessagingStrings.UnexpectedMessagePartValue, "nonce", this.Nonce);
+ } else {
+ ErrorUtilities.VerifyProtocol(this.Algorithm != null, this, MessagingStrings.RequiredParametersMissing, "algorithm");
+ ErrorUtilities.VerifyProtocol(this.Timestamp.HasValue, this, MessagingStrings.RequiredParametersMissing, "timestamp");
+ ErrorUtilities.VerifyProtocol(this.Nonce != null, this, MessagingStrings.RequiredParametersMissing, "nonce");
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAssertionRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAssertionRequest.cs
new file mode 100644
index 0000000..8c2ef2b
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAssertionRequest.cs
@@ -0,0 +1,37 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenAssertionRequest.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;
+
+ internal class AccessTokenAssertionRequest : AccessTokenRequestBase {
+ internal AccessTokenAssertionRequest(Uri tokenEndpoint, Version version)
+ : base(tokenEndpoint, version) {
+ }
+
+ /// <summary>
+ /// Gets or sets the format of the assertion as defined by the Authorization Server.
+ /// </summary>
+ /// <value>The assertion format.</value>
+ [MessagePart(Protocol.assertion_type, IsRequired = true, AllowEmpty = false)]
+ internal Uri AssertionType { get; set; }
+
+ /// <summary>
+ /// Gets or sets the assertion.
+ /// </summary>
+ /// <value>The assertion.</value>
+ [MessagePart(Protocol.assertion, IsRequired = true, AllowEmpty = false)]
+ internal string Assertion { get; set; }
+
+ internal override GrantType GrantType {
+ get { return GrantType.Assertion; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs
new file mode 100644
index 0000000..86c1a4b
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenAuthorizationCodeRequest.cs
@@ -0,0 +1,77 @@
+//-----------------------------------------------------------------------
+// <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;
+
+ internal class AccessTokenAuthorizationCodeRequest : AccessTokenRequestBase, ITokenCarryingRequest {
+ /// <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) {
+ }
+
+
+ internal AccessTokenAuthorizationCodeRequest(AuthorizationServerDescription authorizationServer)
+ : this(authorizationServer.TokenEndpoint, authorizationServer.Version)
+ {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null, "authorizationServer");
+ }
+
+ internal override GrantType GrantType {
+ get { return Messages.GrantType.AuthorizationCode; }
+ }
+
+ /// <summary>
+ /// Gets the type of the code or token.
+ /// </summary>
+ /// <value>The type of the code or token.</value>
+ CodeOrTokenType ITokenCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AuthorizationCode; }
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string ITokenCarryingRequest.CodeOrToken {
+ get { return this.AuthorizationCode; }
+ set { this.AuthorizationCode = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription ITokenCarryingRequest.AuthorizationDescription { get; set; }
+
+ /// <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, AllowEmpty = false)]
+ 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, AllowEmpty = false)]
+ internal Uri Callback { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs
new file mode 100644
index 0000000..59b0758
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenClientCredentialsRequest.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <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 : AccessTokenRequestBase {
+ /// <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>
+ /// 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(this.Recipient.IsTransportSecure(), OAuthStrings.HttpsRequired);
+ }
+
+ internal override GrantType GrantType {
+ get { return Messages.GrantType.None; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenFailedResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenFailedResponse.cs
new file mode 100644
index 0000000..90c5e67
--- /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;
+ }
+
+ /// <summary>
+ /// Gets or sets the error.
+ /// </summary>
+ /// <value>One of the values given in <see cref="Protocol.AccessTokenRequestErrorCodes"/>.</value>
+ [MessagePart(Protocol.error, IsRequired = true, AllowEmpty = false)]
+ 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, AllowEmpty = true, 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, AllowEmpty = false, IsRequired = false)]
+ internal Uri ErrorUri { get; set; }
+
+ #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
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRefreshRequest.cs b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRefreshRequest.cs
new file mode 100644
index 0000000..f15f190
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRefreshRequest.cs
@@ -0,0 +1,71 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenRefreshRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuth2.Messages {
+ using System;
+ 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 : AccessTokenRequestBase, ITokenCarryingRequest {
+ /// <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 ITokenCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.RefreshToken; }
+ }
+
+
+ /// <summary>
+ /// Gets or sets the verification code or refresh/access token.
+ /// </summary>
+ /// <value>The code or token.</value>
+ string ITokenCarryingRequest.CodeOrToken {
+ get { return this.RefreshToken; }
+ set { this.RefreshToken = value; }
+ }
+
+ /// <summary>
+ /// Gets or sets the authorization that the token describes.
+ /// </summary>
+ IAuthorizationDescription ITokenCarryingRequest.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, AllowEmpty = false)]
+ internal string RefreshToken { get; set; }
+
+ 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..943308e
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenRequestBase.cs
@@ -0,0 +1,60 @@
+//-----------------------------------------------------------------------
+// <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 {
+ /// <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;
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ }
+
+ /// <summary>
+ /// Gets the type of the grant.
+ /// </summary>
+ /// <value>The type of the grant.</value>
+ [MessagePart(Protocol.grant_type, IsRequired = true, AllowEmpty = false, Encoder = typeof(GrantTypeEncoder))]
+ internal abstract GrantType GrantType { get; }
+
+ [MessagePart(Protocol.scope, IsRequired = false, AllowEmpty = true, Encoder = typeof(ScopeEncoder))]
+ internal 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>
+ /// <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..98b1068
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenResourceOwnerPasswordCredentialsRequest.cs
@@ -0,0 +1,42 @@
+//-----------------------------------------------------------------------
+// <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;
+
+ internal class AccessTokenResourceOwnerPasswordCredentialsRequest : AccessTokenRequestBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenResourceOwnerPasswordCredentialsRequest"/> class.
+ /// </summary>
+ internal AccessTokenResourceOwnerPasswordCredentialsRequest(Uri accessTokenEndpoint, Version version)
+ : base(accessTokenEndpoint, version) {
+ }
+
+ internal override GrantType GrantType {
+ get { return Messages.GrantType.BasicCredentials; }
+ }
+
+ /// <summary>
+ /// Gets or sets the user's account username.
+ /// </summary>
+ /// <value>The username on the user's account.</value>
+ [MessagePart(Protocol.username, IsRequired = true, AllowEmpty = false)]
+ internal string UserName { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user's password.
+ /// </summary>
+ /// <value>The password.</value>
+ [MessagePart(Protocol.password, IsRequired = true, AllowEmpty = 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..37a4684
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/AccessTokenSuccessResponse.cs
@@ -0,0 +1,83 @@
+//-----------------------------------------------------------------------
+// <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);
+ }
+
+ /// <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, AllowEmpty = false)]
+ public string AccessToken { 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, AllowEmpty = false)]
+ public string RefreshToken { get; internal set; }
+
+ /// <summary>
+ /// Gets or sets 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, AllowEmpty = true, Encoder = typeof(ScopeEncoder))]
+ public HashSet<string> Scope { get; private set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/AuthenticatedClientRequestBase.cs b/src/DotNetOpenAuth/OAuth2/Messages/AuthenticatedClientRequestBase.cs
new file mode 100644
index 0000000..292ea95
--- /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 or sets the client identifier previously obtained from the Authorization Server.
+ /// </summary>
+ /// <value>The client identifier.</value>
+ [MessagePart(Protocol.client_id, IsRequired = true, AllowEmpty = false)]
+ public string ClientIdentifier { get; internal set; }
+
+ /// <summary>
+ /// Gets or sets 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, AllowEmpty = true)]
+ 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..b125c67
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationFailedResponse.cs
@@ -0,0 +1,70 @@
+//-----------------------------------------------------------------------
+// <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;
+
+ public class EndUserAuthorizationFailedResponse : 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 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, "request");
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ }
+
+ /// <summary>
+ /// Gets or sets the error.
+ /// </summary>
+ /// <value>One of the values given in <see cref="Protocol.EndUserAuthorizationRequestErrorCodes"/>.</value>
+ [MessagePart(Protocol.error, IsRequired = true, AllowEmpty = false)]
+ 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, AllowEmpty = true, 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, AllowEmpty = false, 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, AllowEmpty = true)]
+ 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..a4e8b89
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationRequest.cs
@@ -0,0 +1,93 @@
+//-----------------------------------------------------------------------
+// <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.Contracts;
+ 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 {
+ /// <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;
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ }
+
+ /// <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 the type of the authorization 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, AllowEmpty = false, Encoder = typeof(EndUserAuthorizationResponseTypeEncoder))]
+ public EndUserAuthorizationResponseType ResponseType
+ {
+ get { return EndUserAuthorizationResponseType.AuthorizationCode; }
+ }
+
+ /// <summary>
+ /// Gets or sets the identifier by which this client is known to the Authorization Server.
+ /// </summary>
+ [MessagePart(Protocol.client_id, IsRequired = true, AllowEmpty = false)]
+ public string ClientIdentifier { get; set; }
+
+ /// <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, AllowEmpty = 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>
+ /// REQUIRED. The client identifier as described in Section 3.4 (Client Credentials).
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false, AllowEmpty = true)]
+ public string ClientState { get; set; }
+
+ /// <summary>
+ /// Gets or sets 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, AllowEmpty = true, Encoder = typeof(ScopeEncoder))]
+ public HashSet<string> Scope { get; private set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationResponseType.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationResponseType.cs
new file mode 100644
index 0000000..3afcae5
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationResponseType.cs
@@ -0,0 +1,31 @@
+//-----------------------------------------------------------------------
+// <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>
+ [Flags]
+ public enum EndUserAuthorizationResponseType {
+ /// <summary>
+ /// An access token should be returned immediately.
+ /// </summary>
+ AccessToken = 0x1,
+
+ /// <summary>
+ /// An authorization code should be returned, which can later be exchanged for refresh and access tokens.
+ /// </summary>
+ AuthorizationCode = 0x2,
+
+ /// <summary>
+ /// Both an access token and an authorization code should be returned.
+ /// </summary>
+ Both = AccessToken | AuthorizationCode,
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs
new file mode 100644
index 0000000..41c7e68
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAccessTokenResponse.cs
@@ -0,0 +1,64 @@
+//-----------------------------------------------------------------------
+// <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, ITokenCarryingRequest {
+ /// <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);
+ }
+
+ /// <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, "clientCallback");
+ Contract.Requires<ArgumentNullException>(request != null, "request");
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ }
+
+ [MessagePart(Protocol.access_token, AllowEmpty = false, IsRequired = true)]
+ internal string AccessToken { get; set; }
+
+ #region ITokenCarryingRequest Members
+
+ string ITokenCarryingRequest.CodeOrToken {
+ get { return this.AccessToken; }
+ set { this.AccessToken = value; }
+ }
+
+ CodeOrTokenType ITokenCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AccessToken; }
+ }
+
+ IAuthorizationDescription ITokenCarryingRequest.AuthorizationDescription { get; set; }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs
new file mode 100644
index 0000000..5ef501b
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessAuthCodeResponse.cs
@@ -0,0 +1,67 @@
+//-----------------------------------------------------------------------
+// <copyright file="EndUserAuthorizationSuccessAuthCodeResponse.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 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, ITokenCarryingRequest {
+ /// <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, "clientCallback");
+ Contract.Requires<ArgumentNullException>(request != null, "request");
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ }
+
+ [MessagePart(Protocol.code, AllowEmpty = false, IsRequired = true)]
+ internal string AuthorizationCode { get; set; }
+
+ [MessagePart(Protocol.access_token, AllowEmpty = false, IsRequired = false)]
+ internal string AccessToken { get; set; }
+
+ #region ITokenCarryingRequest Members
+
+ string ITokenCarryingRequest.CodeOrToken {
+ get { return this.AuthorizationCode; }
+ set { this.AuthorizationCode = value; }
+ }
+
+ CodeOrTokenType ITokenCarryingRequest.CodeOrTokenType {
+ get { return CodeOrTokenType.AuthorizationCode; }
+ }
+
+ IAuthorizationDescription ITokenCarryingRequest.AuthorizationDescription { get; set; }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs
new file mode 100644
index 0000000..305c0e6
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/EndUserAuthorizationSuccessResponseBase.cs
@@ -0,0 +1,76 @@
+//-----------------------------------------------------------------------
+// <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, "clientCallback");
+ Contract.Requires<ArgumentNullException>(request != null, "request");
+ ((IMessageWithClientState)this).ClientState = request.ClientState;
+ this.Scope = new HashSet<string>(OAuthUtilities.ScopeStringComparer);
+ }
+
+ /// <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, AllowEmpty = true)]
+ string IMessageWithClientState.ClientState { get; set; }
+
+ /// <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; }
+
+ /// <summary>
+ /// Gets 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, AllowEmpty = true, Encoder = typeof(ScopeEncoder))]
+ public ICollection<string> Scope { get; private 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..1321ac2
--- /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>
+ BasicCredentials,
+
+ /// <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>
+ None,
+ }
+}
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..3233360
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Messages/MessageBase.cs
@@ -0,0 +1,210 @@
+//-----------------------------------------------------------------------
+// <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.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 MessageProtections.None; }
+ }
+
+ /// <summary>
+ /// Gets a value indicating whether this is a direct or indirect message.
+ /// </summary>
+ /// <value></value>
+ MessageTransport IProtocolMessage.Transport {
+ get { return this.messageTransport; }
+ }
+
+ #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 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 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/UnauthorizedResponse.cs b/src/DotNetOpenAuth/OAuth2/Messages/UnauthorizedResponse.cs
new file mode 100644
index 0000000..0f12a8c
--- /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, "exception");
+ 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, "exception");
+ 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.HttpAuthorizationScheme },
+ };
+ }
+ }
+
+ #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..f4a74cc
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/OAuthStrings.Designer.cs
@@ -0,0 +1,135 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.1
+//
+// 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 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 Client&apos;s pre-registered callback URL ({0}) does not match the one found in the authorization request ({1})..
+ /// </summary>
+ internal static string CallbackMismatch {
+ get {
+ return ResourceManager.GetString("CallbackMismatch", 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 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..dacd9fc
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/OAuthStrings.resx
@@ -0,0 +1,144 @@
+<?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="AccessScopeExceedsGrantScope" xml:space="preserve">
+ <value>The requested access scope ("{0}") exceeds the grant scope ("{1}").</value>
+ </data>
+ <data name="CallbackMismatch" xml:space="preserve">
+ <value>Client's pre-registered callback URL ({0}) does not match the one found in the authorization request ({1}).</value>
+ </data>
+ <data name="CannotObtainAccessTokenWithReason" xml:space="preserve">
+ <value>Failed to obtain access token. Authorization Server reports reason: {0}</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..6b4c42a
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/OAuthUtilities.cs
@@ -0,0 +1,117 @@
+//-----------------------------------------------------------------------
+// <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 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 +
+ @"!#$%&'()*+-./:<=>?@[]^_`{|}~\,;";
+
+ public static readonly StringComparer ScopeStringComparer = StringComparer.Ordinal;
+
+ /// <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 scope.</param>
+ /// <param name="scopeComparer">The scope comparer, allowing scopes to be case sensitive or insensitive.
+ /// Usually <see cref="StringComparer.Ordinal"/> or <see cref="StringComparer.OrdinalIgnoreCase"/>.</param>
+ /// <returns></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);
+ }
+
+ public static string JoinScopes(HashSet<string> scopes) {
+ Contract.Requires<ArgumentNullException>(scopes != null, "scopes");
+ 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 AuthorizeWithOAuthWrap(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.HttpAuthorizationHeaderFormat,
+ 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..a8a67bb
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/Protocol.cs
@@ -0,0 +1,330 @@
+// <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 "OAuth";
+ /// </summary>
+ internal const string HttpAuthorizationScheme = "OAuth";
+
+ /// <summary>
+ /// The format of the HTTP Authorization header value that authorizes OAuth 2.0 requests.
+ /// </summary>
+ internal const string HttpAuthorizationHeaderFormat = "OAuth token=\"{0}\"";
+
+ /// <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 "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 "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");
+ }
+ }
+
+ internal static class ResponseTypes
+ {
+ internal const string Code = "code";
+ internal const string Token = "token";
+ internal const string CodeAndToken = "code-and-token";
+ }
+
+ internal static class GrantTypes
+ {
+ internal const string AuthorizationCode = "authorization-code";
+
+ internal const string BasicCredentials = "basic-credentials";
+
+ internal const string Assertion = "assertion";
+
+ internal const string RefreshToken = "refresh-token";
+
+ internal const string None = "none";
+ }
+
+ /// <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 identifier provided is invalid, the client failed to authenticate, or the client provided multiple client credentials.
+ /// </summary>
+ internal const string InvalidClientCredentials = "invalid-client-credentials";
+
+ /// <summary>
+ /// The client is not authorized to use the access grant type provided.
+ /// </summary>
+ internal const string UnauthorizedClient = "unauthorized-client";
+
+ /// <summary>
+ /// The provided access grant is invalid, expired, or revoked (e.g. invalid assertion, expired authorization token, bad end-user basic credentials, or mismatching authorization code and redirection URI).
+ /// </summary>
+ internal const string InvalidGrant = "invalid-grant";
+
+ /// <summary>
+ /// The access grant included - its type or another attribute - is not supported by the authorization server.
+ /// </summary>
+ internal const string UnsupportedGrantType = "unsupported-grant-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 identifier provided is invalid.
+ /// </summary>
+ internal const string InvalidClientId = "invalid-client-id";
+
+ /// <summary>
+ /// The client is not authorized to use the requested response type.
+ /// </summary>
+ internal const string UnauthorizedClient = "unauthorized-client";
+
+ /// <summary>
+ /// The redirection URI provided does not match a pre-registered value.
+ /// </summary>
+ internal const string RedirectUriMismatch = "redirect-uri-mismatch";
+
+ /// <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";
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuth2/ResourceServer.cs b/src/DotNetOpenAuth/OAuth2/ResourceServer.cs
new file mode 100644
index 0000000..a2afdae
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/ResourceServer.cs
@@ -0,0 +1,144 @@
+//-----------------------------------------------------------------------
+// <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.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, "accessTokenAnalyzer");
+
+ 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 or sets the endpoint information for an authorization server that may be used
+ /// to obtain an access token for this resource.
+ /// </summary>
+ /// <value>The authorization server description.</value>
+ /// <remarks>
+ /// This value is optional. If set, this information will be used to generate
+ /// more useful HTTP 401 Unauthorized responses for requests that lack an OAuth access token.
+ /// </remarks>
+ public AuthorizationServerDescription AuthorizationServerDescription { get; 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>
+ 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>
+ public virtual OutgoingWebResponse VerifyAccess(HttpRequestInfo httpRequestInfo, out string username, out HashSet<string> scope) {
+ Contract.Requires<ArgumentNullException>(httpRequestInfo != null, "httpRequestInfo");
+
+ 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>
+ public virtual OutgoingWebResponse VerifyAccess(HttpRequestInfo httpRequestInfo, out IPrincipal principal) {
+ string username;
+ HashSet<string> scope;
+ var result = this.VerifyAccess(httpRequestInfo, out username, out scope);
+ if (result == null) {
+ principal = new OAuth.ChannelElements.OAuthPrincipal(username, scope != null ? scope.ToArray() : new string[0]);
+ } else {
+ principal = 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>
+ public virtual OutgoingWebResponse VerifyAccess(HttpRequestMessageProperty request, Uri requestUri, out IPrincipal principal) {
+ Contract.Requires<ArgumentNullException>(request != null, "request");
+ Contract.Requires<ArgumentNullException>(requestUri != null, "requestUri");
+
+ 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..d4d4c2f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/StandardAccessTokenAnalyzer.cs
@@ -0,0 +1,62 @@
+//-----------------------------------------------------------------------
+// <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.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 authorization server public signing key.</param>
+ /// <param name="resourceServerPrivateEncryptionKey">The resource server private encryption key.</param>
+ public StandardAccessTokenAnalyzer(RSAParameters authorizationServerPublicSigningKey, RSAParameters resourceServerPrivateEncryptionKey) {
+ this.AuthorizationServerPublicSigningKey = authorizationServerPublicSigningKey;
+ this.ResourceServerPrivateEncryptionKey = resourceServerPrivateEncryptionKey;
+ }
+
+ /// <summary>
+ /// Gets the authorization server public signing key.
+ /// </summary>
+ /// <value>The authorization server public signing key.</value>
+ public RSAParameters AuthorizationServerPublicSigningKey { get; private set; }
+
+ /// <summary>
+ /// Gets the resource server private encryption key.
+ /// </summary>
+ /// <value>The resource server private encryption key.</value>
+ public RSAParameters 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..367a36a
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/UserAgentClient.cs
@@ -0,0 +1,107 @@
+//-----------------------------------------------------------------------
+// <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>
+ 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, "authorizationEndpoint");
+ }
+
+ /// <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, "authorization");
+ 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, "actualRedirectUrl");
+
+ 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) {
+ this.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..091b022
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuth2/WebServerClient.cs
@@ -0,0 +1,126 @@
+//-----------------------------------------------------------------------
+// <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>
+ /// <returns>The authorization request as an HTTP response that causes a redirect.</returns>
+ public OutgoingWebResponse RequestUserAuthorization(IEnumerable<string> scope = null) {
+ var response = this.PrepareRequestUserAuthorization(scope);
+ return this.Channel.PrepareResponse(response);
+ }
+
+ /// <summary>
+ /// Prepares a request for user authorization from an authorization server.
+ /// </summary>
+ /// <param name="scope">The scope of authorized access requested.</param>
+ /// <returns>The authorization request.</returns>
+ public EndUserAuthorizationRequest PrepareRequestUserAuthorization(IEnumerable<string> scopes = null) {
+ var authorizationState = new AuthorizationState(scopes);
+ return this.PrepareRequestUserAuthorization(authorizationState);
+ }
+
+ /// <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>
+ /// <returns>The authorization request.</returns>
+ public EndUserAuthorizationRequest PrepareRequestUserAuthorization(IAuthorizationState authorization) {
+ 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<EndUserAuthorizationRequest>() != null);
+ Contract.Ensures(Contract.Result<EndUserAuthorizationRequest>().ClientIdentifier == this.ClientIdentifier);
+ Contract.Ensures(Contract.Result<EndUserAuthorizationRequest>().Callback == authorization.Callback);
+
+ 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,
+ };
+ request.Scope.ResetContents(authorization.Scope);
+
+ return 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/Behaviors/GsaIcamProfile.cs b/src/DotNetOpenAuth/OpenId/Behaviors/GsaIcamProfile.cs
index 20c207f..97a55c1 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,13 @@ namespace DotNetOpenAuth.OpenId.Behaviors {
private static readonly TimeSpan MaximumAssociationLifetime = TimeSpan.FromSeconds(86400);
/// <summary>
+ /// Initializes static members of the <see cref="GsaIcamProfile"/> class.
+ /// </summary>
+ static GsaIcamProfile() {
+ DisableSslRequirement = DotNetOpenAuthSection.Configuration.Messaging.RelaxSslRequirements;
+ }
+
+ /// <summary>
/// Initializes a new instance of the <see cref="GsaIcamProfile"/> class.
/// </summary>
public GsaIcamProfile() {
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/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/version.txt b/src/version.txt
index 1cf8253..1545d96 100644
--- a/src/version.txt
+++ b/src/version.txt
@@ -1 +1 @@
-3.4.6
+3.5.0