public static JObject GetUserInfo(WebConsumer consumer, int userid, String screenName, string accessToken)
        {
            var    baseUri = "https://api.twitter.com/1.1/users/show.json";
            String uri     = String.Empty;

            if (userid > 0 && String.IsNullOrEmpty(screenName))
            {
                uri = String.Concat(baseUri, "?user_id=", userid);
            }

            if (userid == 0 && !String.IsNullOrEmpty(screenName))
            {
                uri = String.Concat(baseUri, "?screen_name=", screenName);
            }

            var endpoint = new MessageReceivingEndpoint(uri, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
            IncomingWebResponse response = consumer.PrepareAuthorizedRequestAndSend(endpoint, accessToken);

            using (var responseReader = response.GetResponseReader())
            {
                var result = responseReader.ReadToEnd();

                return(JObject.Parse(result));
            }
        }
Пример #2
0
        /// <summary>
        /// Gets the direct response of a direct HTTP request.
        /// </summary>
        /// <param name="webRequest">The web request.</param>
        /// <returns>The response to the web request.</returns>
        /// <exception cref="ProtocolException">Thrown on network or protocol errors.</exception>
        protected override IncomingWebResponse GetDirectResponse(HttpWebRequest webRequest)
        {
            IncomingWebResponse response = this.WebRequestHandler.GetResponse(webRequest, DirectWebRequestOptions.AcceptAllHttpResponses);

            // Filter the responses to the allowable set of HTTP status codes.
            if (response.Status != HttpStatusCode.OK && response.Status != HttpStatusCode.BadRequest)
            {
                if (Logger.Channel.IsErrorEnabled)
                {
                    using (var reader = new StreamReader(response.ResponseStream)) {
                        Logger.Channel.ErrorFormat(
                            "Unexpected HTTP status code {0} {1} received in direct response:{2}{3}",
                            (int)response.Status,
                            response.Status,
                            Environment.NewLine,
                            reader.ReadToEnd());
                    }
                }

                // Call dispose before throwing since we're not including the response in the
                // exception we're throwing.
                response.Dispose();

                ErrorUtilities.ThrowProtocol(OpenIdStrings.UnexpectedHttpStatusCode, (int)response.Status, response.Status);
            }

            return(response);
        }
        public static JArray GetUserTimeLine(WebConsumer consumer, String accessToken, int userId, String screenName, bool includeRetweets, int count)
        {
            var parameters = new Dictionary <String, string>();

            parameters.Add("count", count.ToString(CultureInfo.InvariantCulture));
            parameters.Add("include_rts", includeRetweets.ToString());

            if (!String.IsNullOrEmpty(screenName))
            {
                parameters.Add("screen_name", screenName);
            }

            if (userId > 0)
            {
                parameters.Add("user_id", userId.ToString(CultureInfo.InvariantCulture));
            }

            HttpWebRequest      request  = consumer.PrepareAuthorizedRequest(GetUserTimeLineEndPoint, accessToken, parameters);
            IncomingWebResponse response = consumer.Channel.WebRequestHandler.GetResponse(request);

            using (var responseReader = response.GetResponseReader())
            {
                var result = responseReader.ReadToEnd();

                return(JArray.Parse(result));
            }
        }
Пример #4
0
 /// <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)
 {
     try {
         return(this.keyValueForm.GetDictionary(response.ResponseStream));
     } catch (FormatException ex) {
         throw ErrorUtilities.Wrap(ex, ex.Message);
     }
 }
Пример #5
0
        public static XDocument GetUserInfo(int userid, string accessToken)
        {
            var endpoint = new MessageReceivingEndpoint("http://api.twitter.com/1/users/show.xml?user_id=" + userid, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
            IncomingWebResponse response = TwitterSignIn.PrepareAuthorizedRequestAndSend(endpoint, accessToken);
            var doc = XDocument.Load(XmlReader.Create(response.GetResponseReader()));

            return(doc);
        }
Пример #6
0
        public static string Tweet(ConsumerBase twitter, string accessToken, string status)
        {
            Dictionary <string, string> extraData = new Dictionary <string, string>();

            extraData.Add("status", status);
            HttpWebRequest      request  = twitter.PrepareAuthorizedRequest(TweetEndpoint, accessToken, extraData);
            IncomingWebResponse response = twitter.Channel.WebRequestHandler.GetResponse(request);

            return(response.GetResponseReader().ReadToEnd());
        }
Пример #7
0
        private void beginButton_Click(object sender, RoutedEventArgs e)
        {
            try {
                var service = new ServiceProviderDescription {
                    RequestTokenEndpoint      = new MessageReceivingEndpoint(this.requestTokenUrlBox.Text, this.requestTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest),
                    UserAuthorizationEndpoint = new MessageReceivingEndpoint(this.authorizeUrlBox.Text, HttpDeliveryMethods.GetRequest),
                    AccessTokenEndpoint       = new MessageReceivingEndpoint(this.accessTokenUrlBox.Text, this.accessTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest),
                    TamperProtectionElements  = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() },
                    ProtocolVersion           = this.oauthVersion.SelectedIndex == 0 ? ProtocolVersion.V10 : ProtocolVersion.V10a,
                };
                var tokenManager = new InMemoryTokenManager();
                tokenManager.ConsumerKey    = this.consumerKeyBox.Text;
                tokenManager.ConsumerSecret = this.consumerSecretBox.Text;

                var    consumer = new DesktopConsumer(service, tokenManager);
                string accessToken;
                if (service.ProtocolVersion == ProtocolVersion.V10)
                {
                    string requestToken;
                    Uri    authorizeUrl = consumer.RequestUserAuthorization(null, null, out requestToken);
                    Process.Start(authorizeUrl.AbsoluteUri);
                    MessageBox.Show(this, "Click OK when you've authorized the app.");
                    var authorizationResponse = consumer.ProcessUserAuthorization(requestToken, null);
                    accessToken = authorizationResponse.AccessToken;
                }
                else
                {
                    var authorizePopup = new Authorize(
                        consumer,
                        (DesktopConsumer c, out string requestToken) => c.RequestUserAuthorization(null, null, out requestToken));
                    authorizePopup.Owner = this;
                    bool?result = authorizePopup.ShowDialog();
                    if (result.HasValue && result.Value)
                    {
                        accessToken = authorizePopup.AccessToken;
                    }
                    else
                    {
                        return;
                    }
                }
                HttpDeliveryMethods resourceHttpMethod = this.resourceHttpMethodList.SelectedIndex < 2 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest;
                if (this.resourceHttpMethodList.SelectedIndex == 1)
                {
                    resourceHttpMethod |= HttpDeliveryMethods.AuthorizationHeaderRequest;
                }
                var resourceEndpoint = new MessageReceivingEndpoint(this.resourceUrlBox.Text, resourceHttpMethod);
                using (IncomingWebResponse resourceResponse = consumer.PrepareAuthorizedRequestAndSend(resourceEndpoint, accessToken)) {
                    this.resultsBox.Text = resourceResponse.GetResponseReader().ReadToEnd();
                }
            } catch (DotNetOpenAuth.Messaging.ProtocolException ex) {
                MessageBox.Show(this, ex.Message);
            }
        }
Пример #8
0
        public static XDocument UpdateProfileImage(ConsumerBase twitter, string accessToken, Stream image, string contentType)
        {
            var parts = new[] {
                MultipartPostPart.CreateFormFilePart("image", "twitterPhoto", contentType, image),
            };
            HttpWebRequest      request  = twitter.PrepareAuthorizedRequest(UpdateProfileImageEndpoint, accessToken, parts);
            IncomingWebResponse response = twitter.Channel.WebRequestHandler.GetResponse(request);
            string responseString        = response.GetResponseReader().ReadToEnd();

            return(XDocument.Parse(responseString));
        }
Пример #9
0
 internal void RegisterMockResponse(IncomingWebResponse response)
 {
     Requires.NotNull(response, "response");
     if (this.registeredMockResponses.ContainsKey(response.RequestUri))
     {
         Logger.Http.WarnFormat("Mock HTTP response already registered for {0}.", response.RequestUri);
     }
     else
     {
         this.registeredMockResponses.Add(response.RequestUri, response);
     }
 }
Пример #10
0
 internal void RegisterMockResponse(IncomingWebResponse response)
 {
     Contract.Requires <ArgumentNullException>(response != null);
     if (this.registeredMockResponses.ContainsKey(response.RequestUri))
     {
         Logger.Http.WarnFormat("Mock HTTP response already registered for {0}.", response.RequestUri);
     }
     else
     {
         this.registeredMockResponses.Add(response.RequestUri, response);
     }
 }
Пример #11
0
    private string GetResponseContent(IncomingWebResponse response)
    {
        MemoryStream stream = new MemoryStream();

        response.ResponseStream.CopyTo(stream);
        stream.Position = 0;
        response.ResponseStream.Position = 0;

        using (var sr = new StreamReader(stream))
        {
            return(sr.ReadToEnd());
        }
    }
        public static JArray SearchUsers(WebConsumer consumer, String search, string accessToken)
        {
            var endpoint = new MessageReceivingEndpoint("https://api.twitter.com/1.1/users/search.json?q=" + search, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);

            IncomingWebResponse response = consumer.PrepareAuthorizedRequestAndSend(endpoint, accessToken);

            using (var responseReader = response.GetResponseReader())
            {
                var result = responseReader.ReadToEnd();

                return(JArray.Parse(result));
            }
        }
Пример #13
0
        public static XDocument UpdateProfileBackgroundImage(ConsumerBase twitter, string accessToken, string image, bool tile)
        {
            var parts = new[] {
                MultipartPostPart.CreateFormFilePart("image", image, "image/" + Path.GetExtension(image).Substring(1).ToLowerInvariant()),
                MultipartPostPart.CreateFormPart("tile", tile.ToString().ToLowerInvariant()),
            };
            HttpWebRequest request = twitter.PrepareAuthorizedRequest(UpdateProfileBackgroundImageEndpoint, accessToken, parts);

            request.ServicePoint.Expect100Continue = false;
            IncomingWebResponse response = twitter.Channel.WebRequestHandler.GetResponse(request);
            string responseString        = response.GetResponseReader().ReadToEnd();

            return(XDocument.Parse(responseString));
        }
        /// <summary>
        ///    Updates the authenticating user's status, also known as tweeting.
        /// </summary>
        /// <param name="twitter"></param>
        /// <param name="accessToken"></param>
        /// <param name="status">The text of your status update, typically up to 140 characters. URL encode as necessary. t.co link wrapping may effect character counts.</param>
        /// <param name="includeEntities">When set to either true, t or 1, each tweet will include a node called "entities,". This node offers a variety of metadata about the tweet in a discreet structure, including: user_mentions, urls, and hashtags. While entities are opt-in on timelines at present, they will be made a default component of output in the future. See Tweet Entities for more detail on entities.
        ///  </param>
        /// <returns></returns>
        public static JObject UpdateStatus(ConsumerBase twitter, string accessToken, String status, bool includeEntities)
        {
            var parts = new[] {
                MultipartPostPart.CreateFormPart("status", status),
                MultipartPostPart.CreateFormPart("include_entities", includeEntities.ToString()),
            };

            HttpWebRequest      request  = twitter.PrepareAuthorizedRequest(UpdateStatusEndpoint, accessToken, parts);
            IncomingWebResponse response = twitter.Channel.WebRequestHandler.GetResponse(request);

            using (var responseReader = response.GetResponseReader())
            {
                var result = responseReader.ReadToEnd();

                return(JObject.Parse(result));
            }
        }
        public static JArray GetHomeTimeLine(WebConsumer consumer, String accessToken, bool includeRetweets, int count)
        {
            var parameters = new Dictionary <String, string>();

            parameters.Add("count", count.ToString());
            parameters.Add("include_rts", includeRetweets.ToString());

            HttpWebRequest      request  = consumer.PrepareAuthorizedRequest(GetHomeTimeLineEndpoint, accessToken, parameters);
            IncomingWebResponse response = consumer.Channel.WebRequestHandler.GetResponse(request);

            using (var responseReader = response.GetResponseReader())
            {
                var result = responseReader.ReadToEnd();

                return(JArray.Parse(result));
            }
        }
Пример #16
0
        /// <summary>
        /// Gets the protocol message that may be in the given HTTP response.
        /// </summary>
        /// <param name="response">The response that is anticipated to contain an protocol message.</param>
        /// <returns>
        /// The deserialized message parts, if found.  Null otherwise.
        /// </returns>
        /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception>
        protected override IDictionary <string, string> ReadFromResponseCore(IncomingWebResponse response)
        {
            // The spec says direct responses should be JSON objects, but Facebook uses HttpFormUrlEncoded instead, calling it text/plain
            // Others return text/javascript.  Again bad.
            string body = response.GetResponseReader().ReadToEnd();

            if (response.ContentType.MediaType == JsonEncoded || response.ContentType.MediaType == JsonTextEncoded)
            {
                return(this.DeserializeFromJson(body));
            }
            else if (response.ContentType.MediaType == HttpFormUrlEncoded || response.ContentType.MediaType == PlainTextEncoded)
            {
                return(HttpUtility.ParseQueryString(body).ToDictionary());
            }
            else
            {
                throw ErrorUtilities.ThrowProtocol(ClientStrings.UnexpectedResponseContentType, response.ContentType.MediaType);
            }
        }
Пример #17
0
        /// <summary>
        /// Called when receiving a direct response message, before deserialization begins.
        /// </summary>
        /// <param name="response">The HTTP direct response.</param>
        /// <param name="message">The newly instantiated message, prior to deserialization.</param>
        protected override void OnReceivingDirectResponse(IncomingWebResponse response, IDirectResponseProtocolMessage message)
        {
            base.OnReceivingDirectResponse(response, message);

            // Verify that the expected HTTP status code was used for the message,
            // per OpenID 2.0 section 5.1.2.2.
            // Note: The v1.1 spec doesn't require 400 responses for some error messages
            if (message.Version.Major >= 2)
            {
                var httpDirectResponse = message as IHttpDirectResponse;
                if (httpDirectResponse != null)
                {
                    ErrorUtilities.VerifyProtocol(
                        httpDirectResponse.HttpStatusCode == response.Status,
                        MessagingStrings.UnexpectedHttpStatusCode,
                        (int)httpDirectResponse.HttpStatusCode,
                        (int)response.Status);
                }
            }
        }
Пример #18
0
        private static void ValidateXmlDSig(XrdsDocument document, UriIdentifier identifier, IncomingWebResponse response, string signingHost)
        {
            Requires.NotNull(document, "document");
            Requires.NotNull(identifier, "identifier");
            Requires.NotNull(response, "response");

            var signatureNode = document.Node.SelectSingleNode("/xrds:XRDS/ds:Signature", document.XmlNamespaceResolver);

            ErrorUtilities.VerifyProtocol(signatureNode != null, OpenIdStrings.MissingElement, "Signature");
            var signedInfoNode = signatureNode.SelectSingleNode("ds:SignedInfo", document.XmlNamespaceResolver);

            ErrorUtilities.VerifyProtocol(signedInfoNode != null, OpenIdStrings.MissingElement, "SignedInfo");
            ErrorUtilities.VerifyProtocol(
                signedInfoNode.SelectSingleNode("ds:CanonicalizationMethod[@Algorithm='http://docs.oasis-open.org/xri/xrd/2009/01#canonicalize-raw-octets']", document.XmlNamespaceResolver) != null,
                OpenIdStrings.UnsupportedCanonicalizationMethod);
            ErrorUtilities.VerifyProtocol(
                signedInfoNode.SelectSingleNode("ds:SignatureMethod[@Algorithm='http://www.w3.org/2000/09/xmldsig#rsa-sha1']", document.XmlNamespaceResolver) != null,
                OpenIdStrings.UnsupportedSignatureMethod);
            var certNodes = signatureNode.Select("ds:KeyInfo/ds:X509Data/ds:X509Certificate", document.XmlNamespaceResolver);

            ErrorUtilities.VerifyProtocol(certNodes.Count > 0, OpenIdStrings.MissingElement, "X509Certificate");
            var certs = certNodes.Cast <XPathNavigator>().Select(n => new X509Certificate2(Convert.FromBase64String(n.Value.Trim()))).ToList();

            VerifyCertificateChain(certs);

            // Verify that the certificate is issued to the host on whom we are performing discovery.
            string hostName = certs[0].GetNameInfo(X509NameType.DnsName, false);

            ErrorUtilities.VerifyProtocol(string.Equals(hostName, signingHost, StringComparison.OrdinalIgnoreCase), OpenIdStrings.MisdirectedSigningCertificate, hostName, signingHost);

            // Verify the signature itself
            byte[] signature = Convert.FromBase64String(response.Headers["Signature"]);
            var    provider  = (RSACryptoServiceProvider)certs.First().PublicKey.Key;

            byte[] data = new byte[response.ResponseStream.Length];
            response.ResponseStream.Seek(0, SeekOrigin.Begin);
            response.ResponseStream.Read(data, 0, data.Length);
            ErrorUtilities.VerifyProtocol(provider.VerifyData(data, "SHA1", signature), OpenIdStrings.InvalidDSig);
        }
 protected override IDictionary <string, string> ReadFromResponseCore(IncomingWebResponse response)
 {
     return(this.wrappedChannel.ReadFromResponseCoreTestHook(response));
 }
Пример #20
0
        public static XDocument GetUpdates(ConsumerBase twitter, string accessToken)
        {
            IncomingWebResponse response = twitter.PrepareAuthorizedRequestAndSend(GetFriendTimelineStatusEndpoint, accessToken);

            return(XDocument.Load(XmlReader.Create(response.GetResponseReader())));
        }
Пример #21
0
        public static XDocument GetAuthToken(ConsumerBase flickr, string accessToken)
        {
            IncomingWebResponse response = flickr.PrepareAuthorizedRequestAndSend(ServiceDescription.AccessTokenEndpoint, accessToken);

            return(XDocument.Load(XmlReader.Create(response.GetResponseReader())));
        }
Пример #22
0
        /// <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>
        protected override IDictionary <string, string> ReadFromResponseCore(IncomingWebResponse response)
        {
            string body = response.GetResponseReader().ReadToEnd();

            return(HttpUtility.ParseQueryString(body).ToDictionary());
        }
Пример #23
0
        protected override IDictionary <string, string> ReadFromResponseCore(IncomingWebResponse response)
        {
            Channel_Accessor accessor = Channel_Accessor.AttachShadow(this.wrappedChannel);

            return(accessor.ReadFromResponseCore(response));
        }
Пример #24
0
        public static XDocument VerifyCredentials(ConsumerBase twitter, string accessToken)
        {
            IncomingWebResponse response = twitter.PrepareAuthorizedRequestAndSend(VerifyCredentialsEndpoint, accessToken);

            return(XDocument.Load(XmlReader.Create(response.GetResponseReader())));
        }
Пример #25
0
 /// <summary>
 /// Gets the protocol message that may be in the given HTTP response.
 /// </summary>
 /// <param name="response">The response that is anticipated to contain an protocol message.</param>
 /// <returns>
 /// The deserialized message parts, if found.  Null otherwise.
 /// </returns>
 /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception>
 protected override IDictionary <string, string> ReadFromResponseCore(IncomingWebResponse response)
 {
     throw new NotImplementedException();
 }
Пример #26
0
 /// <summary>
 /// Gets the protocol message that may be in the given HTTP response.
 /// </summary>
 /// <param name="response">The response that is anticipated to contain an protocol message.</param>
 /// <returns>
 /// The deserialized message parts, if found.  Null otherwise.
 /// </returns>
 /// <exception cref="ProtocolException">Thrown when the response is not valid.</exception>
 protected override IDictionary <string, string> ReadFromResponseCore(IncomingWebResponse response)
 {
     // We never expect resource servers to send out direct requests,
     // and therefore won't have direct responses.
     throw new NotImplementedException();
 }
        /// <summary>
        /// Validates the XML digital signature on an XRDS document.
        /// </summary>
        /// <param name="document">The XRDS document whose signature should be validated.</param>
        /// <param name="identifier">The identifier under discovery.</param>
        /// <param name="response">The response.</param>
        /// <param name="signingHost">The host name on the certificate that should be used to verify the signature in the XRDS.</param>
        /// <exception cref="ProtocolException">Thrown if the XRDS document has an invalid or a missing signature.</exception>
        private static void ValidateXmlDSig(XrdsDocument document, UriIdentifier identifier, IncomingWebResponse response, string signingHost)
        {
            Contract.Requires <ArgumentNullException>(document != null);
            Contract.Requires <ArgumentNullException>(identifier != null);
            Contract.Requires <ArgumentNullException>(response != null);

            var signatureNode = document.Node.SelectSingleNode("/xrds:XRDS/ds:Signature", document.XmlNamespaceResolver);

            ErrorUtilities.VerifyProtocol(signatureNode != null, "Missing Signature element.");
            var signedInfoNode = signatureNode.SelectSingleNode("ds:SignedInfo", document.XmlNamespaceResolver);

            ErrorUtilities.VerifyProtocol(signedInfoNode != null, "Missing SignedInfo element.");
            ErrorUtilities.VerifyProtocol(
                signedInfoNode.SelectSingleNode("ds:CanonicalizationMethod[@Algorithm='http://docs.oasis-open.org/xri/xrd/2009/01#canonicalize-raw-octets']", document.XmlNamespaceResolver) != null,
                "Unrecognized or missing canonicalization method.");
            ErrorUtilities.VerifyProtocol(
                signedInfoNode.SelectSingleNode("ds:SignatureMethod[@Algorithm='http://www.w3.org/2000/09/xmldsig#rsa-sha1']", document.XmlNamespaceResolver) != null,
                "Unrecognized or missing signature method.");
            var certNodes = signatureNode.Select("ds:KeyInfo/ds:X509Data/ds:X509Certificate", document.XmlNamespaceResolver);

            ErrorUtilities.VerifyProtocol(certNodes.Count > 0, "Missing X509Certificate element.");
            var certs = certNodes.Cast <XPathNavigator>().Select(n => new X509Certificate2(Convert.FromBase64String(n.Value.Trim()))).ToList();

            // Verify that we trust the signer of the certificates.
            // Start by trying to validate just the certificate used to sign the XRDS document,
            // since we can do that with partial trust.
            if (!certs[0].Verify())
            {
                // We couldn't verify just the signing certificate, so try to verify the whole certificate chain.
                try {
                    VerifyCertChain(certs);
                } catch (SecurityException) {
                    Logger.Yadis.Warn("Signing certificate verification failed and we have insufficient code access security permissions to perform certificate chain validation.");
                    ErrorUtilities.ThrowProtocol(OpenIdStrings.X509CertificateNotTrusted);
                }
            }

            // Verify that the certificate is issued to the host on whom we are performing discovery.
            string hostName = certs[0].GetNameInfo(X509NameType.DnsName, false);

            ErrorUtilities.VerifyProtocol(string.Equals(hostName, signingHost, StringComparison.OrdinalIgnoreCase), "X.509 signing certificate issued to {0}, but a certificate for {1} was expected.", hostName, signingHost);

            // Verify the signature itself
            byte[] signature = Convert.FromBase64String(response.Headers["Signature"]);
            var    provider  = (RSACryptoServiceProvider)certs.First().PublicKey.Key;

            byte[] data = new byte[response.ResponseStream.Length];
            response.ResponseStream.Seek(0, SeekOrigin.Begin);
            response.ResponseStream.Read(data, 0, data.Length);
            ErrorUtilities.VerifyProtocol(provider.VerifyData(data, "SHA1", signature), "Invalid XmlDSig signature on XRDS document.");
        }
Пример #28
0
        public XPathNavigator DoRequest(MessageReceivingEndpoint message, List <MultipartPostPart> parameters)
        {
            // Initialize the response XML document
            XDocument responseDocument = null;

            // Perform the request based on the authentication
            if (_oAuthConsumer == null)
            {
                // Multipart requests are only available to authenticated API accesses at the moment
                if (parameters != null)
                {
                    throw new NotImplementedException();
                }

                // Construct the request
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(message.Location);

                if ((message.AllowedMethods & HttpDeliveryMethods.PostRequest) == HttpDeliveryMethods.PostRequest)
                {
                    request.Method = "POST";
                }

                if (_proxy != null)
                {
                    request.Proxy = _proxy;
                }

                // Get and parse the response
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new MalformedRequest(new StreamReader(response.GetResponseStream()).ReadToEnd());
                }

                responseDocument = XDocument.Load(XmlReader.Create(response.GetResponseStream(), new XmlReaderSettings()));
            }
            else
            {
                // Verify authentication
                if (_accessToken == null)
                {
                    AuthorizedTokenResponse accessTokenResponse = _oAuthConsumer.ProcessUserAuthorization();
                    if (accessTokenResponse != null)
                    {
                        _accessToken = accessTokenResponse.AccessToken;
                    }
                    else if (_accessToken == null)
                    {
                        _oAuthConsumer.Channel.Send(_oAuthConsumer.PrepareRequestUserAuthorization());
                    }
                }

                // Construct the request
                HttpWebRequest request = (parameters == null ? _oAuthConsumer.PrepareAuthorizedRequest(message, _accessToken) : _oAuthConsumer.PrepareAuthorizedRequest(message, _accessToken, parameters));
                if (_proxy != null)
                {
                    request.Proxy = _proxy;
                }

                IncomingWebResponse response = _oAuthConsumer.Channel.WebRequestHandler.GetResponse(request);

                if (response.Status != HttpStatusCode.OK)
                {
                    throw new MalformedRequest(new StreamReader(response.ResponseStream).ReadToEnd());
                }

                // Parse the response
                responseDocument = XDocument.Load(XmlReader.Create(response.GetResponseReader()));
            }

            // Establish navigator and validate response
            XPathNavigator responseNavigation = responseDocument.CreateNavigator();

            XPathNodeIterator responseCheckIterator = responseNavigation.Select("/response");

            if (responseCheckIterator.Count == 0)
            {
                throw new MalformedRequest(responseDocument.ToString());
            }
            while (responseCheckIterator.MoveNext())
            {
                if (responseCheckIterator.Current == null)
                {
                    return(null);
                }

                if (responseCheckIterator.Current.GetAttribute("status", "") != "ok")
                {
                    string code = responseCheckIterator.Current.GetAttribute("code", "");
                    string msg  = responseCheckIterator.Current.GetAttribute("message", "");
                    switch (code)
                    {
                    default:
                        throw new MalformedRequest(msg);

                    case "invalid_oauth_site":
                    case "invalid_oauth_user":
                    case "invalid_signature":
                    case "token_required":
                        throw new InvalidCredentials(msg);

                    case "permission_denied":
                        throw new PermissionDenied(msg);
                    }
                }
            }

            // All should be good, return the document
            return(responseNavigation);
        }