示例#1
0
        /// <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)
        {
            Contract.Requires <ArgumentNullException>(consumerDescription != null);
            Contract.Requires <ArgumentNullException>(serviceDescription != null);

            this.consumerDescription = consumerDescription;
            this.serviceDescription  = serviceDescription;
        }
示例#2
0
        /// <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;
        }
示例#3
0
        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(),
                },
            };
            MessageReceivingEndpoint accessPhotoEndpoint = new MessageReceivingEndpoint("http://photos.example.net/photos?file=vacation.jpg&size=original", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest);
            ConsumerDescription      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 = ((CoordinatingOAuthChannel)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();
                ((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;
                ((CoordinatingOAuthChannel)sp.Channel).SendDirectRawResponse(new OutgoingWebResponse {
                    ResponseStream = new MemoryStream(new byte[] { 0x33, 0x66 }),
                    Headers        = new WebHeaderCollection {
                        { HttpResponseHeader.ContentType, "image/jpeg" },
                    },
                });
            });

            coordinator.Run();
        }
        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(),
                },
            };
            MessageReceivingEndpoint accessPhotoEndpoint = new MessageReceivingEndpoint("http://photos.example.net/photos?file=vacation.jpg&size=original", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest);
            ConsumerDescription 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 = ((CoordinatingOAuthChannel)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();
                    ((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;
                    ((CoordinatingOAuthChannel)sp.Channel).SendDirectRawResponse(new OutgoingWebResponse {
                        ResponseStream = new MemoryStream(new byte[] { 0x33, 0x66 }),
                        Headers = new WebHeaderCollection {
                            { HttpResponseHeader.ContentType, "image/jpeg" },
                        },
                    });
                });

            coordinator.Run();
        }
示例#5
0
        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(), },
            };
            var accessPhotoEndpoint = new Uri("http://photos.example.net/photos?file=vacation.jpg&size=original");
            var consumerDescription = new ConsumerDescription("dpf43f3p2l4k3l03", "kd94hf93k423kf44");

            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);
                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);

            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));
                }
            }
        }
		/// <summary>
		/// Tells a Service Provider's token manager about a consumer and its secret
		/// so that the SP can verify the Consumer's signed messages.
		/// </summary>
		/// <param name="consumerDescription">The consumer description.</param>
		internal void AddConsumer(ConsumerDescription consumerDescription) {
			this.consumers.Add(new ConsumerInfo { Key = consumerDescription.ConsumerKey, Secret = consumerDescription.ConsumerSecret });
		}
		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(), },
			};
			var accessPhotoEndpoint = new Uri("http://photos.example.net/photos?file=vacation.jpg&size=original");
			var consumerDescription = new ConsumerDescription("dpf43f3p2l4k3l03", "kd94hf93k423kf44");

			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);
					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);

			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));
				}
			}
		}