summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj4
-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/OAuthWrap/MessageFactoryTests.cs290
-rw-r--r--src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapChannelTests.cs21
-rw-r--r--src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapTestBase.cs15
-rw-r--r--src/DotNetOpenAuth.sln1
-rw-r--r--src/DotNetOpenAuth/DotNetOpenAuth.csproj85
-rw-r--r--src/DotNetOpenAuth/Logger.cs10
-rw-r--r--src/DotNetOpenAuth/Messaging/Channel.cs41
-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/MessagingStrings.Designer.cs9
-rw-r--r--src/DotNetOpenAuth/Messaging/MessagingStrings.resx5
-rw-r--r--src/DotNetOpenAuth/Messaging/MessagingUtilities.cs24
-rw-r--r--src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs198
-rw-r--r--src/DotNetOpenAuth/Messaging/Reflection/MessageDescriptionCollection.cs32
-rw-r--r--src/DotNetOpenAuth/Messaging/StandardMessageFactory.cs269
-rw-r--r--src/DotNetOpenAuth/Messaging/TimespanSecondsEncoder.cs (renamed from src/DotNetOpenAuth/OpenId/Extensions/ProviderAuthenticationPolicy/TimespanSecondsEncoder.cs)9
-rw-r--r--src/DotNetOpenAuth/OAuth/Protocol.cs2
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/AuthorizationServerBase.cs38
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/AuthorizationServerDescription.cs62
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/AuthorizationState.cs47
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ChannelElements/OAuthWrapChannel.cs156
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/ClientBase.cs70
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/IAuthorizationServer.cs32
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/IAuthorizationState.cs67
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/IClientTokenManager.cs42
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/AccessTokenFailedResponse.cs37
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/AccessTokenSuccessResponse.cs83
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/Assertion/AssertionRequest.cs81
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/Assertion/AssertionSuccessResponse.cs40
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/ClientCredentials/ClientCredentialsRequest.cs69
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppAccessTokenFailedResponse.cs21
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppAccessTokenRequest.cs61
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppAccessTokenSuccessResponse.cs45
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppRequest.cs46
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppResponse.cs73
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/IMessageWithClientState.cs13
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/MessageBase.cs205
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/RefreshAccessTokenRequest.cs62
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UnauthorizedResponse.cs47
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentFailedResponse.cs42
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentRequest.cs91
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentSuccessResponse.cs65
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordCaptchaResponse.cs54
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordFailedResponse.cs22
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordRequest.cs93
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordSuccessResponse.cs51
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordVerificationResponse.cs55
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppAccessTokenRequest.cs109
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppFailedResponse.cs47
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppRequest.cs89
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppSuccessResponse.cs49
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.Designer.cs99
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.resx132
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/Protocol.cs223
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/WebAppAuthorizationServer.cs106
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/WebAppClient.cs116
-rw-r--r--src/DotNetOpenAuth/OAuthWrap/WrapUtilities.cs34
-rw-r--r--src/DotNetOpenAuth/OpenId/Messages/DirectErrorResponse.cs8
-rw-r--r--src/version.txt2
64 files changed, 4272 insertions, 102 deletions
diff --git a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
index 6355d59..ee39ba3 100644
--- a/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
+++ b/src/DotNetOpenAuth.Test/DotNetOpenAuth.Test.csproj
@@ -196,6 +196,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" />
@@ -221,6 +222,9 @@
<Compile Include="Mocks\TestChannel.cs" />
<Compile Include="Mocks\TestMessage.cs" />
<Compile Include="Mocks\TestMessageFactory.cs" />
+ <Compile Include="OAuthWrap\MessageFactoryTests.cs" />
+ <Compile Include="OAuthWrap\OAuthWrapChannelTests.cs" />
+ <Compile Include="OAuthWrap\OAuthWrapTestBase.cs" />
<Compile Include="OAuth\ChannelElements\HmacSha1SigningBindingElementTests.cs" />
<Compile Include="OAuth\ChannelElements\OAuthChannelTests.cs" />
<Compile Include="OAuth\ChannelElements\PlaintextSigningBindingElementTest.cs" />
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/OAuthWrap/MessageFactoryTests.cs b/src/DotNetOpenAuth.Test/OAuthWrap/MessageFactoryTests.cs
new file mode 100644
index 0000000..414afba
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuthWrap/MessageFactoryTests.cs
@@ -0,0 +1,290 @@
+//-----------------------------------------------------------------------
+// <copyright file="MessageFactoryTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap;
+ using DotNetOpenAuth.OAuthWrap.ChannelElements;
+ using DotNetOpenAuth.OAuthWrap.Messages;
+ using NUnit.Framework;
+
+ /// <summary>
+ /// Verifies that the WRAP message types are recognized.
+ /// </summary>
+ public class MessageFactoryTests : OAuthWrapTestBase {
+ private readonly MessageReceivingEndpoint recipient = new MessageReceivingEndpoint("http://who", HttpDeliveryMethods.PostRequest);
+ private OAuthWrapChannel channel;
+ private IMessageFactory messageFactory;
+
+ public override void SetUp() {
+ base.SetUp();
+
+ this.channel = new OAuthWrapChannel();
+ this.messageFactory = OAuthWrapChannel_Accessor.AttachShadow(this.channel).MessageFactory;
+ }
+
+ #region Refresh Access Token messages
+
+ [TestCase]
+ public void RefreshAccessTokenRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.refresh_token, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(RefreshAccessTokenRequest), request);
+ }
+
+ [TestCase]
+ public void RefreshAccessTokenSuccessResponse() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.access_token, "abc" },
+ };
+ var request = new RefreshAccessTokenRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(AccessTokenSuccessResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ [TestCase]
+ public void RefreshAccessTokenFailedResponse() {
+ var fields = new Dictionary<string, string> {
+ };
+ var request = new RefreshAccessTokenRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(AccessTokenFailedResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ #endregion
+
+ #region Web App profile messages
+
+ [TestCase]
+ public void WebAppRequestRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.redirect_uri, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(WebAppRequest), request);
+ }
+
+ [TestCase]
+ public void WebAppFailedResponse() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.error, "user_denied" },
+ };
+ var request = new WebAppRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(WebAppFailedResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ [TestCase]
+ public void WebAppSuccessResponse() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.code, "abc" },
+ };
+ var request = new WebAppRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(WebAppSuccessResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ [TestCase]
+ public void WebAppAccessTokenRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.client_secret, "abc" },
+ { Protocol.code, "abc" },
+ { Protocol.redirect_uri, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(WebAppAccessTokenRequest), request);
+ }
+
+ [TestCase, Ignore("Not implemented")]
+ public void WebAppAccessTokenFailedResponse() {
+ // HTTP 400 Bad Request
+ }
+
+ [TestCase, Ignore("Not implemented")]
+ public void WebAppAccessTokenBadClientResponse() {
+ // HTTP 401 Unauthorized
+ // WWW-Authenticate: WRAP
+ }
+
+ #endregion
+
+ #region Username and Password profile messages
+
+ [TestCase]
+ public void UserNamePasswordRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.wrap_username, "abc" },
+ { Protocol.wrap_password, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(UserNamePasswordRequest), request);
+ }
+
+ [TestCase]
+ public void UserNamePasswordSuccessResponse() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.access_token, "abc" },
+ };
+ var request = new UserNamePasswordRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(UserNamePasswordSuccessResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ [TestCase]
+ public void UserNamePasswordVerificationResponse() {
+ // HTTP 400 Bad Request
+ var fields = new Dictionary<string, string> {
+ { Protocol.wrap_verification_url, "abc" },
+ };
+ var request = new UserNamePasswordRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(UserNamePasswordVerificationResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ [TestCase, Ignore("Not implemented")]
+ public void UserNamePasswordFailedResponse() {
+ // HTTP 401 Unauthorized
+ // WWW-Authenticate: WRAP
+ }
+
+ [TestCase]
+ public void UsernamePasswordCaptchaResponse() {
+ // HTTP 400 Bad Request
+ var fields = new Dictionary<string, string> {
+ { Protocol.wrap_captcha_url, "abc" },
+ };
+ var request = new UserNamePasswordRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(UsernamePasswordCaptchaResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ #endregion
+
+ #region Rich App profile messages
+
+ [TestCase]
+ public void RichAppRequest() {
+ // include just required parameters
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(RichAppRequest), request);
+
+ // including optional parts
+ fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.redirect_uri, "abc" },
+ { Protocol.state, "abc" },
+ { Protocol.scope, "abc" },
+ };
+ request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(RichAppRequest), request);
+ }
+
+ [TestCase]
+ public void RichAppResponse() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.refresh_token, "abc" },
+ { Protocol.access_token, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(RichAppResponse), request);
+ }
+
+ [TestCase]
+ public void RichAppAccessTokenRequest() {
+ // include just required parameters
+ var fields = new Dictionary<string, string> {
+ { Protocol.client_id, "abc" },
+ { Protocol.code, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(RichAppAccessTokenRequest), request);
+ }
+
+ [TestCase]
+ public void RichAppAccessTokenSuccessResponse() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.refresh_token, "abc" },
+ { Protocol.access_token, "abc" },
+ };
+ var request = new RichAppAccessTokenRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(RichAppAccessTokenSuccessResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ [TestCase]
+ public void RichAppAccessTokenFailedResponse() {
+ // HTTP 401 Unauthorized
+ // WWW-Authenticate: WRAP
+ var fields = new Dictionary<string, string> {
+ };
+ var request = new RichAppAccessTokenRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(RichAppAccessTokenFailedResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ #endregion
+
+ #region Client Account and Password profile messages
+
+ [TestCase]
+ public void ClientCredentialsRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.wrap_name, "abc" },
+ { Protocol.wrap_password, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(ClientCredentialsRequest), request);
+ }
+
+ #endregion
+
+ #region Assertion profile messages
+
+ [TestCase]
+ public void AssertionRequest() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.format, "abc" },
+ { Protocol.assertion, "abc" },
+ };
+ IDirectedProtocolMessage request = this.messageFactory.GetNewRequestMessage(this.recipient, fields);
+ Assert.IsInstanceOf(typeof(AssertionRequest), request);
+ }
+
+ [TestCase]
+ public void AssertionSuccessResponse() {
+ var fields = new Dictionary<string, string> {
+ { Protocol.access_token, "abc" },
+ };
+ var request = new AssertionRequest(this.recipient.Location, Protocol.Default.Version);
+ Assert.IsInstanceOf(
+ typeof(AssertionSuccessResponse),
+ this.messageFactory.GetNewResponseMessage(request, fields));
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapChannelTests.cs b/src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapChannelTests.cs
new file mode 100644
index 0000000..c7fe48f
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapChannelTests.cs
@@ -0,0 +1,21 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthWrapChannelTests.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap;
+ using DotNetOpenAuth.OAuthWrap.ChannelElements;
+ using DotNetOpenAuth.OAuthWrap.Messages;
+ using NUnit.Framework;
+
+ [TestFixture]
+ public class OAuthWrapChannelTests : OAuthWrapTestBase {
+ }
+}
diff --git a/src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapTestBase.cs b/src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapTestBase.cs
new file mode 100644
index 0000000..08c9da6
--- /dev/null
+++ b/src/DotNetOpenAuth.Test/OAuthWrap/OAuthWrapTestBase.cs
@@ -0,0 +1,15 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthWrapTestBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.Test.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ public class OAuthWrapTestBase : TestBase {
+ }
+}
diff --git a/src/DotNetOpenAuth.sln b/src/DotNetOpenAuth.sln
index f6f3d03..60dffe6 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/DotNetOpenAuth.csproj b/src/DotNetOpenAuth/DotNetOpenAuth.csproj
index 1c018eb..dd95d3a 100644
--- a/src/DotNetOpenAuth/DotNetOpenAuth.csproj
+++ b/src/DotNetOpenAuth/DotNetOpenAuth.csproj
@@ -224,13 +224,13 @@ http://opensource.org/licenses/ms-pl.html
</Reference>
</ItemGroup>
<ItemGroup Condition=" '$(ClrVersion)' == '4' ">
- <Reference Include="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"/>
+ <Reference Include="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
</ItemGroup>
<ItemGroup Condition=" '$(ClrVersion)' != '4' ">
<!-- MVC 2 can run on CLR 2 (it doesn't require CLR 4) but since MVC 2 apps tend to use type forwarding,
it's a more broadly consumable idea to bind against MVC 1 for the library unless we're building on CLR 4,
which will definitely have MVC 2 available. -->
- <Reference Include="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"/>
+ <Reference Include="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" />
</ItemGroup>
<ItemGroup>
<Compile Include="ComponentModel\ClaimTypeSuggestions.cs" />
@@ -284,6 +284,7 @@ http://opensource.org/licenses/ms-pl.html
<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" />
@@ -304,6 +305,32 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="Messaging\Reflection\MessageDescriptionCollection.cs" />
<Compile Include="Mvc\OpenIdHelper.cs" />
<Compile Include="Mvc\OpenIdAjaxOptions.cs" />
+ <Compile Include="Messaging\StandardMessageFactory.cs" />
+ <Compile Include="OAuthWrap\AuthorizationServerBase.cs" />
+ <Compile Include="OAuthWrap\AuthorizationState.cs" />
+ <Compile Include="OAuthWrap\IAuthorizationServer.cs" />
+ <Compile Include="OAuthWrap\IAuthorizationState.cs" />
+ <Compile Include="OAuthWrap\IClientTokenManager.cs" />
+ <Compile Include="OAuthWrap\Messages\Assertion\AssertionRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\ClientCredentials\ClientCredentialsRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\Assertion\AssertionSuccessResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\IMessageWithClientState.cs" />
+ <Compile Include="OAuthWrap\Messages\RefreshAccessTokenRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\Device\RichAppAccessTokenRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\Device\RichAppRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\Device\RichAppResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\Device\RichAppAccessTokenSuccessResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\Device\RichAppAccessTokenFailedResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\UnauthorizedResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\AccessTokenFailedResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\AccessTokenSuccessResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\UserAgent\UserAgentFailedResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\UserAgent\UserAgentRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\UserAgent\UserAgentSuccessResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\UsernameAndPassword\UserNamePasswordCaptchaResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\UsernameAndPassword\UserNamePasswordVerificationResponse.cs" />
+ <Compile Include="OAuthWrap\WebAppAuthorizationServer.cs" />
+ <Compile Include="OAuthWrap\WrapUtilities.cs" />
<Compile Include="OAuth\ChannelElements\ICombinedOpenIdProviderTokenManager.cs" />
<Compile Include="OAuth\ChannelElements\IConsumerDescription.cs" />
<Compile Include="OAuth\ChannelElements\IConsumerTokenManager.cs" />
@@ -447,7 +474,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" />
@@ -590,6 +617,24 @@ http://opensource.org/licenses/ms-pl.html
<Compile Include="Messaging\StandardWebRequestHandler.cs" />
<Compile Include="Messaging\MessageReceivingEndpoint.cs" />
<Compile Include="Reporting.cs" />
+ <Compile Include="OAuthWrap\ChannelElements\OAuthWrapChannel.cs" />
+ <Compile Include="OAuthWrap\ClientBase.cs" />
+ <Compile Include="OAuthWrap\Messages\MessageBase.cs" />
+ <Compile Include="OAuthWrap\Messages\WebServer\WebAppAccessTokenRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\WebServer\WebAppFailedResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\WebServer\WebAppRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\WebServer\WebAppSuccessResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\UsernameAndPassword\UserNamePasswordFailedResponse.cs" />
+ <Compile Include="OAuthWrap\Messages\UsernameAndPassword\UserNamePasswordRequest.cs" />
+ <Compile Include="OAuthWrap\Messages\UsernameAndPassword\UserNamePasswordSuccessResponse.cs" />
+ <Compile Include="OAuthWrap\Protocol.cs" />
+ <Compile Include="OAuthWrap\OAuthWrapStrings.Designer.cs">
+ <AutoGen>True</AutoGen>
+ <DesignTime>True</DesignTime>
+ <DependentUpon>OAuthWrapStrings.resx</DependentUpon>
+ </Compile>
+ <Compile Include="OAuthWrap\AuthorizationServerDescription.cs" />
+ <Compile Include="OAuthWrap\WebAppClient.cs" />
<Compile Include="Util.cs" />
<Compile Include="OAuth\Protocol.cs" />
<Compile Include="OAuth\ServiceProvider.cs" />
@@ -702,6 +747,10 @@ http://opensource.org/licenses/ms-pl.html
<EmbeddedResource Include="OpenId\RelyingParty\OpenIdRelyingPartyAjaxControlBase.js">
<Copyright>$(StandardCopyright)</Copyright>
</EmbeddedResource>
+ <EmbeddedResource Include="OAuthWrap\OAuthWrapStrings.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>OAuthWrapStrings.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
<EmbeddedResource Include="Strings.sr.resx" />
<EmbeddedResource Include="Xrds\XrdsStrings.sr.resx" />
</ItemGroup>
@@ -732,31 +781,19 @@ http://opensource.org/licenses/ms-pl.html
</BootstrapperPackage>
<Content Include="DotNetOpenAuth.ico" />
</ItemGroup>
-
<ItemGroup>
<SignDependsOn Include="BuildUnifiedProduct" />
- <DelaySignedAssemblies Include="$(ILMergeOutputAssembly);
- $(OutputPath)CodeContracts\$(ProductName).Contracts.dll;
- " />
+ <DelaySignedAssemblies Include="$(ILMergeOutputAssembly);&#xD;&#xA; $(OutputPath)CodeContracts\$(ProductName).Contracts.dll;&#xD;&#xA; " />
</ItemGroup>
- <PropertyGroup>
- <!-- Don't sign the non-unified version of the assembly. -->
- <SuppressTargetPathDelaySignedAssembly>true</SuppressTargetPathDelaySignedAssembly>
- </PropertyGroup>
-
- <Target Name="BuildUnifiedProduct"
- DependsOnTargets="Build"
- Inputs="@(ILMergeInputAssemblies)"
- Outputs="$(ILMergeOutputAssembly)">
+ <ItemGroup />
+ <PropertyGroup>
+ <!-- Don't sign the non-unified version of the assembly. -->
+ <SuppressTargetPathDelaySignedAssembly>true</SuppressTargetPathDelaySignedAssembly>
+ </PropertyGroup>
+ <Target Name="BuildUnifiedProduct" DependsOnTargets="Build" Inputs="@(ILMergeInputAssemblies)" Outputs="$(ILMergeOutputAssembly)">
<MakeDir Directories="$(ILMergeOutputAssemblyDirectory)" />
- <ILMerge ExcludeFile="$(ProjectRoot)ILMergeInternalizeExceptions.txt"
- InputAssemblies="@(ILMergeInputAssemblies)"
- OutputFile="$(ILMergeOutputAssembly)"
- KeyFile="$(PublicKeyFile)"
- DelaySign="true"
- />
+ <ILMerge ExcludeFile="$(ProjectRoot)ILMergeInternalizeExceptions.txt" InputAssemblies="@(ILMergeInputAssemblies)" OutputFile="$(ILMergeOutputAssembly)" KeyFile="$(PublicKeyFile)" DelaySign="true" />
</Target>
-
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(ProjectRoot)tools\DotNetOpenAuth.targets" />
-</Project>
+</Project> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/Logger.cs b/src/DotNetOpenAuth/Logger.cs
index 48007ed..7c8691c 100644
--- a/src/DotNetOpenAuth/Logger.cs
+++ b/src/DotNetOpenAuth/Logger.cs
@@ -75,6 +75,11 @@ namespace DotNetOpenAuth {
private static readonly ILog oauth = Create("DotNetOpenAuth.OAuth");
/// <summary>
+ /// Backing field for the <see cref="Wrap"/> property.
+ /// </summary>
+ private static readonly ILog wrap = Create("DotNetOpenAuth.WRAP");
+
+ /// <summary>
/// Backing field for the <see cref="InfoCard"/> property.
/// </summary>
private static readonly ILog infocard = Create("DotNetOpenAuth.InfoCard");
@@ -130,6 +135,11 @@ namespace DotNetOpenAuth {
internal static ILog OAuth { get { return oauth; } }
/// <summary>
+ /// Gets the logger for the high-level OAuth WRAP events.
+ /// </summary>
+ internal static ILog Wrap { get { return wrap; } }
+
+ /// <summary>
/// Gets the logger for high-level InfoCard events.
/// </summary>
internal static ILog InfoCard { get { return infocard; } }
diff --git a/src/DotNetOpenAuth/Messaging/Channel.cs b/src/DotNetOpenAuth/Messaging/Channel.cs
index 055ce68..2e15fb5 100644
--- a/src/DotNetOpenAuth/Messaging/Channel.cs
+++ b/src/DotNetOpenAuth/Messaging/Channel.cs
@@ -40,6 +40,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.
@@ -151,7 +161,7 @@ namespace DotNetOpenAuth.Messaging {
/// <summary>
/// Gets or sets the message descriptions.
/// </summary>
- internal MessageDescriptionCollection MessageDescriptions {
+ internal virtual MessageDescriptionCollection MessageDescriptions {
get {
return this.messageDescriptions;
}
@@ -201,11 +211,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 {
get { return this.messageTypeProvider; }
+ set { this.messageTypeProvider = value; }
}
/// <summary>
@@ -634,6 +645,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);
@@ -641,10 +653,25 @@ 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) {
+ // First try creating a 301 redirect, and fallback to a form POST
+ // if the message is too big.
+ response = this.Create301RedirectResponse(message, fields);
+ 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);
}
@@ -870,7 +897,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/MessagingStrings.Designer.cs b/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs
index 6f8c4f9..1be62f5 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs
+++ b/src/DotNetOpenAuth/Messaging/MessagingStrings.Designer.cs
@@ -421,6 +421,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 bdf4f68..cb80442 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingStrings.resx
+++ b/src/DotNetOpenAuth/Messaging/MessagingStrings.resx
@@ -303,4 +303,7 @@
<data name="SessionRequired" xml:space="preserve">
<value>An HttpContext.Current.Session object is required.</value>
</data>
-</root> \ No newline at end of file
+ <data name="StandardMessageFactoryUnsupportedMessageType" xml:space="preserve">
+ <value>This message factory does not support message type(s): {0}</value>
+ </data>
+</root>
diff --git a/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs b/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs
index 5dccc7a..40a0791 100644
--- a/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs
+++ b/src/DotNetOpenAuth/Messaging/MessagingUtilities.cs
@@ -193,6 +193,30 @@ namespace DotNetOpenAuth.Messaging {
}
/// <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>
diff --git a/src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs b/src/DotNetOpenAuth/Messaging/Reflection/MessageDescription.cs
index 5493ba6..17b5304 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>
@@ -70,51 +86,17 @@ 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);
} 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;
@@ -122,42 +104,134 @@ 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);
+ }
+
+ /// <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));
+ } else {
+ Logger.Messaging.DebugFormat(
MessagingStrings.RequiredNonEmptyParameterWasEmpty,
- this.messageType.FullName,
- string.Join(", ", emptyValuedKeys)));
+ this.MessageType.FullName,
+ emptyValuedKeys.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 ff8b74b..8911960 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/StandardMessageFactory.cs b/src/DotNetOpenAuth/Messaging/StandardMessageFactory.cs
new file mode 100644
index 0000000..40f2d5d
--- /dev/null
+++ b/src/DotNetOpenAuth/Messaging/StandardMessageFactory.cs
@@ -0,0 +1,269 @@
+//-----------------------------------------------------------------------
+// <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 => 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())
+ orderby 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 });
+ }
+
+ 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;
+ }
+
+ private IEnumerable<ConstructorInfo> FindMatchingResponseConstructors(MessageDescription messageDescription, Type requestType) {
+ Contract.Requires<ArgumentNullException>(messageDescription != null);
+ Contract.Requires<ArgumentNullException>(requestType != null);
+
+ return this.responseMessageTypes[messageDescription].Where(pair => pair.Key.IsAssignableFrom(requestType)).Select(pair => pair.Value);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/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/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/OAuthWrap/AuthorizationServerBase.cs b/src/DotNetOpenAuth/OAuthWrap/AuthorizationServerBase.cs
new file mode 100644
index 0000000..cfbd80f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/AuthorizationServerBase.cs
@@ -0,0 +1,38 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationServerBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+using System.Diagnostics.Contracts;
+using DotNetOpenAuth.OAuth.ChannelElements;
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ public abstract class AuthorizationServerBase {
+ protected AuthorizationServerBase(IAuthorizationServer authorizationServer) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null, "authorizationServer");
+ this.AuthorizationServer = authorizationServer;
+ }
+
+ public Channel Channel { get; set; }
+
+ public IAuthorizationServer AuthorizationServer { get; set; }
+
+ protected IConsumerDescription GetClient(string clientIdentifier) {
+ Contract.Requires<ArgumentException>(!String.IsNullOrEmpty(clientIdentifier));
+ Contract.Ensures(Contract.Result<IConsumerDescription>() != null);
+
+ try {
+ return this.AuthorizationServer.GetClient(clientIdentifier);
+ } catch (KeyNotFoundException ex) {
+ throw ErrorUtilities.Wrap(ex, DotNetOpenAuth.OAuth.OAuthStrings.ConsumerOrTokenSecretNotFound);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/AuthorizationServerDescription.cs b/src/DotNetOpenAuth/OAuthWrap/AuthorizationServerDescription.cs
new file mode 100644
index 0000000..93cc1e1
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/AuthorizationServerDescription.cs
@@ -0,0 +1,62 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationServerDescription.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+
+ /// <summary>
+ /// A description of an OAuth WRAP 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 WRAP version supported by the Authorization Server.
+ /// </summary>
+ public ProtocolVersion ProtocolVersion { get; set; }
+
+ /// <summary>
+ /// Gets the version of the OAuth WRAP 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/OAuthWrap/AuthorizationState.cs b/src/DotNetOpenAuth/OAuthWrap/AuthorizationState.cs
new file mode 100644
index 0000000..a19f523
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/AuthorizationState.cs
@@ -0,0 +1,47 @@
+//-----------------------------------------------------------------------
+// <copyright file="AuthorizationState.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System;
+
+ /// <summary>
+ /// A simple memory-only copy of an authorization state.
+ /// </summary>
+ public class AuthorizationState : IAuthorizationState {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AuthorizationState"/> class.
+ /// </summary>
+ public AuthorizationState() {
+ }
+
+ public Uri Callback { get; set; }
+
+ public string RefreshToken { get; set; }
+
+ public string AccessToken { get; set; }
+
+ public string AccessTokenSecret { get; set; }
+
+ public DateTime? AccessTokenExpirationUtc { get; set; }
+
+ public string Scope { get; 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; }
+
+ public void Delete() {
+ this.IsDeleted = true;
+ }
+
+ public void SaveChanges() {
+ }
+ }
+} \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OAuthWrap/ChannelElements/OAuthWrapChannel.cs b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/OAuthWrapChannel.cs
new file mode 100644
index 0000000..e99b2cf
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ChannelElements/OAuthWrapChannel.cs
@@ -0,0 +1,156 @@
+//-----------------------------------------------------------------------
+// <copyright file="OAuthWrapChannel.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.ChannelElements {
+ 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.Messaging.Reflection;
+
+ /// <summary>
+ /// The channel for the OAuth WRAP protocol.
+ /// </summary>
+ internal class OAuthWrapChannel : Channel {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="OAuthWrapChannel"/> class.
+ /// </summary>
+ protected internal OAuthWrapChannel()
+ : base(new StandardMessageFactory()) {
+ ((StandardMessageFactory)this.MessageFactory).AddMessageTypes(GetWrapMessageDescriptions(this.MessageDescriptions));
+ }
+
+ /// <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(GetWrapMessageDescriptions(value));
+ this.MessageFactory = factory;
+ }
+ }
+
+ /// <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="RequestCore"/> method
+ /// is overridden and does not require this method.
+ /// </remarks>
+ protected override HttpWebRequest CreateHttpRequest(IDirectedProtocolMessage request) {
+ HttpWebRequest httpRequest;
+ if ((request.HttpMethods & HttpDeliveryMethods.GetRequest) != 0) {
+ httpRequest = InitializeRequestAsGet(request);
+ } else if ((request.HttpMethods & HttpDeliveryMethods.PostRequest) != 0) {
+ httpRequest = InitializeRequestAsPost(request);
+ } else {
+ throw new NotSupportedException();
+ }
+
+ return httpRequest;
+ }
+
+ /// <summary>
+ /// Gets the protocol message that may be in the given HTTP response.
+ /// </summary>
+ /// <param name="response">The response that is anticipated to contain an protocol message.</param>
+ /// <returns>
+ /// The deserialized message parts, if found. Null otherwise.
+ /// </returns>
+ /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception>
+ protected override IDictionary<string, string> ReadFromResponseCore(IncomingWebResponse response) {
+ // The spec says direct responses should be JSON objects, but Facebook uses HttpFormUrlEncoded instead, calling it text/plain
+ if (response.ContentType.MediaType == JsonEncoded) {
+ throw new NotImplementedException();
+ } else if (response.ContentType.MediaType == HttpFormUrlEncoded || response.ContentType.MediaType == PlainTextEncoded) {
+ string body = response.GetResponseReader().ReadToEnd();
+ return HttpUtility.ParseQueryString(body).ToDictionary();
+ } else {
+ throw ErrorUtilities.ThrowProtocol("Unexpected response Content-Type {0}", response.ContentType.MediaType);
+ }
+ }
+
+ /// <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) {
+ throw new NotImplementedException();
+ }
+
+ /// <summary>
+ /// Gets the message types that come standard with OAuth WRAP.
+ /// </summary>
+ /// <param name="descriptionsCache">The descriptions cache from which to draw.</param>
+ /// <returns>A collection of WRAP message types.</returns>
+ private static IEnumerable<MessageDescription> GetWrapMessageDescriptions(MessageDescriptionCollection descriptionsCache) {
+ Contract.Requires<ArgumentNullException>(descriptionsCache != null);
+ Contract.Ensures(Contract.Result<IEnumerable<MessageDescription>>() != null);
+
+ var messageTypes = new Type[] {
+ typeof(Messages.RefreshAccessTokenRequest),
+ typeof(Messages.AccessTokenSuccessResponse),
+ typeof(Messages.AccessTokenFailedResponse),
+ typeof(Messages.UnauthorizedResponse),
+ typeof(Messages.AssertionRequest),
+ typeof(Messages.AssertionSuccessResponse),
+ typeof(Messages.ClientCredentialsRequest),
+ typeof(Messages.RichAppRequest),
+ typeof(Messages.RichAppResponse),
+ typeof(Messages.RichAppAccessTokenRequest),
+ typeof(Messages.RichAppAccessTokenSuccessResponse),
+ typeof(Messages.RichAppAccessTokenFailedResponse),
+ typeof(Messages.UserNamePasswordRequest),
+ typeof(Messages.UserNamePasswordSuccessResponse),
+ typeof(Messages.UserNamePasswordVerificationResponse),
+ typeof(Messages.UserNamePasswordFailedResponse),
+ typeof(Messages.UsernamePasswordCaptchaResponse),
+ typeof(Messages.WebAppRequest),
+ typeof(Messages.WebAppSuccessResponse),
+ typeof(Messages.WebAppFailedResponse),
+ typeof(Messages.WebAppAccessTokenRequest),
+ typeof(Messages.UserAgentRequest),
+ typeof(Messages.UserAgentSuccessResponse),
+ typeof(Messages.UserAgentFailedResponse),
+ };
+
+ // 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.Length * Protocol.AllVersions.Count);
+ foreach (Protocol protocol in Protocol.AllVersions) {
+ foreach (Type messageType in messageTypes) {
+ messageDescriptions.Add(descriptionsCache.Get(messageType, protocol.Version));
+ }
+ }
+
+ return messageDescriptions;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/ClientBase.cs b/src/DotNetOpenAuth/OAuthWrap/ClientBase.cs
new file mode 100644
index 0000000..d5746bc
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/ClientBase.cs
@@ -0,0 +1,70 @@
+//-----------------------------------------------------------------------
+// <copyright file="ClientBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ 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.OAuthWrap.ChannelElements;
+
+ /// <summary>
+ /// A base class for common OAuth WRAP Consumer behaviors.
+ /// </summary>
+ public class ClientBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ClientBase"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The token issuer.</param>
+ protected ClientBase(AuthorizationServerDescription authorizationServer) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ this.AuthorizationServer = authorizationServer;
+ this.Channel = new OAuthWrapChannel();
+ }
+
+ /// <summary>
+ /// Gets the token issuer.
+ /// </summary>
+ /// <value>The token issuer.</value>
+ public AuthorizationServerDescription AuthorizationServer { get; private set; }
+
+ /// <summary>
+ /// Gets the OAuth WRAP channel.
+ /// </summary>
+ /// <value>The channel.</value>
+ public Channel Channel { get; private set; }
+
+ /// <summary>
+ /// Adds the necessary HTTP Authorization header to an HTTP request for protected resources
+ /// so that the Service Provider will allow the request through.
+ /// </summary>
+ /// <param name="request">The request for protected resources from the service provider.</param>
+ /// <param name="accessToken">The access token previously obtained from the Authorization Server.</param>
+ public static void AuthorizeRequest(HttpWebRequest request, string accessToken) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(accessToken));
+ WrapUtilities.AuthorizeWithOAuthWrap(request, accessToken);
+ }
+
+ /// <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="authorization">The authorization for this request previously obtained via OAuth WRAP.</param>
+ public static 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);
+ AuthorizeRequest(request, authorization.AccessToken);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/IAuthorizationServer.cs b/src/DotNetOpenAuth/OAuthWrap/IAuthorizationServer.cs
new file mode 100644
index 0000000..ba328b1
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/IAuthorizationServer.cs
@@ -0,0 +1,32 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAuthorizationServer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+using System.Diagnostics.Contracts;
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.OAuth.ChannelElements;
+
+ [ContractClass(typeof(IAuthorizationServerContract))]
+ public interface IAuthorizationServer {
+ IConsumerDescription GetClient(string clientIdentifier);
+ }
+
+ [ContractClassFor(typeof(IAuthorizationServer))]
+ internal abstract class IAuthorizationServerContract : IAuthorizationServer {
+ private IAuthorizationServerContract() {
+ }
+
+ IConsumerDescription IAuthorizationServer.GetClient(string clientIdentifier) {
+ Contract.Ensures(Contract.Result<IConsumerDescription>() != null);
+ throw new NotImplementedException();
+ }
+ }
+
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/IAuthorizationState.cs b/src/DotNetOpenAuth/OAuthWrap/IAuthorizationState.cs
new file mode 100644
index 0000000..7e86b5b
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/IAuthorizationState.cs
@@ -0,0 +1,67 @@
+//-----------------------------------------------------------------------
+// <copyright file="IAuthorizationState.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap
+{
+ using System;
+
+ /// <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 secret.
+ /// </summary>
+ /// <value>The access token secret.</value>
+ string AccessTokenSecret { 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>
+ string Scope { 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>
+ 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/OAuthWrap/IClientTokenManager.cs b/src/DotNetOpenAuth/OAuthWrap/IClientTokenManager.cs
new file mode 100644
index 0000000..3b593e3
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/IClientTokenManager.cs
@@ -0,0 +1,42 @@
+//-----------------------------------------------------------------------
+// <copyright file="IClientTokenManager.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System;
+ using System.Diagnostics.Contracts;
+
+ [ContractClass(typeof(IClientTokenManagerContract))]
+ public interface IClientTokenManager {
+ /// <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="IClientTokenManager"/> interface.
+ /// </summary>
+ [ContractClassFor(typeof(IClientTokenManager))]
+ internal abstract class IClientTokenManagerContract : IClientTokenManager {
+ /// <summary>
+ /// Prevents a default instance of the <see cref="IClientTokenManagerContract"/> class from being created.
+ /// </summary>
+ private IClientTokenManagerContract() {
+ }
+
+ #region IClientTokenManager Members
+
+ IAuthorizationState IClientTokenManager.GetAuthorizationState(Uri callbackUrl, string clientState) {
+ Contract.Requires<ArgumentNullException>(callbackUrl != null);
+ throw new NotImplementedException();
+ }
+
+ #endregion
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/AccessTokenFailedResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/AccessTokenFailedResponse.cs
new file mode 100644
index 0000000..c487ebc
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/AccessTokenFailedResponse.cs
@@ -0,0 +1,37 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenFailedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using DotNetOpenAuth.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 : UnauthorizedResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AccessTokenFailedResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal AccessTokenFailedResponse(IDirectedProtocolMessage request)
+ : base(request) {
+ }
+
+ /// <summary>
+ /// Gets or sets the error.
+ /// </summary>
+ /// <value>The error.</value>
+ /// <remarks>
+ /// REQUIRED. The parameter value MUST be set to one of the values specified by each flow.
+ /// </remarks>
+ [MessagePart(Protocol.error, IsRequired = true, AllowEmpty = false)]
+ internal string Error { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/AccessTokenSuccessResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/AccessTokenSuccessResponse.cs
new file mode 100644
index 0000000..3c2714a
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/AccessTokenSuccessResponse.cs
@@ -0,0 +1,83 @@
+//-----------------------------------------------------------------------
+// <copyright file="AccessTokenSuccessResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Net;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A response from the Authorization Server to the Consumer containing a delegation code
+ /// that the Consumer 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(IDirectedProtocolMessage request)
+ : base(request) {
+ }
+
+ /// <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)]
+ internal string AccessToken { get; 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))]
+ internal TimeSpan? Lifetime { get; 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)]
+ internal string RefreshToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token secret.
+ /// </summary>
+ /// <value>The access token secret.</value>
+ /// <remarks>
+ /// REQUIRED if requested by the client. The corresponding access token secret as requested by the client.
+ /// </remarks>
+ [MessagePart(Protocol.access_token_secret, IsRequired = false, AllowEmpty = false)]
+ internal string AccessTokenSecret { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/Assertion/AssertionRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/Assertion/AssertionRequest.cs
new file mode 100644
index 0000000..1024a3f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/Assertion/AssertionRequest.cs
@@ -0,0 +1,81 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssertionRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A request from a Client to an Authorization Server with some assertion for an access token.
+ /// </summary>
+ internal class AssertionRequest : MessageBase {
+ /// <summary>
+ /// The type of message.
+ /// </summary>
+ [MessagePart(Protocol.type, IsRequired = true)]
+ private const string Type = "assertion";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AssertionRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ /// <param name="version">The version.</param>
+ internal AssertionRequest(Uri authorizationServer, Version version)
+ : base(version, MessageTransport.Direct, authorizationServer) {
+ this.HttpMethods = HttpDeliveryMethods.PostRequest;
+ }
+
+ /// <summary>
+ /// Gets or sets the format of the assertion as defined by the Authorization Server.
+ /// </summary>
+ /// <value>The assertion format.</value>
+ [MessagePart(Protocol.format, IsRequired = true, AllowEmpty = false)]
+ internal string AssertionFormat { 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; }
+
+ /// <summary>
+ /// Gets or sets an optional authorization scope as defined by the Authorization Server.
+ /// </summary>
+ [MessagePart(Protocol.scope, IsRequired = false, AllowEmpty = true)]
+ internal string Scope { get; set; }
+
+ /// <summary>
+ /// Gets or sets the type of the secret.
+ /// </summary>
+ /// <value>The type of the secret.</value>
+ /// <remarks>
+ /// OPTIONAL. The access token secret type as described by Section 5.3 (Cryptographic Tokens Requests). If omitted, the authorization server will issue a bearer token (an access token without a matching secret) as described by Section 5.2 (Bearer Token Requests).
+ /// </remarks>
+ [MessagePart(Protocol.secret_type, IsRequired = false, AllowEmpty = false)]
+ internal string SecretType { get; 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(this.Recipient.IsTransportSecure(), OAuthWrapStrings.HttpsRequired);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/Assertion/AssertionSuccessResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/Assertion/AssertionSuccessResponse.cs
new file mode 100644
index 0000000..2dc6ca7
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/Assertion/AssertionSuccessResponse.cs
@@ -0,0 +1,40 @@
+//-----------------------------------------------------------------------
+// <copyright file="AssertionSuccessResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A response from the Authorization Server to the Client containing an access code.
+ /// </summary>
+ internal class AssertionSuccessResponse : MessageBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="AssertionSuccessResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal AssertionSuccessResponse(ClientCredentialsRequest request)
+ : base(request) {
+ }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ [MessagePart(Protocol.access_token, IsRequired = true, AllowEmpty = false)]
+ internal string AccessToken { get; 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))]
+ internal TimeSpan? Lifetime { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/ClientCredentials/ClientCredentialsRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/ClientCredentials/ClientCredentialsRequest.cs
new file mode 100644
index 0000000..9ebbdd1
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/ClientCredentials/ClientCredentialsRequest.cs
@@ -0,0 +1,69 @@
+//-----------------------------------------------------------------------
+// <copyright file="ClientCredentialsRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <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 ClientCredentialsRequest : MessageBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="ClientCredentialsRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ /// <param name="version">The version.</param>
+ internal ClientCredentialsRequest(Uri authorizationServer, Version version)
+ : base(version, MessageTransport.Direct, authorizationServer) {
+ this.HttpMethods = HttpDeliveryMethods.PostRequest;
+ }
+
+ /// <summary>
+ /// Gets or sets the account name.
+ /// </summary>
+ /// <value>The name on the account.</value>
+ [MessagePart(Protocol.wrap_name, IsRequired = true, AllowEmpty = false)]
+ internal string Name { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user's password.
+ /// </summary>
+ /// <value>The password.</value>
+ [MessagePart(Protocol.wrap_password, IsRequired = true, AllowEmpty = false)]
+ internal string Password { get; set; }
+
+ /// <summary>
+ /// Gets or sets an optional authorization scope as defined by the Authorization Server.
+ /// </summary>
+ [MessagePart(Protocol.scope, IsRequired = false, AllowEmpty = true)]
+ internal string Scope { get; 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(this.Recipient.IsTransportSecure(), OAuthWrapStrings.HttpsRequired);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppAccessTokenFailedResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppAccessTokenFailedResponse.cs
new file mode 100644
index 0000000..be4f001
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppAccessTokenFailedResponse.cs
@@ -0,0 +1,21 @@
+//-----------------------------------------------------------------------
+// <copyright file="RichAppAccessTokenFailedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ /// <summary>
+ /// A response from the Authorization Server to the Client in the event
+ /// that an access token could not be granted.
+ /// </summary>
+ internal class RichAppAccessTokenFailedResponse : UnauthorizedResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RichAppAccessTokenFailedResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal RichAppAccessTokenFailedResponse(RichAppAccessTokenRequest request)
+ : base(request) {
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppAccessTokenRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppAccessTokenRequest.cs
new file mode 100644
index 0000000..015ef54
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppAccessTokenRequest.cs
@@ -0,0 +1,61 @@
+//-----------------------------------------------------------------------
+// <copyright file="RichAppAccessTokenRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A message from the Client to the Authorization Server exchanging a
+ /// verification code for refresh and access tokens.
+ /// </summary>
+ internal class RichAppAccessTokenRequest : MessageBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RichAppAccessTokenRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ /// <param name="version">The version.</param>
+ internal RichAppAccessTokenRequest(Uri authorizationServer, Version version)
+ : base(version, MessageTransport.Direct, authorizationServer) {
+ this.HttpMethods = HttpDeliveryMethods.PostRequest;
+ }
+
+ /// <summary>
+ /// Gets or sets the identifier by which this client is known to the Authorization Server.
+ /// </summary>
+ /// <value>The client identifier.</value>
+ [MessagePart(Protocol.client_id, IsRequired = true, AllowEmpty = false)]
+ internal string ClientIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets or sets the verification code previously communicated to the Client
+ /// in <see cref="RichAppResponse.VerificationCode"/>.
+ /// </summary>
+ /// <value>The verification code.</value>
+ [MessagePart(Protocol.code, IsRequired = true, AllowEmpty = false)]
+ internal string VerificationCode { get; 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(this.Recipient.IsTransportSecure(), OAuthWrapStrings.HttpsRequired);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppAccessTokenSuccessResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppAccessTokenSuccessResponse.cs
new file mode 100644
index 0000000..17979e4
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppAccessTokenSuccessResponse.cs
@@ -0,0 +1,45 @@
+//-----------------------------------------------------------------------
+// <copyright file="RichAppAccessTokenSuccessResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// The direct response message that contains the access token from the Authorization Server
+ /// to the Client.
+ /// </summary>
+ internal class RichAppAccessTokenSuccessResponse : MessageBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RichAppAccessTokenSuccessResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal RichAppAccessTokenSuccessResponse(RichAppAccessTokenRequest request)
+ : base(request) {
+ }
+
+ /// <summary>
+ /// Gets or sets the refresh token.
+ /// </summary>
+ /// <value>The token.</value>
+ [MessagePart(Protocol.refresh_token, IsRequired = true, AllowEmpty = false)]
+ internal string RefreshToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The token.</value>
+ [MessagePart(Protocol.access_token, IsRequired = true, AllowEmpty = false)]
+ internal string AccessToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the lifetime of the access token.
+ /// </summary>
+ /// <value>The lifetime.</value>
+ [MessagePart(Protocol.expires_in, IsRequired = false, AllowEmpty = false, Encoder = typeof(TimespanSecondsEncoder))]
+ internal TimeSpan? Lifetime { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppRequest.cs
new file mode 100644
index 0000000..b392c52
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppRequest.cs
@@ -0,0 +1,46 @@
+//-----------------------------------------------------------------------
+// <copyright file="RichAppRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A request from a rich app Client to an Authorization Server requested
+ /// authorization to access user Protected Data.
+ /// </summary>
+ internal class RichAppRequest : MessageBase {
+ [MessagePart(Protocol.type, IsRequired = true)]
+ private const string MessageType = "device_code";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RichAppRequest"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The authorization server.</param>
+ /// <param name="version">The version.</param>
+ internal RichAppRequest(Uri tokenEndpoint, Version version)
+ : base(version, MessageTransport.Direct, tokenEndpoint) {
+ this.HttpMethods = HttpDeliveryMethods.GetRequest;
+ }
+
+ /// <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)]
+ internal string ClientIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets or sets the scope.
+ /// </summary>
+ /// <value>The Authorization Server MAY define authorization scope values for the Client to include.</value>
+ [MessagePart(Protocol.scope, IsRequired = false, AllowEmpty = true)]
+ internal string Scope { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppResponse.cs
new file mode 100644
index 0000000..4a93a45
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/Device/RichAppResponse.cs
@@ -0,0 +1,73 @@
+//-----------------------------------------------------------------------
+// <copyright file="RichAppResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// An indirect response from the Authorization Server to the rich app Client
+ /// with the verification code.
+ /// </summary>
+ internal class RichAppResponse : MessageBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RichAppResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal RichAppResponse(RichAppRequest request)
+ : base(request) {
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code.
+ /// </summary>
+ /// <value>
+ /// The long-lived credential assigned by the Authorization Server to this Client for
+ /// use in accessing the authorizing user's protected resources.
+ /// </value>
+ [MessagePart(Protocol.code, IsRequired = true, AllowEmpty = false)]
+ internal string VerificationCode { get; set; }
+
+ /// <summary>
+ /// Gets or sets the code the user must enter on the authorization page.
+ /// </summary>
+ /// <value>The user code.</value>
+ [MessagePart(Protocol.user_code, IsRequired = true, AllowEmpty = false)]
+ internal string UserCode { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user authorization URI on the authorization server.
+ /// </summary>
+ [MessagePart(Protocol.user_uri, IsRequired = true)]
+ internal Uri AuthorizationUri { get; set; }
+
+ /// <summary>
+ /// Gets or sets the lifetime.
+ /// </summary>
+ /// <value>The lifetime.</value>
+ [MessagePart(Protocol.expires_in, IsRequired = false, Encoder = typeof(TimespanSecondsEncoder))]
+ internal TimeSpan? Lifetime { get; set; }
+
+ /// <summary>
+ /// Gets or sets the minimum amount of time that the client SHOULD wait between polling requests to the token endpoint.
+ /// </summary>
+ [MessagePart(Protocol.interval, IsRequired = false, Encoder = typeof(TimespanSecondsEncoder))]
+ internal TimeSpan? PollingInterval { get; set; }
+
+ /// <summary>
+ /// Gets a value indicating whether the user granted the authorization request.
+ /// </summary>
+ /// <value>
+ /// <c>true</c> if authorization is granted; otherwise, <c>false</c>.
+ /// </value>
+ internal bool IsGranted {
+ get { return !string.IsNullOrEmpty(this.VerificationCode) && this.VerificationCode != Protocol.user_denied; }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/IMessageWithClientState.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/IMessageWithClientState.cs
new file mode 100644
index 0000000..8054d27
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/IMessageWithClientState.cs
@@ -0,0 +1,13 @@
+//-----------------------------------------------------------------------
+// <copyright file="IMessageWithClientState.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using DotNetOpenAuth.Messaging;
+
+ internal interface IMessageWithClientState : IProtocolMessage {
+ string ClientState { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/MessageBase.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/MessageBase.cs
new file mode 100644
index 0000000..9986d19
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/MessageBase.cs
@@ -0,0 +1,205 @@
+//-----------------------------------------------------------------------
+// <copyright file="MessageBase.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A common message base class for OAuth WRAP messages.
+ /// </summary>
+ 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;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="MessageBase"/> class.
+ /// </summary>
+ /// <param name="request">The originating request.</param>
+ protected MessageBase(IDirectedProtocolMessage request) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ this.originatingRequest = request;
+ this.messageTransport = MessageTransport.Direct;
+ this.version = request.Version;
+ }
+
+ /// <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/OAuthWrap/Messages/RefreshAccessTokenRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/RefreshAccessTokenRequest.cs
new file mode 100644
index 0000000..b895f20
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/RefreshAccessTokenRequest.cs
@@ -0,0 +1,62 @@
+//-----------------------------------------------------------------------
+// <copyright file="RefreshAccessTokenRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using DotNetOpenAuth.Messaging;
+
+ /// <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 RefreshAccessTokenRequest : MessageBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="RefreshAccessTokenRequest"/> class.
+ /// </summary>
+ /// <param name="tokenEndpoint">The token endpoint.</param>
+ /// <param name="version">The version.</param>
+ internal RefreshAccessTokenRequest(Uri tokenEndpoint, Version version)
+ : base(version, MessageTransport.Direct, tokenEndpoint) {
+ }
+
+ /// <summary>
+ /// Gets or sets the identifier by which this client is known to the Authorization Server.
+ /// </summary>
+ /// <value>The client identifier.</value>
+ [MessagePart(Protocol.client_id, IsRequired = true, AllowEmpty = false)]
+ internal string ClientIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets or sets the client secret.
+ /// </summary>
+ /// <value>The client secret.</value>
+ /// <remarks>
+ /// REQUIRED if the client identifier has a matching secret. The client secret as described in Section 3.4 (Client Credentials).
+ /// </remarks>
+ [MessagePart(Protocol.client_secret, IsRequired = false, AllowEmpty = true)]
+ internal string ClientSecret { 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; }
+
+ /// <summary>
+ /// Gets or sets the type of the secret.
+ /// </summary>
+ /// <value>The type of the secret.</value>
+ /// <remarks>
+ /// OPTIONAL. The access token secret type as described by Section 5.3 (Cryptographic Tokens Requests). If omitted, the authorization server will issue a bearer token (an access token without a matching secret) as described by Section 5.2 (Bearer Token Requests).
+ /// </remarks>
+ [MessagePart(Protocol.secret_type, IsRequired = false, AllowEmpty = false)]
+ internal string SecretType { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UnauthorizedResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UnauthorizedResponse.cs
new file mode 100644
index 0000000..901b6ff
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UnauthorizedResponse.cs
@@ -0,0 +1,47 @@
+//-----------------------------------------------------------------------
+// <copyright file="UnauthorizedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System.Net;
+ 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="request">The request.</param>
+ internal UnauthorizedResponse(IDirectedProtocolMessage request)
+ : base(request) {
+ }
+
+ #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
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentFailedResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentFailedResponse.cs
new file mode 100644
index 0000000..5547946
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentFailedResponse.cs
@@ -0,0 +1,42 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserAgentFailedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ internal class UserAgentFailedResponse : MessageBase {
+ /// <summary>
+ /// A constant parameter that indicates the user refused to grant the requested authorization.
+ /// </summary>
+ [MessagePart(Protocol.error, IsRequired = true)]
+ private const string ErrorReason = Protocol.user_denied;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserAgentFailedResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The client callback.</param>
+ /// <param name="version">The version.</param>
+ internal UserAgentFailedResponse(Uri clientCallback, Version version)
+ : base(version, MessageTransport.Indirect, clientCallback) {
+ }
+
+ /// <summary>
+ /// Gets or sets the state of the client that was supplied to the Authorization Server.
+ /// </summary>
+ /// <value>
+ /// An opaque value that Clients can use to maintain state associated with the authorization request.
+ /// </value>
+ /// <remarks>
+ /// If this value is present, the Authorization Server MUST return it to the Client's callback URL.
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false, AllowEmpty = true)]
+ public string ClientState { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentRequest.cs
new file mode 100644
index 0000000..4aa1021
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentRequest.cs
@@ -0,0 +1,91 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserAgentRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ internal class UserAgentRequest : MessageBase {
+ /// <summary>
+ /// The type of message.
+ /// </summary>
+ [MessagePart(Protocol.type, IsRequired = true)]
+ private const string Type = "user_agent";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserAgentRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationEndpoint">The authorization endpoint.</param>
+ /// <param name="version">The version.</param>
+ internal UserAgentRequest(Uri authorizationEndpoint, Version version)
+ : base(version, MessageTransport.Indirect, authorizationEndpoint) {
+ }
+
+ /// <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 identifier by which this client is known to the Authorization Server.
+ /// </summary>
+ [MessagePart(Protocol.client_id, IsRequired = true, AllowEmpty = false)]
+ internal 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)]
+ internal Uri Callback { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the authorization server is
+ /// required to redirect the browser back to the client immediately.
+ /// </summary>
+ /// <remarks>
+ /// OPTIONAL. The parameter value must be set to true or false. If set to true, the authorization server MUST NOT prompt the end-user to authenticate or approve access. Instead, the authorization server attempts to establish the end-user's identity via other means (e.g. browser cookies) and checks if the end-user has previously approved an identical access request by the same client and if that access grant is still active. If the authorization server does not support an immediate check or if it is unable to establish the end-user's identity or approval status, it MUST deny the request without prompting the end-user. Defaults to false if omitted.
+ /// </remarks>
+ [MessagePart(Protocol.immediate, IsRequired = false, AllowEmpty = false)]
+ internal bool? Immediate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the scope.
+ /// </summary>
+ /// <value>The scope.</value>
+ /// <remarks>
+ /// OPTIONAL. 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 additional access range to the requested scope.
+ /// </remarks>
+ [MessagePart(Protocol.scope, IsRequired = false, AllowEmpty = true)]
+ internal string Scope { get; set; }
+
+ /// <summary>
+ /// Gets or sets the type of the secret.
+ /// </summary>
+ /// <value>The type of the secret.</value>
+ /// <remarks>
+ /// OPTIONAL. The access token secret type as described by Section 5.3 (Cryptographic Tokens Requests). If omitted, the authorization server will issue a bearer token (an access token without a matching secret) as described by Section 5.2 (Bearer Token Requests).
+ /// </remarks>
+ [MessagePart(Protocol.secret_type, IsRequired = false, AllowEmpty = false)]
+ internal string SecretType { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentSuccessResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentSuccessResponse.cs
new file mode 100644
index 0000000..9b55647
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UserAgent/UserAgentSuccessResponse.cs
@@ -0,0 +1,65 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserAgentSuccessResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ internal class UserAgentSuccessResponse : MessageBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserAgentSuccessResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The client callback.</param>
+ /// <param name="version">The version.</param>
+ internal UserAgentSuccessResponse(Uri clientCallback, Version version)
+ : base(version, MessageTransport.Indirect, clientCallback)
+ {
+ }
+
+ [MessagePart(Protocol.access_token, IsRequired = true, AllowEmpty = false)]
+ internal string AccessToken { get; 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))]
+ internal TimeSpan? Lifetime { get; 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)]
+ internal string RefreshToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token secret.
+ /// </summary>
+ /// <value>The access token secret.</value>
+ /// <remarks>
+ /// REQUIRED if requested by the client. The corresponding access token secret as requested by the client.
+ /// </remarks>
+ [MessagePart(Protocol.access_token_secret, IsRequired = false, AllowEmpty = false)]
+ internal string AccessTokenSecret { get; set; }
+
+ /// <summary>
+ /// Gets or sets the state.
+ /// </summary>
+ /// <value>The state.</value>
+ /// <remarks>
+ /// REQUIRED if the state parameter was present in the client authorization request. Set to the exact value received from the client.
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false, AllowEmpty = true)]
+ internal string ClientState { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordCaptchaResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordCaptchaResponse.cs
new file mode 100644
index 0000000..192af58
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordCaptchaResponse.cs
@@ -0,0 +1,54 @@
+//-----------------------------------------------------------------------
+// <copyright file="UsernamePasswordCaptchaResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Net;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A response from the Authorization Server indicating the Client must have the user
+ /// complete a CAPTCHA puzzle prior to authorization.
+ /// </summary>
+ internal class UsernamePasswordCaptchaResponse : MessageBase, IHttpDirectResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UsernamePasswordCaptchaResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal UsernamePasswordCaptchaResponse(UserNamePasswordRequest request)
+ : base(request) {
+ }
+
+ #region IHttpDirectResponse Members
+
+ /// <summary>
+ /// Gets the HTTP status code that the direct response should be sent with.
+ /// </summary>
+ HttpStatusCode IHttpDirectResponse.HttpStatusCode {
+ 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>
+ /// Gets or sets the URL to the CAPTCHA puzzle.
+ /// </summary>
+ /// <value>The captcha URL.</value>
+ [MessagePart(Protocol.wrap_captcha_url, IsRequired = true, AllowEmpty = false)]
+ internal Uri CaptchaPuzzle { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordFailedResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordFailedResponse.cs
new file mode 100644
index 0000000..fa98b83
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordFailedResponse.cs
@@ -0,0 +1,22 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserNamePasswordFailedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ /// <summary>
+ /// A response from the Authorization Server to the Consumer to indicate that a
+ /// request for a delegation code failed, probably due to an invalid
+ /// username and password.
+ /// </summary>
+ internal class UserNamePasswordFailedResponse : UnauthorizedResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserNamePasswordFailedResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal UserNamePasswordFailedResponse(UserNamePasswordRequest request)
+ : base(request) {
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordRequest.cs
new file mode 100644
index 0000000..7ce570a
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordRequest.cs
@@ -0,0 +1,93 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserNamePasswordRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A request for a delegation code in exchnage for a user's confidential
+ /// username and password.
+ /// </summary>
+ /// <remarks>
+ /// After this request has been sent, the consumer application MUST discard
+ /// the confidential user credentials and use the delegation code going forward.
+ /// </remarks>
+ internal class UserNamePasswordRequest : MessageBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserNamePasswordRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ /// <param name="version">The version.</param>
+ internal UserNamePasswordRequest(Uri authorizationServer, Version version)
+ : base(version, MessageTransport.Direct, authorizationServer) {
+ this.HttpMethods = HttpDeliveryMethods.PostRequest;
+ }
+
+ /// <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)]
+ internal string ClientIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets or sets the user's account username.
+ /// </summary>
+ /// <value>The username on the user's account.</value>
+ [MessagePart(Protocol.wrap_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.wrap_password, IsRequired = true, AllowEmpty = false)]
+ internal string Password { get; set; }
+
+ /// <summary>
+ /// Gets or sets the CAPTCHA puzzle that the user just solved, if applicable.
+ /// </summary>
+ /// <value>The captcha puzzle location.</value>
+ [MessagePart(Protocol.wrap_captcha_url, IsRequired = false, AllowEmpty = false)]
+ internal Uri CaptchaPuzzle { get; set; }
+
+ /// <summary>
+ /// Gets or sets the solution to the CAPTCHA puzzle the user just solved, if applicable.
+ /// </summary>
+ /// <value>The CAPTCHA solution.</value>
+ [MessagePart(Protocol.wrap_captcha_solution, IsRequired = false, AllowEmpty = false)]
+ internal string CaptchaSolution { get; set; }
+
+ /// <summary>
+ /// Gets or sets the scope.
+ /// </summary>
+ /// <value>The scope.</value>
+ [MessagePart(Protocol.scope, IsRequired = false, AllowEmpty = true)]
+ internal string Scope { get; 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(this.Recipient.IsTransportSecure(), OAuthWrapStrings.HttpsRequired);
+ ErrorUtilities.VerifyProtocol((this.CaptchaPuzzle == null) == (this.CaptchaSolution == null), "CAPTCHA puzzle and solution must either be both absent or both present.");
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordSuccessResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordSuccessResponse.cs
new file mode 100644
index 0000000..db3a7d2
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordSuccessResponse.cs
@@ -0,0 +1,51 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserNamePasswordSuccessResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A response from the Authorization Server to the Client containing a refresh token
+ /// and an access token.
+ /// </summary>
+ internal class UserNamePasswordSuccessResponse : MessageBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserNamePasswordSuccessResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal UserNamePasswordSuccessResponse(UserNamePasswordRequest request)
+ : base(request) {
+ }
+
+ /// <summary>
+ /// Gets or sets the verification code.
+ /// </summary>
+ /// <value>
+ /// The long-lived credential assigned by the Authorization Server to this Client for
+ /// use in accessing the authorizing user's protected resources.
+ /// </value>
+ [MessagePart(Protocol.refresh_token, IsRequired = true, AllowEmpty = false)]
+ internal string RefreshToken { get; set; }
+
+ /// <summary>
+ /// Gets or sets the access token.
+ /// </summary>
+ /// <value>The access token.</value>
+ [MessagePart(Protocol.access_token, IsRequired = true, AllowEmpty = false)]
+ internal string AccessToken { get; 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))]
+ internal TimeSpan? Lifetime { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordVerificationResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordVerificationResponse.cs
new file mode 100644
index 0000000..9b4602c
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/UsernameAndPassword/UserNamePasswordVerificationResponse.cs
@@ -0,0 +1,55 @@
+//-----------------------------------------------------------------------
+// <copyright file="UserNamePasswordVerificationResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Net;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// A response from the Authorization Server to the client indicating that the user
+ /// must visit a URL to complete an additional verification step before proceeding.
+ /// </summary>
+ internal class UserNamePasswordVerificationResponse : MessageBase, IHttpDirectResponse {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="UserNamePasswordVerificationResponse"/> class.
+ /// </summary>
+ /// <param name="request">The request.</param>
+ internal UserNamePasswordVerificationResponse(UserNamePasswordRequest request)
+ : base(request) {
+ }
+
+ #region IHttpDirectResponse Members
+
+ /// <summary>
+ /// Gets the HTTP status code that the direct response should be sent with.
+ /// </summary>
+ /// <value><see cref="HttpStatusCode.BadRequest"/></value>
+ HttpStatusCode IHttpDirectResponse.HttpStatusCode {
+ get { return HttpStatusCode.BadRequest; }
+ }
+
+ /// <summary>
+ /// Gets the HTTP headers to add to the response.
+ /// </summary>
+ WebHeaderCollection IHttpDirectResponse.Headers {
+ get { return new WebHeaderCollection(); }
+ }
+
+ #endregion
+
+ /// <summary>
+ /// Gets or sets the verification URL the user must visit with a browser
+ /// to complete some step to defeat automated attacks.
+ /// </summary>
+ /// <value>The verification URL.</value>
+ [MessagePart(Protocol.wrap_verification_url, IsRequired = true, AllowEmpty = false)]
+ internal Uri VerificationUrl { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppAccessTokenRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppAccessTokenRequest.cs
new file mode 100644
index 0000000..de3ef40
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppAccessTokenRequest.cs
@@ -0,0 +1,109 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebAppAccessTokenRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap.ChannelElements;
+
+ /// <summary>
+ /// A message sent by the Client directly to the Authorization Server to exchange
+ /// the verification code for an Access Token.
+ /// </summary>
+ /// <remarks>
+ /// Used by the Web App (and Rich App?) profiles.
+ /// </remarks>
+ internal class WebAppAccessTokenRequest : MessageBase {
+ /// <summary>
+ /// The type of message.
+ /// </summary>
+ [MessagePart(Protocol.type, IsRequired = true)]
+ private const string Type = "web_server";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebAppAccessTokenRequest"/> class.
+ /// </summary>
+ /// <param name="accessTokenEndpoint">The Authorization Server's access token endpoint URL.</param>
+ /// <param name="version">The version.</param>
+ internal WebAppAccessTokenRequest(Uri accessTokenEndpoint, Version version)
+ : base(version, MessageTransport.Direct, accessTokenEndpoint) {
+ this.HttpMethods = HttpDeliveryMethods.PostRequest;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebAppAccessTokenRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ internal WebAppAccessTokenRequest(AuthorizationServerDescription authorizationServer)
+ : this(authorizationServer.TokenEndpoint, authorizationServer.Version) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ Contract.Requires<ArgumentException>(authorizationServer.Version != null);
+ Contract.Requires<ArgumentException>(authorizationServer.TokenEndpoint != null);
+ }
+
+ /// <summary>
+ /// Gets or sets the identifier by which this client is known to the Authorization Server.
+ /// </summary>
+ /// <value>The client identifier.</value>
+ [MessagePart(Protocol.client_id, IsRequired = true, AllowEmpty = false)]
+ internal string ClientIdentifier { get; set; }
+
+ /// <summary>
+ /// Gets or sets the client secret.
+ /// </summary>
+ /// <value>The client secret.</value>
+ /// <remarks>
+ /// REQUIRED if the client identifier has a matching secret. The client secret as described in Section 3.4 (Client Credentials).
+ /// </remarks>
+ [MessagePart(Protocol.client_secret, IsRequired = false, AllowEmpty = true)]
+ internal string ClientSecret { get; set; }
+
+ /// <summary>
+ /// Gets or sets the verification code previously communicated to the Client
+ /// in <see cref="WebAppSuccessResponse.VerificationCode"/>.
+ /// </summary>
+ /// <value>The verification code received from the authorization server.</value>
+ [MessagePart(Protocol.code, IsRequired = true, AllowEmpty = false)]
+ internal string VerificationCode { get; set; }
+
+ /// <summary>
+ /// Gets or sets the callback URL used in <see cref="WebAppRequest.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; }
+
+ /// <summary>
+ /// Gets or sets the type of the secret.
+ /// </summary>
+ /// <value>The type of the secret.</value>
+ /// <remarks>
+ /// OPTIONAL. The access token secret type as described by Section 5.3 (Cryptographic Tokens Requests). If omitted, the authorization server will issue a bearer token (an access token without a matching secret) as described by Section 5.2 (Bearer Token Requests).
+ /// </remarks>
+ [MessagePart(Protocol.secret_type, IsRequired = false, AllowEmpty = false)]
+ internal string SecretType { get; 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(this.Recipient.IsTransportSecure(), OAuthWrapStrings.HttpsRequired);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppFailedResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppFailedResponse.cs
new file mode 100644
index 0000000..be00f52
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppFailedResponse.cs
@@ -0,0 +1,47 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebAppFailedResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Messaging;
+
+ /// <summary>
+ /// The message the Authorization Server MAY use to send the user back to the Client
+ /// following the user's denial to grant Consumer with authorization of
+ /// access to requested resources.
+ /// </summary>
+ internal class WebAppFailedResponse : MessageBase, IMessageWithClientState {
+ /// <summary>
+ /// A constant parameter that indicates the user refused to grant the requested authorization.
+ /// </summary>
+ [MessagePart(Protocol.error, IsRequired = true)]
+ private const string ErrorReason = Protocol.user_denied;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebAppFailedResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The recipient of the message.</param>
+ /// <param name="version">The version.</param>
+ internal WebAppFailedResponse(Uri clientCallback, Version version) :
+ base(version, MessageTransport.Indirect, clientCallback) {
+ Contract.Requires<ArgumentNullException>(version != null);
+ Contract.Requires<ArgumentNullException>(clientCallback != null);
+ }
+
+ /// <summary>
+ /// Gets or sets the state of the client that was supplied to the Authorization Server.
+ /// </summary>
+ /// <value>
+ /// An opaque value that Clients can use to maintain state associated with the authorization request.
+ /// </value>
+ /// <remarks>
+ /// If this value is present, the Authorization Server MUST return it to the Client's callback URL.
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false, AllowEmpty = true)]
+ public string ClientState { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppRequest.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppRequest.cs
new file mode 100644
index 0000000..790d229
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppRequest.cs
@@ -0,0 +1,89 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebAppRequest.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap.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>
+ public class WebAppRequest : MessageBase, IMessageWithClientState {
+ /// <summary>
+ /// The type of message.
+ /// </summary>
+ [MessagePart(Protocol.type, IsRequired = true)]
+ private const string Type = "web_server";
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebAppRequest"/> 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 WebAppRequest(Uri authorizationEndpoint, Version version)
+ : base(version, MessageTransport.Indirect, authorizationEndpoint) {
+ Contract.Requires<ArgumentNullException>(authorizationEndpoint != null);
+ Contract.Requires<ArgumentNullException>(version != null);
+ this.HttpMethods = HttpDeliveryMethods.GetRequest;
+ }
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebAppRequest"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ internal WebAppRequest(AuthorizationServerDescription authorizationServer)
+ : this(authorizationServer.AuthorizationEndpoint, authorizationServer.Version) {
+ Contract.Requires<ArgumentNullException>(authorizationServer != null);
+ Contract.Requires<ArgumentException>(authorizationServer.Version != null);
+ Contract.Requires<ArgumentException>(authorizationServer.AuthorizationEndpoint != null);
+ }
+
+ /// <summary>
+ /// Gets or sets 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 a value indicating whether the authorization server is
+ /// required to redirect the browser back to the client immediately.
+ /// </summary>
+ /// <remarks>
+ /// OPTIONAL. The parameter value must be set to true or false. If set to true, the authorization server MUST NOT prompt the end-user to authenticate or approve access. Instead, the authorization server attempts to establish the end-user's identity via other means (e.g. browser cookies) and checks if the end-user has previously approved an identical access request by the same client and if that access grant is still active. If the authorization server does not support an immediate check or if it is unable to establish the end-user's identity or approval status, it MUST deny the request without prompting the end-user. Defaults to false if omitted.
+ /// </remarks>
+ [MessagePart(Protocol.immediate, IsRequired = false, AllowEmpty = false)]
+ public bool? Immediate { get; set; }
+
+ /// <summary>
+ /// Gets or sets the identifier by which this client is known to the Authorization Server.
+ /// </summary>
+ [MessagePart(Protocol.client_id, IsRequired = true, AllowEmpty = false)]
+ internal 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)]
+ internal Uri Callback { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppSuccessResponse.cs b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppSuccessResponse.cs
new file mode 100644
index 0000000..abc99bb
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Messages/WebServer/WebAppSuccessResponse.cs
@@ -0,0 +1,49 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebAppSuccessResponse.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap.Messages {
+ using System;
+ using System.Diagnostics.Contracts;
+ using DotNetOpenAuth.Messaging;
+
+ /// <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>
+ internal class WebAppSuccessResponse : MessageBase, IMessageWithClientState {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebAppSuccessResponse"/> class.
+ /// </summary>
+ /// <param name="clientCallback">The client callback.</param>
+ /// <param name="version">The protocol version.</param>
+ internal WebAppSuccessResponse(Uri clientCallback, Version version)
+ : base(version, MessageTransport.Indirect, clientCallback) {
+ Contract.Requires<ArgumentNullException>(version != null);
+ Contract.Requires<ArgumentNullException>(clientCallback != null);
+ }
+
+ /// <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="WebAppRequest"/>.
+ /// </remarks>
+ [MessagePart(Protocol.state, IsRequired = false, AllowEmpty = true)]
+ public string ClientState { get; set; }
+
+ /// <summary>
+ /// Gets or sets the verification code.
+ /// </summary>
+ /// <value>
+ /// The long-lived credential assigned by the Authorization Server to this Consumer for
+ /// use in accessing the authorizing user's protected resources.
+ /// </value>
+ [MessagePart(Protocol.code, IsRequired = true, AllowEmpty = true)]
+ internal string VerificationCode { get; set; }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.Designer.cs b/src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.Designer.cs
new file mode 100644
index 0000000..d5836ff
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.Designer.cs
@@ -0,0 +1,99 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// This code was generated by a tool.
+// Runtime Version:4.0.30426.0
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ 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 OAuthWrapStrings {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal OAuthWrapStrings() {
+ }
+
+ /// <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.OAuthWrap.OAuthWrapStrings", typeof(OAuthWrapStrings).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 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);
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.resx b/src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.resx
new file mode 100644
index 0000000..2e70624
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/OAuthWrapStrings.resx
@@ -0,0 +1,132 @@
+<?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="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>
+</root> \ No newline at end of file
diff --git a/src/DotNetOpenAuth/OAuthWrap/Protocol.cs b/src/DotNetOpenAuth/OAuthWrap/Protocol.cs
new file mode 100644
index 0000000..c11c127
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/Protocol.cs
@@ -0,0 +1,223 @@
+// <auto-generated/> // disable StyleCop on this file
+//-----------------------------------------------------------------------
+// <copyright file="Protocol.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+
+ /// <summary>
+ /// An enumeration of the OAuth WRAP protocol versions supported by this library.
+ /// </summary>
+ public enum ProtocolVersion {
+ /// <summary>
+ /// The OAuth 2.0 specification.
+ /// </summary>
+ V20,
+ }
+
+ /// <summary>
+ /// Protocol constants for OAuth WRAP.
+ /// </summary>
+ internal class Protocol {
+ /// <summary>
+ /// The HTTP authorization scheme "WRAP";
+ /// </summary>
+ internal const string HttpAuthorizationScheme = "WRAP";
+
+ /// <summary>
+ /// The format of the HTTP Authorization header value that authorizes OAuth WRAP requests.
+ /// </summary>
+ internal const string HttpAuthorizationHeaderFormat = "Token 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" 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 "wrap_verification_code" string.
+ /// </summary>
+ internal const string code = "code";
+
+ /// <summary>
+ /// The "user_code" string.
+ /// </summary>
+ internal const string user_code = "user_code";
+
+ /// <summary>
+ /// The "user_uri" string.
+ /// </summary>
+ internal const string user_uri = "user_uri";
+
+ /// <summary>
+ /// The "interval" string.
+ /// </summary>
+ internal const string interval = "interval";
+
+ /// <summary>
+ /// The "wrap_verification_url" string.
+ /// </summary>
+ internal const string wrap_verification_url = "wrap_verification_url";
+
+ /// <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 "wrap_username" string.
+ /// </summary>
+ internal const string wrap_username = "wrap_username";
+
+ /// <summary>
+ /// The "wrap_password" string.
+ /// </summary>
+ internal const string wrap_password = "wrap_password";
+
+ /// <summary>
+ /// The "wrap_name" string.
+ /// </summary>
+ internal const string wrap_name = "wrap_name";
+
+ /// <summary>
+ /// The "format" string.
+ /// </summary>
+ internal const string format = "format";
+
+ /// <summary>
+ /// The "assertion" string.
+ /// </summary>
+ internal const string assertion = "assertion";
+
+ /// <summary>
+ /// The "wrap_SAML" string.
+ /// </summary>
+ internal const string wrap_saml = "wrap_SAML";
+
+ /// <summary>
+ /// The "wrap_SWT" string.
+ /// </summary>
+ internal const string wrap_swt = "wrap_SWT";
+
+ /// <summary>
+ /// The "wrap_captcha_url" string.
+ /// </summary>
+ internal const string wrap_captcha_url = "wrap_captcha_url";
+
+ /// <summary>
+ /// The "wrap_captcha_solution" string.
+ /// </summary>
+ internal const string wrap_captcha_solution = "wrap_captcha_solution";
+
+ /// <summary>
+ /// The "user_denied" string.
+ /// </summary>
+ internal const string user_denied = "user_denied";
+
+ /// <summary>
+ /// The "secret_type" string.
+ /// </summary>
+ internal const string secret_type = "secret_type";
+
+ /// <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>
+ /// Gets or sets the OAuth WRAP version represented by this instance.
+ /// </summary>
+ /// <value>The version.</value>
+ internal Version Version { get; private set; }
+
+ /// <summary>
+ /// Gets or sets the OAuth WRAP 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");
+ }
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/WebAppAuthorizationServer.cs b/src/DotNetOpenAuth/OAuthWrap/WebAppAuthorizationServer.cs
new file mode 100644
index 0000000..91ce097
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/WebAppAuthorizationServer.cs
@@ -0,0 +1,106 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebAppAuthorizationServer.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Linq;
+ using System.Text;
+ using DotNetOpenAuth.Messaging;
+ using DotNetOpenAuth.OAuthWrap.Messages;
+
+ public class WebAppAuthorizationServer : AuthorizationServerBase {
+ public WebAppAuthorizationServer(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>
+ /// <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>
+ /// <remarks>
+ /// Requires HttpContext.Current.
+ /// </remarks>
+ public WebAppRequest ReadAuthorizationRequest() {
+ return this.ReadAuthorizationRequest(this.Channel.GetRequestFromContext());
+ }
+
+ /// <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 WebAppRequest ReadAuthorizationRequest(HttpRequestInfo request) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ WebAppRequest message;
+ this.Channel.TryReadFromRequest(request, out message);
+ return message;
+ }
+
+ public OutgoingWebResponse ApproveAuthorizationRequest(WebAppRequest authorizationRequest) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+ Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
+
+ return ApproveAuthorizationRequest(authorizationRequest, this.GetCallback(authorizationRequest));
+ }
+
+ public OutgoingWebResponse ApproveAuthorizationRequest(WebAppRequest authorizationRequest, Uri callback) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+ Contract.Requires<ArgumentNullException>(callback != null, "callback");
+ Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
+
+ var client = GetClient(authorizationRequest.ClientIdentifier);
+ var response = new WebAppSuccessResponse(callback, ((IMessage)authorizationRequest).Version) {
+ ClientState = authorizationRequest.ClientState,
+ VerificationCode = OAuth.ServiceProvider.CreateVerificationCode(client.VerificationCodeFormat, client.VerificationCodeLength),
+ };
+
+ return this.Channel.PrepareResponse(response);
+ }
+
+ public OutgoingWebResponse RejectAuthorizationRequest(WebAppRequest authorizationRequest) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+ Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
+
+ return this.RejectAuthorizationRequest(authorizationRequest, GetCallback(authorizationRequest));
+ }
+
+ public OutgoingWebResponse RejectAuthorizationRequest(WebAppRequest authorizationRequest, Uri callback) {
+ Contract.Requires<ArgumentNullException>(authorizationRequest != null, "authorizationRequest");
+ Contract.Requires<ArgumentNullException>(callback != null, "callback");
+ Contract.Ensures(Contract.Result<OutgoingWebResponse>() != null);
+
+ var response = new WebAppFailedResponse(callback, ((IMessage)authorizationRequest).Version) {
+ ClientState = authorizationRequest.ClientState,
+ };
+
+ return this.Channel.PrepareResponse(response);
+ }
+
+ protected Uri GetCallback(WebAppRequest 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(OAuthWrapStrings.NoCallback);
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/WebAppClient.cs b/src/DotNetOpenAuth/OAuthWrap/WebAppClient.cs
new file mode 100644
index 0000000..8df71b9
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/WebAppClient.cs
@@ -0,0 +1,116 @@
+//-----------------------------------------------------------------------
+// <copyright file="WebAppClient.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ 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.OAuthWrap.Messages;
+
+ /// <summary>
+ /// An OAuth WRAP consumer designed for web applications.
+ /// </summary>
+ public class WebAppClient : ClientBase {
+ /// <summary>
+ /// Initializes a new instance of the <see cref="WebAppClient"/> class.
+ /// </summary>
+ /// <param name="authorizationServer">The authorization server.</param>
+ public WebAppClient(AuthorizationServerDescription authorizationServer)
+ : base(authorizationServer) {
+ }
+
+ /// <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; }
+
+ public IClientTokenManager TokenManager { get; set; }
+
+ public WebAppRequest PrepareRequestUserAuthorization() {
+ return this.PrepareRequestUserAuthorization(new AuthorizationState());
+ }
+
+ public WebAppRequest 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<WebAppRequest>() != null);
+ Contract.Ensures(Contract.Result<WebAppRequest>().ClientIdentifier == this.ClientIdentifier);
+ Contract.Ensures(Contract.Result<WebAppRequest>().Callback == authorization.Callback);
+
+ if (authorization.Callback == null) {
+ authorization.Callback = this.Channel.GetRequestFromContext().UrlBeforeRewriting;
+ authorization.SaveChanges();
+ }
+
+ var request = new WebAppRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ Callback = authorization.Callback,
+ };
+
+ return request;
+ }
+
+ public IAuthorizationState ProcessUserAuthorization() {
+ Contract.Requires<InvalidOperationException>(HttpContext.Current != null && HttpContext.Current.Request != null, MessagingStrings.HttpContextRequired);
+ return this.ProcessUserAuthorization(this.Channel.GetRequestFromContext());
+ }
+
+ public IAuthorizationState ProcessUserAuthorization(HttpRequestInfo request) {
+ Contract.Requires<ArgumentNullException>(request != null);
+ Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientIdentifier));
+ Contract.Requires<InvalidOperationException>(!string.IsNullOrEmpty(this.ClientSecret));
+
+ IMessageWithClientState response;
+ if (this.Channel.TryReadFromRequest<IMessageWithClientState>(request, out response)) {
+ Uri callback = MessagingUtilities.StripMessagePartsFromQueryString(request.UrlBeforeRewriting, this.Channel.MessageDescriptions.Get(response));
+ IAuthorizationState authorizationState = this.TokenManager.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.");
+ var success = response as WebAppSuccessResponse;
+ var failure = response as WebAppFailedResponse;
+ ErrorUtilities.VerifyProtocol(success != null || failure != null, MessagingStrings.UnexpectedMessageReceivedOfMany);
+ if (success != null) {
+ var accessTokenRequest = new WebAppAccessTokenRequest(this.AuthorizationServer) {
+ ClientIdentifier = this.ClientIdentifier,
+ ClientSecret = this.ClientSecret,
+ Callback = authorizationState.Callback,
+ VerificationCode = success.VerificationCode,
+ };
+ IProtocolMessage accessTokenResponse = this.Channel.Request(accessTokenRequest);
+ var accessTokenSuccess = accessTokenResponse as AccessTokenSuccessResponse;
+ var failedAccessTokenResponse = accessTokenResponse as AccessTokenFailedResponse;
+ if (accessTokenSuccess != null) {
+ authorizationState.AccessToken = accessTokenSuccess.AccessToken;
+ authorizationState.AccessTokenSecret = accessTokenSuccess.AccessTokenSecret;
+ authorizationState.RefreshToken = accessTokenSuccess.RefreshToken;
+ authorizationState.AccessTokenExpirationUtc = DateTime.UtcNow + accessTokenSuccess.Lifetime;
+ authorizationState.SaveChanges();
+ } else {
+ authorizationState.Delete();
+ ErrorUtilities.ThrowProtocol(OAuthWrapStrings.CannotObtainAccessTokenWithReason, failedAccessTokenResponse.Error);
+ }
+ } else { // failure
+ Logger.Wrap.Info("User refused to grant the requested authorization at the Authorization Server.");
+ authorizationState.Delete();
+ }
+
+ return authorizationState;
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/DotNetOpenAuth/OAuthWrap/WrapUtilities.cs b/src/DotNetOpenAuth/OAuthWrap/WrapUtilities.cs
new file mode 100644
index 0000000..7e04f3f
--- /dev/null
+++ b/src/DotNetOpenAuth/OAuthWrap/WrapUtilities.cs
@@ -0,0 +1,34 @@
+//-----------------------------------------------------------------------
+// <copyright file="WrapUtilities.cs" company="Andrew Arnott">
+// Copyright (c) Andrew Arnott. All rights reserved.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace DotNetOpenAuth.OAuthWrap {
+ using System;
+ using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
+ using System.Globalization;
+ using System.Linq;
+ using System.Net;
+ using System.Text;
+
+ /// <summary>
+ /// Some common utility methods for OAuth WRAP.
+ /// </summary>
+ internal static class WrapUtilities {
+ /// <summary>
+ /// Authorizes an HTTP request using an OAuth WRAP 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));
+ request.Headers[HttpRequestHeader.Authorization] = string.Format(
+ CultureInfo.InvariantCulture,
+ Protocol.HttpAuthorizationHeaderFormat,
+ accessToken);
+ }
+ }
+}
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 f989260..1545d96 100644
--- a/src/version.txt
+++ b/src/version.txt
@@ -1 +1 @@
-3.4.4
+3.5.0