diff options
Diffstat (limited to 'src/DotNetOpenAuth.Test/OAuth')
8 files changed, 170 insertions, 209 deletions
diff --git a/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs b/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs index a295732..c7b2bfa 100644 --- a/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs +++ b/src/DotNetOpenAuth.Test/OAuth/AppendixScenarios.cs @@ -8,6 +8,9 @@ namespace DotNetOpenAuth.Test.OAuth { using System; using System.IO; using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Threading.Tasks; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.ChannelElements; @@ -17,50 +20,76 @@ namespace DotNetOpenAuth.Test.OAuth { [TestFixture] public class AppendixScenarios : TestBase { [Test] - public void SpecAppendixAExample() { - ServiceProviderDescription serviceDescription = new ServiceProviderDescription() { - RequestTokenEndpoint = new MessageReceivingEndpoint("https://photos.example.net/request_token", HttpDeliveryMethods.PostRequest), - UserAuthorizationEndpoint = new MessageReceivingEndpoint("http://photos.example.net/authorize", HttpDeliveryMethods.GetRequest), - AccessTokenEndpoint = new MessageReceivingEndpoint("https://photos.example.net/access_token", HttpDeliveryMethods.PostRequest), - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { - new PlaintextSigningBindingElement(), - new HmacSha1SigningBindingElement(), - }, + public async Task SpecAppendixAExample() { + var serviceDescription = new ServiceProviderDescription( + "https://photos.example.net/request_token", + "http://photos.example.net/authorize", + "https://photos.example.net/access_token"); + var serviceHostDescription = new ServiceProviderHostDescription { + RequestTokenEndpoint = new MessageReceivingEndpoint(serviceDescription.TemporaryCredentialsRequestEndpoint, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), + UserAuthorizationEndpoint = new MessageReceivingEndpoint(serviceDescription.ResourceOwnerAuthorizationEndpoint, HttpDeliveryMethods.GetRequest), + AccessTokenEndpoint = new MessageReceivingEndpoint(serviceDescription.TokenRequestEndpoint, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), + TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement(), }, }; - MessageReceivingEndpoint accessPhotoEndpoint = new MessageReceivingEndpoint("http://photos.example.net/photos?file=vacation.jpg&size=original", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest); - ConsumerDescription consumerDescription = new ConsumerDescription("dpf43f3p2l4k3l03", "kd94hf93k423kf44"); + var accessPhotoEndpoint = new Uri("http://photos.example.net/photos?file=vacation.jpg&size=original"); + var consumerDescription = new ConsumerDescription("dpf43f3p2l4k3l03", "kd94hf93k423kf44"); - OAuthCoordinator coordinator = new OAuthCoordinator( - consumerDescription, - serviceDescription, - consumer => { - consumer.Channel.PrepareResponse(consumer.PrepareRequestUserAuthorization(new Uri("http://printer.example.com/request_token_ready"), null, null)); // .Send() dropped because this is just a simulation - string accessToken = consumer.ProcessUserAuthorization().AccessToken; - var photoRequest = consumer.CreateAuthorizingMessage(accessPhotoEndpoint, accessToken); - OutgoingWebResponse protectedPhoto = ((CoordinatingOAuthConsumerChannel)consumer.Channel).RequestProtectedResource(photoRequest); - Assert.IsNotNull(protectedPhoto); - Assert.AreEqual(HttpStatusCode.OK, protectedPhoto.Status); - Assert.AreEqual("image/jpeg", protectedPhoto.Headers[HttpResponseHeader.ContentType]); - Assert.AreNotEqual(0, protectedPhoto.ResponseStream.Length); - }, - sp => { - var requestTokenMessage = sp.ReadTokenRequest(); - sp.Channel.PrepareResponse(sp.PrepareUnauthorizedTokenMessage(requestTokenMessage)); // .Send() dropped because this is just a simulation - var authRequest = sp.ReadAuthorizationRequest(); + var tokenManager = new InMemoryTokenManager(); + tokenManager.AddConsumer(consumerDescription); + var sp = new ServiceProvider(serviceHostDescription, tokenManager); + + Handle(serviceDescription.TemporaryCredentialsRequestEndpoint).By( + async (request, ct) => { + var requestTokenMessage = await sp.ReadTokenRequestAsync(request, ct); + return await sp.Channel.PrepareResponseAsync(sp.PrepareUnauthorizedTokenMessage(requestTokenMessage)); + }); + Handle(serviceDescription.ResourceOwnerAuthorizationEndpoint).By( + async (request, ct) => { + var authRequest = await sp.ReadAuthorizationRequestAsync(request, ct); ((InMemoryTokenManager)sp.TokenManager).AuthorizeRequestToken(authRequest.RequestToken); - sp.Channel.PrepareResponse(sp.PrepareAuthorizationResponse(authRequest)); // .Send() dropped because this is just a simulation - var accessRequest = sp.ReadAccessTokenRequest(); - sp.Channel.PrepareResponse(sp.PrepareAccessTokenMessage(accessRequest)); // .Send() dropped because this is just a simulation - string accessToken = sp.ReadProtectedResourceAuthorization().AccessToken; - ((CoordinatingOAuthServiceProviderChannel)sp.Channel).SendDirectRawResponse(new OutgoingWebResponse { - ResponseStream = new MemoryStream(new byte[] { 0x33, 0x66 }), - Headers = new WebHeaderCollection { - { HttpResponseHeader.ContentType, "image/jpeg" }, - }, - }); + return await sp.Channel.PrepareResponseAsync(sp.PrepareAuthorizationResponse(authRequest)); + }); + Handle(serviceDescription.TokenRequestEndpoint).By( + async (request, ct) => { + var accessRequest = await sp.ReadAccessTokenRequestAsync(request, ct); + return await sp.Channel.PrepareResponseAsync(sp.PrepareAccessTokenMessage(accessRequest), ct); }); + Handle(accessPhotoEndpoint).By( + async (request, ct) => { + string accessToken = (await sp.ReadProtectedResourceAuthorizationAsync(request)).AccessToken; + Assert.That(accessToken, Is.Not.Null.And.Not.Empty); + var responseMessage = new HttpResponseMessage { Content = new ByteArrayContent(new byte[] { 0x33, 0x66 }), }; + responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); + return responseMessage; + }); + + var consumer = new Consumer( + consumerDescription.ConsumerKey, + consumerDescription.ConsumerSecret, + serviceDescription, + new MemoryTemporaryCredentialStorage()); + consumer.HostFactories = this.HostFactories; + var authorizeUrl = await consumer.RequestUserAuthorizationAsync(new Uri("http://printer.example.com/request_token_ready")); + Uri authorizeResponseUri; + this.HostFactories.AllowAutoRedirects = false; + using (var httpClient = this.HostFactories.CreateHttpClient()) { + using (var response = await httpClient.GetAsync(authorizeUrl)) { + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Redirect)); + authorizeResponseUri = response.Headers.Location; + } + } + + var accessTokenResponse = await consumer.ProcessUserAuthorizationAsync(authorizeResponseUri); + Assert.That(accessTokenResponse, Is.Not.Null); - coordinator.Run(); + using (var authorizingClient = consumer.CreateHttpClient(accessTokenResponse.AccessToken)) { + using (var protectedPhoto = await authorizingClient.GetAsync(accessPhotoEndpoint)) { + Assert.That(protectedPhoto, Is.Not.Null); + protectedPhoto.EnsureSuccessStatusCode(); + Assert.That("image/jpeg", Is.EqualTo(protectedPhoto.Content.Headers.ContentType.MediaType)); + Assert.That(protectedPhoto.Content.Headers.ContentLength, Is.Not.EqualTo(0)); + } + } } } } diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs index 49260eb..e436143 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/HmacSha1SigningBindingElementTests.cs @@ -5,6 +5,8 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Test.OAuth.ChannelElements { + using System.Net.Http; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OAuth; @@ -33,7 +35,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { ((ITamperResistantOAuthMessage)message).ConsumerSecret = "ExJXsYl7Or8OfK98"; ((ITamperResistantOAuthMessage)message).TokenSecret = "b197333b-470a-43b3-bcd7-49d6d2229c4c"; var signedMessage = (ITamperResistantOAuthMessage)message; - signedMessage.HttpMethod = "GET"; + signedMessage.HttpMethod = HttpMethod.Get; signedMessage.SignatureMethod = "HMAC-SHA1"; MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(message); dictionary["oauth_timestamp"] = "1353545248"; diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs index b081038..fdf652c 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/OAuthChannelTests.cs @@ -10,7 +10,10 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { using System.Collections.Specialized; using System.IO; using System.Net; + using System.Net.Http; using System.Text; + using System.Threading; + using System.Threading.Tasks; using System.Web; using System.Xml; using DotNetOpenAuth.Messaging; @@ -24,41 +27,32 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { [TestFixture] public class OAuthChannelTests : TestBase { private OAuthChannel channel; - private TestWebRequestHandler webRequestHandler; private SigningBindingElementBase signingElement; private INonceStore nonceStore; private DotNetOpenAuth.OAuth.ServiceProviderSecuritySettings serviceProviderSecuritySettings = DotNetOpenAuth.Configuration.OAuthElement.Configuration.ServiceProvider.SecuritySettings.CreateSecuritySettings(); - private DotNetOpenAuth.OAuth.ConsumerSecuritySettings consumerSecuritySettings = DotNetOpenAuth.Configuration.OAuthElement.Configuration.Consumer.SecuritySettings.CreateSecuritySettings(); [SetUp] public override void SetUp() { base.SetUp(); - this.webRequestHandler = new TestWebRequestHandler(); this.signingElement = new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()); this.nonceStore = new NonceMemoryStore(StandardExpirationBindingElement.MaximumMessageAge); - this.channel = new OAuthServiceProviderChannel(this.signingElement, this.nonceStore, new InMemoryTokenManager(), this.serviceProviderSecuritySettings, new TestMessageFactory()); - this.channel.WebRequestHandler = this.webRequestHandler; + this.channel = new OAuthServiceProviderChannel(this.signingElement, this.nonceStore, new InMemoryTokenManager(), this.serviceProviderSecuritySettings, new TestMessageFactory(), this.HostFactories); } [Test, ExpectedException(typeof(ArgumentException))] public void CtorNullSigner() { - new OAuthConsumerChannel(null, this.nonceStore, new InMemoryTokenManager(), this.consumerSecuritySettings, new TestMessageFactory()); + new OAuthServiceProviderChannel(null, this.nonceStore, new InMemoryTokenManager(), this.serviceProviderSecuritySettings, new TestMessageFactory()); } [Test, ExpectedException(typeof(ArgumentNullException))] public void CtorNullStore() { - new OAuthConsumerChannel(new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()), null, new InMemoryTokenManager(), this.consumerSecuritySettings, new TestMessageFactory()); + new OAuthServiceProviderChannel(new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()), null, new InMemoryTokenManager(), this.serviceProviderSecuritySettings, new TestMessageFactory()); } [Test, ExpectedException(typeof(ArgumentNullException))] public void CtorNullTokenManager() { - new OAuthConsumerChannel(new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()), this.nonceStore, null, this.consumerSecuritySettings, new TestMessageFactory()); - } - - [Test] - public void CtorSimpleConsumer() { - new OAuthConsumerChannel(new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()), this.nonceStore, (IConsumerTokenManager)new InMemoryTokenManager(), this.consumerSecuritySettings); + new OAuthServiceProviderChannel(new RsaSha1ServiceProviderSigningBindingElement(new InMemoryTokenManager()), this.nonceStore, null, this.serviceProviderSecuritySettings, new TestMessageFactory()); } [Test] @@ -67,8 +61,8 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { } [Test] - public void ReadFromRequestAuthorization() { - this.ParameterizedReceiveTest(HttpDeliveryMethods.AuthorizationHeaderRequest); + public async Task ReadFromRequestAuthorization() { + await this.ParameterizedReceiveTestAsync(HttpDeliveryMethods.AuthorizationHeaderRequest); } /// <summary> @@ -76,7 +70,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { /// from the Authorization header, the query string and the entity form data. /// </summary> [Test] - public void ReadFromRequestAuthorizationScattered() { + public async Task ReadFromRequestAuthorizationScattered() { // Start by creating a standard POST HTTP request. var postedFields = new Dictionary<string, string> { { "age", "15" }, @@ -97,7 +91,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { var requestInfo = new HttpRequestInfo("POST", builder.Uri, form: postedFields.ToNameValueCollection(), headers: headers); - IDirectedProtocolMessage requestMessage = this.channel.ReadFromRequest(requestInfo); + IDirectedProtocolMessage requestMessage = await this.channel.ReadFromRequestAsync(requestInfo.AsHttpRequestMessage(), CancellationToken.None); Assert.IsNotNull(requestMessage); Assert.IsInstanceOf<TestMessage>(requestMessage); @@ -108,36 +102,35 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { } [Test] - public void ReadFromRequestForm() { - this.ParameterizedReceiveTest(HttpDeliveryMethods.PostRequest); + public async Task ReadFromRequestForm() { + await this.ParameterizedReceiveTestAsync(HttpDeliveryMethods.PostRequest); } [Test] - public void ReadFromRequestQueryString() { - this.ParameterizedReceiveTest(HttpDeliveryMethods.GetRequest); + public async Task ReadFromRequestQueryString() { + await this.ParameterizedReceiveTestAsync(HttpDeliveryMethods.GetRequest); } [Test] - public void SendDirectMessageResponse() { + public async Task SendDirectMessageResponse() { IProtocolMessage message = new TestDirectedMessage { Age = 15, Name = "Andrew", Location = new Uri("http://hostb/pathB"), }; - OutgoingWebResponse response = this.channel.PrepareResponse(message); - Assert.AreSame(message, response.OriginalMessage); - Assert.AreEqual(HttpStatusCode.OK, response.Status); - Assert.AreEqual(2, response.Headers.Count); + var response = await this.channel.PrepareResponseAsync(message); + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.AreEqual(Channel.HttpFormUrlEncodedContentType.MediaType, response.Content.Headers.ContentType.MediaType); - NameValueCollection body = HttpUtility.ParseQueryString(response.Body); + NameValueCollection body = HttpUtility.ParseQueryString(await response.Content.ReadAsStringAsync()); Assert.AreEqual("15", body["age"]); Assert.AreEqual("Andrew", body["Name"]); Assert.AreEqual("http://hostb/pathB", body["Location"]); } [Test] - public void ReadFromResponse() { + public async Task ReadFromResponse() { var fields = new Dictionary<string, string> { { "age", "15" }, { "Name", "Andrew" }, @@ -150,7 +143,9 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { writer.Write(MessagingUtilities.CreateQueryString(fields)); writer.Flush(); ms.Seek(0, SeekOrigin.Begin); - IDictionary<string, string> deserializedFields = this.channel.ReadFromResponseCoreTestHook(new CachedDirectWebResponse { CachedResponseStream = ms }); + IDictionary<string, string> deserializedFields = await this.channel.ReadFromResponseCoreAsyncTestHook( + new HttpResponseMessage { Content = new StreamContent(ms) }, + CancellationToken.None); Assert.AreEqual(fields.Count, deserializedFields.Count); foreach (string key in fields.Keys) { Assert.AreEqual(fields[key], deserializedFields[key]); @@ -158,34 +153,34 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { } [Test, ExpectedException(typeof(ArgumentNullException))] - public void RequestNull() { - this.channel.Request(null); + public async Task RequestNull() { + await this.channel.RequestAsync(null, CancellationToken.None); } [Test, ExpectedException(typeof(ArgumentException))] - public void RequestNullRecipient() { + public async Task RequestNullRecipient() { IDirectedProtocolMessage message = new TestDirectedMessage(MessageTransport.Direct); - this.channel.Request(message); + await this.channel.RequestAsync(message, CancellationToken.None); } [Test, ExpectedException(typeof(NotSupportedException))] - public void RequestBadPreferredScheme() { + public async Task RequestBadPreferredScheme() { TestDirectedMessage message = new TestDirectedMessage(MessageTransport.Direct); message.Recipient = new Uri("http://localtest"); message.HttpMethods = HttpDeliveryMethods.None; - this.channel.Request(message); + await this.channel.RequestAsync(message, CancellationToken.None); } [Test] - public void RequestUsingAuthorizationHeader() { - this.ParameterizedRequestTest(HttpDeliveryMethods.AuthorizationHeaderRequest); + public async Task RequestUsingAuthorizationHeader() { + await this.ParameterizedRequestTestAsync(HttpDeliveryMethods.AuthorizationHeaderRequest); } /// <summary> /// Verifies that message parts can be distributed to the query, form, and Authorization header. /// </summary> [Test] - public void RequestUsingAuthorizationHeaderScattered() { + public async Task RequestUsingAuthorizationHeaderScattered() { TestDirectedMessage request = new TestDirectedMessage(MessageTransport.Direct) { Age = 15, Name = "Andrew", @@ -201,9 +196,9 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { request.Recipient = new Uri("http://localhost/?appearinquery=queryish"); request.HttpMethods = HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest; - HttpWebRequest webRequest = this.channel.InitializeRequest(request); + var webRequest = await this.channel.InitializeRequestAsync(request, CancellationToken.None); Assert.IsNotNull(webRequest); - Assert.AreEqual("POST", webRequest.Method); + Assert.AreEqual(HttpMethod.Post, webRequest.Method); Assert.AreEqual(request.Recipient, webRequest.RequestUri); var declaredParts = new Dictionary<string, string> { @@ -213,23 +208,23 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { { "Timestamp", XmlConvert.ToString(request.Timestamp, XmlDateTimeSerializationMode.Utc) }, }; - Assert.AreEqual(CreateAuthorizationHeader(declaredParts), webRequest.Headers[HttpRequestHeader.Authorization]); - Assert.AreEqual("appearinform=formish", this.webRequestHandler.RequestEntityAsString); + Assert.AreEqual(CreateAuthorizationHeader(declaredParts), webRequest.Headers.Authorization.ToString()); + Assert.AreEqual("appearinform=formish", await webRequest.Content.ReadAsStringAsync()); } [Test] - public void RequestUsingGet() { - this.ParameterizedRequestTest(HttpDeliveryMethods.GetRequest); + public async Task RequestUsingGet() { + await this.ParameterizedRequestTestAsync(HttpDeliveryMethods.GetRequest); } [Test] - public void RequestUsingPost() { - this.ParameterizedRequestTest(HttpDeliveryMethods.PostRequest); + public async Task RequestUsingPost() { + await this.ParameterizedRequestTestAsync(HttpDeliveryMethods.PostRequest); } [Test] - public void RequestUsingHead() { - this.ParameterizedRequestTest(HttpDeliveryMethods.HeadRequest); + public async Task RequestUsingHead() { + await this.ParameterizedRequestTestAsync(HttpDeliveryMethods.HeadRequest); } /// <summary> @@ -238,14 +233,14 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { [Test] public void SendDirectMessageResponseHonorsHttpStatusCodes() { IProtocolMessage message = MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired); - OutgoingWebResponse directResponse = this.channel.PrepareDirectResponseTestHook(message); - Assert.AreEqual(HttpStatusCode.OK, directResponse.Status); + var directResponse = this.channel.PrepareDirectResponseTestHook(message); + Assert.AreEqual(HttpStatusCode.OK, directResponse.StatusCode); var httpMessage = new TestDirectResponseMessageWithHttpStatus(); MessagingTestBase.GetStandardTestMessage(MessagingTestBase.FieldFill.AllRequired, httpMessage); httpMessage.HttpStatusCode = HttpStatusCode.NotAcceptable; directResponse = this.channel.PrepareDirectResponseTestHook(httpMessage); - Assert.AreEqual(HttpStatusCode.NotAcceptable, directResponse.Status); + Assert.AreEqual(HttpStatusCode.NotAcceptable, directResponse.StatusCode); } private static string CreateAuthorizationHeader(IDictionary<string, string> fields) { @@ -296,8 +291,8 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { return new HttpRequestInfo(request.Method, request.RequestUri, request.Headers, postEntity); } - private void ParameterizedRequestTest(HttpDeliveryMethods scheme) { - TestDirectedMessage request = new TestDirectedMessage(MessageTransport.Direct) { + private async Task ParameterizedRequestTestAsync(HttpDeliveryMethods scheme) { + var request = new TestDirectedMessage(MessageTransport.Direct) { Age = 15, Name = "Andrew", Location = new Uri("http://hostb/pathB"), @@ -306,30 +301,29 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { HttpMethods = scheme, }; - CachedDirectWebResponse rawResponse = null; - this.webRequestHandler.Callback = (req) => { - Assert.IsNotNull(req); - HttpRequestInfo reqInfo = ConvertToRequestInfo(req, this.webRequestHandler.RequestEntityStream); - Assert.AreEqual(MessagingUtilities.GetHttpVerb(scheme), reqInfo.HttpMethod); - var incomingMessage = this.channel.ReadFromRequest(reqInfo) as TestMessage; - Assert.IsNotNull(incomingMessage); - Assert.AreEqual(request.Age, incomingMessage.Age); - Assert.AreEqual(request.Name, incomingMessage.Name); - Assert.AreEqual(request.Location, incomingMessage.Location); - Assert.AreEqual(request.Timestamp, incomingMessage.Timestamp); - - var responseFields = new Dictionary<string, string> { - { "age", request.Age.ToString() }, - { "Name", request.Name }, - { "Location", request.Location.AbsoluteUri }, - { "Timestamp", XmlConvert.ToString(request.Timestamp, XmlDateTimeSerializationMode.Utc) }, - }; - rawResponse = new CachedDirectWebResponse(); - rawResponse.SetResponse(MessagingUtilities.CreateQueryString(responseFields)); - return rawResponse; - }; - - IProtocolMessage response = this.channel.Request(request); + Handle(request.Recipient).By( + async (req, ct) => { + Assert.IsNotNull(req); + Assert.AreEqual(MessagingUtilities.GetHttpVerb(scheme), req.Method); + var incomingMessage = (await this.channel.ReadFromRequestAsync(req, CancellationToken.None)) as TestMessage; + Assert.IsNotNull(incomingMessage); + Assert.AreEqual(request.Age, incomingMessage.Age); + Assert.AreEqual(request.Name, incomingMessage.Name); + Assert.AreEqual(request.Location, incomingMessage.Location); + Assert.AreEqual(request.Timestamp, incomingMessage.Timestamp); + + var responseFields = new Dictionary<string, string> { + { "age", request.Age.ToString() }, + { "Name", request.Name }, + { "Location", request.Location.AbsoluteUri }, + { "Timestamp", XmlConvert.ToString(request.Timestamp, XmlDateTimeSerializationMode.Utc) }, + }; + var rawResponse = new HttpResponseMessage(); + rawResponse.Content = new StringContent(MessagingUtilities.CreateQueryString(responseFields)); + return rawResponse; + }); + + IProtocolMessage response = await this.channel.RequestAsync(request, CancellationToken.None); Assert.IsNotNull(response); Assert.IsInstanceOf<TestMessage>(response); TestMessage responseMessage = (TestMessage)response; @@ -338,7 +332,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { Assert.AreEqual(request.Location, responseMessage.Location); } - private void ParameterizedReceiveTest(HttpDeliveryMethods scheme) { + private async Task ParameterizedReceiveTestAsync(HttpDeliveryMethods scheme) { var fields = new Dictionary<string, string> { { "age", "15" }, { "Name", "Andrew" }, @@ -346,7 +340,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { { "Timestamp", XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) }, { "realm", "someValue" }, }; - IProtocolMessage requestMessage = this.channel.ReadFromRequest(CreateHttpRequestInfo(scheme, fields)); + IProtocolMessage requestMessage = await this.channel.ReadFromRequestAsync(CreateHttpRequestInfo(scheme, fields).AsHttpRequestMessage(), CancellationToken.None); Assert.IsNotNull(requestMessage); Assert.IsInstanceOf<TestMessage>(requestMessage); TestMessage testMessage = (TestMessage)requestMessage; diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs index b3869e7..b8d4f2b 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/PlaintextSigningBindingElementTest.cs @@ -5,6 +5,9 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Test.OAuth.ChannelElements { + using System.Threading; + using System.Threading.Tasks; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.ChannelElements; @@ -15,20 +18,20 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { [TestFixture] public class PlaintextSigningBindingElementTest { [Test] - public void HttpsSignatureGeneration() { + public async Task HttpsSignatureGeneration() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest); ITamperResistantOAuthMessage message = new UnauthorizedTokenRequest(endpoint, Protocol.Default.Version); message.ConsumerSecret = "cs"; message.TokenSecret = "ts"; - Assert.IsNotNull(target.ProcessOutgoingMessage(message)); + Assert.IsNotNull(await target.ProcessOutgoingMessageAsync(message, CancellationToken.None)); Assert.AreEqual("PLAINTEXT", message.SignatureMethod); Assert.AreEqual("cs&ts", message.Signature); } [Test] - public void HttpsSignatureVerification() { + public async Task HttpsSignatureVerification() { MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest); ITamperProtectionChannelBindingElement target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); @@ -37,11 +40,11 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { message.TokenSecret = "ts"; message.SignatureMethod = "PLAINTEXT"; message.Signature = "cs&ts"; - Assert.IsNotNull(target.ProcessIncomingMessage(message)); + Assert.IsNotNull(target.ProcessIncomingMessageAsync(message, CancellationToken.None)); } [Test] - public void HttpsSignatureVerificationNotApplicable() { + public async Task HttpsSignatureVerificationNotApplicable() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("https://localtest", HttpDeliveryMethods.GetRequest); @@ -50,11 +53,11 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { message.TokenSecret = "ts"; message.SignatureMethod = "ANOTHERALGORITHM"; message.Signature = "somethingelse"; - Assert.AreEqual(MessageProtections.None, target.ProcessIncomingMessage(message), "PLAINTEXT binding element should opt-out where it doesn't understand."); + Assert.AreEqual(MessageProtections.None, await target.ProcessIncomingMessageAsync(message, CancellationToken.None), "PLAINTEXT binding element should opt-out where it doesn't understand."); } [Test] - public void HttpSignatureGeneration() { + public async Task HttpSignatureGeneration() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("http://localtest", HttpDeliveryMethods.GetRequest); @@ -63,13 +66,13 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { message.TokenSecret = "ts"; // Since this is (non-encrypted) HTTP, so the plain text signer should not be used - Assert.IsNull(target.ProcessOutgoingMessage(message)); + Assert.IsNull(await target.ProcessOutgoingMessageAsync(message, CancellationToken.None)); Assert.IsNull(message.SignatureMethod); Assert.IsNull(message.Signature); } [Test] - public void HttpSignatureVerification() { + public async Task HttpSignatureVerification() { SigningBindingElementBase target = new PlaintextSigningBindingElement(); target.Channel = new TestChannel(); MessageReceivingEndpoint endpoint = new MessageReceivingEndpoint("http://localtest", HttpDeliveryMethods.GetRequest); @@ -78,7 +81,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { message.TokenSecret = "ts"; message.SignatureMethod = "PLAINTEXT"; message.Signature = "cs%26ts"; - Assert.IsNull(target.ProcessIncomingMessage(message), "PLAINTEXT signature binding element should refuse to participate in non-encrypted messages."); + Assert.IsNull(await target.ProcessIncomingMessageAsync(message, CancellationToken.None), "PLAINTEXT signature binding element should refuse to participate in non-encrypted messages."); } } } diff --git a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs index 490399c..e356c64 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ChannelElements/SigningBindingElementBaseTests.cs @@ -6,6 +6,8 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { using System.Collections.Generic; + using System.Net.Http; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.Messaging.Reflection; using DotNetOpenAuth.OAuth; @@ -80,7 +82,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { message.AccessToken = "tokenpublic"; var signedMessage = (ITamperResistantOAuthMessage)message; - signedMessage.HttpMethod = "GET"; + signedMessage.HttpMethod = HttpMethod.Get; signedMessage.SignatureMethod = "HMAC-SHA1"; MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(message); @@ -115,7 +117,7 @@ namespace DotNetOpenAuth.Test.OAuth.ChannelElements { message.ConsumerKey = "nerdbank.org"; ((ITamperResistantOAuthMessage)message).ConsumerSecret = "nerdbanksecret"; var signedMessage = (ITamperResistantOAuthMessage)message; - signedMessage.HttpMethod = "GET"; + signedMessage.HttpMethod = HttpMethod.Get; signedMessage.SignatureMethod = "HMAC-SHA1"; MessageDictionary dictionary = messageDescriptions.GetAccessor(message); dictionary["oauth_timestamp"] = "1222665749"; diff --git a/src/DotNetOpenAuth.Test/OAuth/ConsumerDescription.cs b/src/DotNetOpenAuth.Test/OAuth/ConsumerDescription.cs index 74752f8..5c25d30 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ConsumerDescription.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ConsumerDescription.cs @@ -5,6 +5,8 @@ //----------------------------------------------------------------------- namespace DotNetOpenAuth.Test.OAuth { + using DotNetOpenAuth.OAuth; + /// <summary> /// Information necessary to initialize a <see cref="Consumer"/>, /// and to tell a <see cref="ServiceProvider"/> about it. diff --git a/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs b/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs deleted file mode 100644 index 21c1775..0000000 --- a/src/DotNetOpenAuth.Test/OAuth/OAuthCoordinator.cs +++ /dev/null @@ -1,71 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="OAuthCoordinator.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.Test.OAuth { - using System; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.Messaging.Bindings; - using DotNetOpenAuth.OAuth; - using DotNetOpenAuth.OAuth.ChannelElements; - using DotNetOpenAuth.Test.Mocks; - using Validation; - - /// <summary> - /// Runs a Consumer and Service Provider simultaneously so they can interact in a full simulation. - /// </summary> - internal class OAuthCoordinator : CoordinatorBase<WebConsumer, ServiceProvider> { - private ConsumerDescription consumerDescription; - private ServiceProviderDescription serviceDescription; - private DotNetOpenAuth.OAuth.ServiceProviderSecuritySettings serviceProviderSecuritySettings = DotNetOpenAuth.Configuration.OAuthElement.Configuration.ServiceProvider.SecuritySettings.CreateSecuritySettings(); - private DotNetOpenAuth.OAuth.ConsumerSecuritySettings consumerSecuritySettings = DotNetOpenAuth.Configuration.OAuthElement.Configuration.Consumer.SecuritySettings.CreateSecuritySettings(); - - /// <summary>Initializes a new instance of the <see cref="OAuthCoordinator"/> class.</summary> - /// <param name="consumerDescription">The description of the consumer.</param> - /// <param name="serviceDescription">The service description that will be used to construct the Consumer and ServiceProvider objects.</param> - /// <param name="consumerAction">The code path of the Consumer.</param> - /// <param name="serviceProviderAction">The code path of the Service Provider.</param> - internal OAuthCoordinator(ConsumerDescription consumerDescription, ServiceProviderDescription serviceDescription, Action<WebConsumer> consumerAction, Action<ServiceProvider> serviceProviderAction) - : base(consumerAction, serviceProviderAction) { - Requires.NotNull(consumerDescription, "consumerDescription"); - Requires.NotNull(serviceDescription, "serviceDescription"); - - this.consumerDescription = consumerDescription; - this.serviceDescription = serviceDescription; - } - - /// <summary> - /// Starts the simulation. - /// </summary> - internal override void Run() { - // Clone the template signing binding element. - var signingElement = this.serviceDescription.CreateTamperProtectionElement(); - var consumerSigningElement = signingElement.Clone(); - var spSigningElement = signingElement.Clone(); - - // Prepare token managers - InMemoryTokenManager consumerTokenManager = new InMemoryTokenManager(); - InMemoryTokenManager serviceTokenManager = new InMemoryTokenManager(); - consumerTokenManager.AddConsumer(this.consumerDescription); - serviceTokenManager.AddConsumer(this.consumerDescription); - - // Prepare channels that will pass messages directly back and forth. - var consumerChannel = new CoordinatingOAuthConsumerChannel(consumerSigningElement, (IConsumerTokenManager)consumerTokenManager, this.consumerSecuritySettings); - var serviceProviderChannel = new CoordinatingOAuthServiceProviderChannel(spSigningElement, (IServiceProviderTokenManager)serviceTokenManager, this.serviceProviderSecuritySettings); - consumerChannel.RemoteChannel = serviceProviderChannel; - serviceProviderChannel.RemoteChannel = consumerChannel; - - // Prepare the Consumer and Service Provider objects - WebConsumer consumer = new WebConsumer(this.serviceDescription, consumerTokenManager) { - OAuthChannel = consumerChannel, - }; - ServiceProvider serviceProvider = new ServiceProvider(this.serviceDescription, serviceTokenManager, new NonceMemoryStore()) { - OAuthChannel = serviceProviderChannel, - }; - - this.RunCore(consumer, serviceProvider); - } - } -} diff --git a/src/DotNetOpenAuth.Test/OAuth/ServiceProviderDescriptionTests.cs b/src/DotNetOpenAuth.Test/OAuth/ServiceProviderDescriptionTests.cs index cdc8de5..3da3112 100644 --- a/src/DotNetOpenAuth.Test/OAuth/ServiceProviderDescriptionTests.cs +++ b/src/DotNetOpenAuth.Test/OAuth/ServiceProviderDescriptionTests.cs @@ -11,7 +11,7 @@ namespace DotNetOpenAuth.Test.OAuth { using NUnit.Framework; /// <summary> - /// Tests for the <see cref="ServiceProviderEndpoints"/> class. + /// Tests for the <see cref="ServiceProviderHostDescription"/> class. /// </summary> [TestFixture] public class ServiceProviderDescriptionTests : TestBase { @@ -20,8 +20,8 @@ namespace DotNetOpenAuth.Test.OAuth { /// </summary> [Test] public void UserAuthorizationUriTest() { - ServiceProviderDescription target = new ServiceProviderDescription(); - MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/authorization", HttpDeliveryMethods.GetRequest); + var target = new ServiceProviderHostDescription(); + var expected = new MessageReceivingEndpoint("http://localhost/authorization", HttpDeliveryMethods.GetRequest); MessageReceivingEndpoint actual; target.UserAuthorizationEndpoint = expected; actual = target.UserAuthorizationEndpoint; @@ -36,8 +36,8 @@ namespace DotNetOpenAuth.Test.OAuth { /// </summary> [Test] public void RequestTokenUriTest() { - var target = new ServiceProviderDescription(); - MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/requesttoken", HttpDeliveryMethods.GetRequest); + var target = new ServiceProviderHostDescription(); + var expected = new MessageReceivingEndpoint("http://localhost/requesttoken", HttpDeliveryMethods.GetRequest); MessageReceivingEndpoint actual; target.RequestTokenEndpoint = expected; actual = target.RequestTokenEndpoint; @@ -53,7 +53,7 @@ namespace DotNetOpenAuth.Test.OAuth { /// </summary> [Test, ExpectedException(typeof(ArgumentException))] public void RequestTokenUriWithOAuthParametersTest() { - var target = new ServiceProviderDescription(); + var target = new ServiceProviderHostDescription(); target.RequestTokenEndpoint = new MessageReceivingEndpoint("http://localhost/requesttoken?oauth_token=something", HttpDeliveryMethods.GetRequest); } @@ -62,7 +62,7 @@ namespace DotNetOpenAuth.Test.OAuth { /// </summary> [Test] public void AccessTokenUriTest() { - var target = new ServiceProviderDescription(); + var target = new ServiceProviderHostDescription(); MessageReceivingEndpoint expected = new MessageReceivingEndpoint("http://localhost/accesstoken", HttpDeliveryMethods.GetRequest); MessageReceivingEndpoint actual; target.AccessTokenEndpoint = expected; |