Ejemplo n.º 1
0
        /// <summary>
        /// After the user Authorizes the app, Twitter will
        /// redirect to the callback url, provided during
        /// BeginAuthorization. When redirecting, Twitter will
        /// also provide oauth_verifier and oauth_token
        /// parameters. This method uses those parameters to
        /// request an access token, which is used automatically
        /// by LINQ to Twitter when executing queries.
        /// </summary>
        /// <param name="callback">URL that Twitter redirected to after authorization</param>
        /// <returns>True if successful</returns>
        public bool CompleteAuthorization(Uri callback)
        {
            if (callback == null)
            {
                throw new ArgumentNullException("callback", "You must pass in the callback that Twitter returned after authentication.");
            }

            if (IsAuthorized)
            {
                return(true);
            }

            string verifier = OAuthTwitter.GetUrlParamValue(callback.Query, "oauth_verifier");

            if (verifier != null)
            {
                string oAuthToken = OAuthTwitter.GetUrlParamValue(callback.Query, "oauth_token");

                string screenName;
                string userID;
                OAuthTwitter.AccessTokenGet(oAuthToken, verifier, OAuthAccessTokenUrl, string.Empty, out screenName, out userID);

                ScreenName = screenName;
                UserId     = userID;

                Credentials.OAuthToken  = OAuthTwitter.OAuthToken;
                Credentials.AccessToken = OAuthTwitter.OAuthTokenSecret;
                Credentials.ScreenName  = screenName;
                Credentials.UserId      = userID;
            }

            return(IsAuthorized);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Asynchronously finishes the authorization process
        /// </summary>
        /// <param name="callback">Callback Url that Twitter has added parameters to</param>
        /// <param name="authorizationCompleteCallback">Action you provide for when authorization completes.</param>
        public void CompleteAuthorize(Uri callback, Action <TwitterAsyncResponse <UserIdentifier> > authorizationCompleteCallback)
        {
            if (IsAuthorized)
            {
                return;
            }

            const int QueryPart = 1;

            string[] callbackParts = callback.OriginalString.Split('?');

            if (callbackParts.Length == 2)
            {
                string oauthToken = OAuthTwitter.GetUrlParamValue(callbackParts[QueryPart], "oauth_token");
                Credentials.OAuthToken  = oauthToken;
                OAuthTwitter.OAuthToken = oauthToken;

                // we have to split on # because Twitter appends #PageName at the end of the url,
                // which identifies the Silverlight page to navigate to, but is not part of the verifier
                string verifier =
                    OAuthTwitter
                    .GetUrlParamValue(callbackParts[QueryPart], "oauth_verifier")
                    .Split('#')[0];

                if (verifier != null)
                {
                    OAuthTwitter.GetAccessTokenAsync(verifier, new Uri(OAuthAccessTokenUrl), null, authorizationCompleteCallback);
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Synchronous authorization
        /// </summary>
        public void Authorize()
        {
            if (IsAuthorized)
            {
                return;
            }

            var xauthCredentials = Credentials as XAuthCredentials;

            string postData =
                "x_auth_username="******"&" +
                "x_auth_password="******"&" +
                "x_auth_mode=client_auth";

            string screenName;
            string userID;

            OAuthTwitter.PostAccessToken(OAuthAccessTokenUrl, postData, out screenName, out userID);

            ScreenName = screenName;
            UserId     = userID;

            Credentials.OAuthToken  = OAuthTwitter.OAuthToken;
            Credentials.AccessToken = OAuthTwitter.OAuthTokenSecret;
        }
Ejemplo n.º 4
0
        /// <summary>
        /// OAuth Get
        /// </summary>
        /// <param name="request">Request details</param>
        /// <returns>Request to be sent to Twitter</returns>
        public WebRequest Get(Request request)
        {
            string outUrl;
            string queryString;

            OAuthTwitter.GetOAuthQueryString(HttpMethod.GET, request, string.Empty, out outUrl, out queryString);

#if SILVERLIGHT
            var fullUrl = ProxyUrl + request.FullUrl;

            var req = WebRequest.Create(fullUrl) as HttpWebRequest;
            req.Headers[HttpRequestHeader.Authorization] = new OAuthTwitter().PrepareAuthHeader(queryString);
            InitializeRequest(req);
#else
            var req = WebRequest.Create(request.FullUrl) as HttpWebRequest;
            if (req != null)
            {
                req.Headers[HttpRequestHeader.Authorization] = new OAuthTwitter().PrepareAuthHeader(queryString, request);

                InitializeRequest(req);
            }
#endif

            return(req);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Synchronous authorization
        /// </summary>
        public void Authorize()
        {
            if (IsAuthorized)
            {
                return;
            }

            var request = new Request(OAuthAccessTokenUrl);

            var xauthCredentials = Credentials as XAuthCredentials;
            var postData         = new Dictionary <string, string>();

            postData.Add("x_auth_username", xauthCredentials.UserName);
            postData.Add("x_auth_password", xauthCredentials.Password);
            postData.Add("x_auth_mode", "client_auth");

            string screenName;
            string userID;

            OAuthTwitter.PostAccessToken(request, postData, out screenName, out userID);

            ScreenName = screenName;
            UserId     = userID;

            Credentials.OAuthToken  = OAuthTwitter.OAuthToken;
            Credentials.AccessToken = OAuthTwitter.OAuthTokenSecret;
            Credentials.ScreenName  = screenName;
            Credentials.UserId      = userID;
        }
Ejemplo n.º 6
0
        /// <summary>
        /// OAuth Post
        /// </summary>
        /// <param name="request">The request with the endpoint URL and the parameters to
        /// include in the POST entity.  Must not be null.</param>
        /// <param name="postData">Hash of parameters</param>
        /// <returns>request to send</returns>
        public virtual HttpWebRequest PostRequest(Request request, IDictionary <string, string> postData)
        {
            var auth = OAuthTwitter.GetOAuthQueryStringForPost(request, postData);

#if SILVERLIGHT
            var req = HttpWebRequest.Create(
                ProxyUrl + request.Endpoint +
                (string.IsNullOrEmpty(ProxyUrl) ? "?" : "&") +
                request.QueryString) as HttpWebRequest;
#else
            var req = WebRequest.Create(request.Endpoint) as HttpWebRequest;
#endif

            if (req != null)
            {
#if !SILVERLIGHT && !NETFX_CORE
                req.ServicePoint.Expect100Continue = false;
#endif
                req.Method = HttpMethod.POST.ToString();
                req.Headers[HttpRequestHeader.Authorization] = auth;
#if !WINDOWS_PHONE
                req.ContentType = "application/x-www-form-urlencoded";
#endif
#if !WINDOWS_PHONE && !NETFX_CORE
                req.ContentLength = 0;
#endif

                InitializeRequest(req);
            }

            return(req);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Async OAuth Post
        /// </summary>
        /// <param name="url">Twitter Command</param>
        /// <param name="args">Command Arguments</param>
        /// <returns>HttpWebRequest for post</returns>
        public HttpWebRequest PostAsync(string url, Dictionary <string, string> args)
        {
            string paramsJoined =
                string.Join(
                    "&",
                    (from param in args
                     where !string.IsNullOrEmpty(param.Value)
                     select param.Key + "=" + OAuthTwitter.TwitterParameterUrlEncode(param.Value))
                    .ToArray());

            //url += "?" + paramsJoined;

            var req = WebRequest.Create(
                ProxyUrl + url +
                (string.IsNullOrEmpty(ProxyUrl) ? "?" : "&") +
                paramsJoined)
                      as HttpWebRequest;

            //req.ServicePoint.Expect100Continue = false;
            req.Method = HttpMethod.POST.ToString();

            req.Headers[HttpRequestHeader.Authorization] = OAuthTwitter.GetOAuthQueryStringForPost(url + "?" + paramsJoined);
            req.ContentLength = 0;

            InitializeRequest(req);

            return(req);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Asynchronously finishes the authorization process
        /// </summary>
        /// <param name="pin">Set this to the 7-digit PIN that Twitter provides after the user authorizes your application</param>
        /// <param name="authorizationCompleteCallback">Action you provide for when authorization completes.</param>
        public void CompleteAuthorize(string pin, Action <TwitterAsyncResponse <UserIdentifier> > authorizationCompleteCallback)
        {
            if (IsAuthorized)
            {
                return;
            }

            if (pin == null)
            {
                throw new ArgumentNullException("pin", "pin is required");
            }

            OAuthTwitter.GetAccessTokenAsync(
                pin, new Uri(OAuthAccessTokenUrl), "oob", AuthAccessType.NoChange,
                resp =>
            {
                Credentials.OAuthToken  = OAuthTwitter.OAuthToken;
                Credentials.AccessToken = OAuthTwitter.OAuthTokenSecret;
                UserIdentifier user     = resp.State;
                if (user != null)
                {
                    Credentials.ScreenName = user.ScreenName;
                    Credentials.UserId     = user.UserID;
                }

                authorizationCompleteCallback(resp);
            });
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Asynchronously performs authorization for Silverlight apps
        /// </summary>
        /// <param name="authorizationCompleteCallback">Action you provide for when authorization completes.</param>
        public void BeginAuthorize(Action <TwitterAsyncResponse <UserIdentifier> > authorizationCompleteCallback)
        {
            if (IsAuthorized)
            {
                return;
            }

            var request = new Request(OAuthAccessTokenUrl);

            var xauthCredentials = Credentials as XAuthCredentials;
            var postData         = new Dictionary <string, string>();

            postData.Add("x_auth_username", xauthCredentials.UserName);
            postData.Add("x_auth_password", xauthCredentials.Password);
            postData.Add("x_auth_mode", "client_auth");

            OAuthTwitter.PostAccessTokenAsync(
                request,
                postData,
                resp =>
            {
                Credentials.OAuthToken  = OAuthTwitter.OAuthToken;
                Credentials.AccessToken = OAuthTwitter.OAuthTokenSecret;
                UserIdentifier user     = resp.State;
                if (user != null)
                {
                    Credentials.ScreenName = user.ScreenName;
                    Credentials.UserId     = user.UserID;
                }

                authorizationCompleteCallback(resp);
            });
        }
Ejemplo n.º 10
0
        public void FilterRequestParameters_Splits_Url_Properly()
        {
            var oaTwit = new OAuthTwitter();
            var fullUrl = new Uri("http://www.mySite.com?oauth_token=123&p1=v1");
            
            string filteredUrl = oaTwit.FilterRequestParameters(fullUrl);

            Assert.Equal("http://www.mysite.com/?p1=v1", filteredUrl);
        }
Ejemplo n.º 11
0
        public HttpWebRequest Post(string url)
        {
            var req = WebRequest.Create(ProxyUrl + url) as HttpWebRequest;

            req.Method = HttpMethod.POST.ToString();

            req.Headers[HttpRequestHeader.Authorization] = OAuthTwitter.GetOAuthQueryStringForPost(url);

            InitializeRequest(req);

            return(req);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// First part of the authorization sequence that:
        /// 1. Obtains a request token and then
        /// 2. Redirects to the Twitter authorization page
        /// </summary>
        /// <param name="forceLogin">Forces user to login for Sign-In with Twitter scenarios</param>
        /// <param name="callback">This is where you want Twitter to redirect to after authorization</param>
        public void BeginAuthorization(Uri callback, bool forceLogin)
        {
            if (IsAuthorized)
            {
                return;
            }

            string callbackStr = OAuthTwitter.FilterRequestParameters(callback);
            string link        = OAuthTwitter.AuthorizationLinkGet(OAuthRequestTokenUrl, OAuthAuthorizeUrl, callbackStr, forceLogin, AuthAccessType);

            PerformRedirect(link);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Asynchronously starts the authorization process
        /// </summary>
        /// <param name="authorizationCompleteCallback">Action you provide for when authorization completes.</param>
        public void BeginAuthorize(Uri callback, Action <TwitterAsyncResponse <object> > authorizationCompleteCallback)
        {
            if (IsAuthorized)
            {
                return;
            }

            if (PerformRedirect == null)
            {
                throw new InvalidOperationException("GoToTwitterAuthorization must have a handler before calling BeginAuthorize.");
            }

            OAuthTwitter.GetRequestTokenAsync(new Uri(OAuthRequestTokenUrl), new Uri(OAuthAuthorizeUrl), callback.ToString(), AuthAccessType, false, PerformRedirect, authorizationCompleteCallback);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Asynchronously finishes the authorization process
        /// </summary>
        /// <param name="pin">Set this to the 7-digit PIN that Twitter provides after the user authorizes your application</param>
        /// <param name="authorizationCompleteCallback">Action you provide for when authorization completes.</param>
        public void CompleteAuthorize(string pin, Action <TwitterAsyncResponse <UserIdentifier> > authorizationCompleteCallback)
        {
            if (IsAuthorized)
            {
                return;
            }

            if (pin == null)
            {
                throw new ArgumentNullException("pin", "pin is required");
            }

            OAuthTwitter.GetAccessTokenAsync(pin, new Uri(OAuthAccessTokenUrl), "oob", authorizationCompleteCallback);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Asynchronously starts the authorization process
        /// </summary>
        /// <param name="authorizationCompleteCallback">Action you provide for when authorization completes.</param>
        public void BeginAuthorize(Action <TwitterAsyncResponse <object> > authorizationCompleteCallback)
        {
            if (IsAuthorized)
            {
                return;
            }

            if (GoToTwitterAuthorization == null)
            {
                throw new InvalidOperationException("GoToTwitterAuthorization must have a handler before calling BeginAuthorize.");
            }

            OAuthTwitter.GetRequestTokenAsync(new Uri(OAuthRequestTokenUrl), new Uri(OAuthAuthorizeUrl), "oob", false, GoToTwitterAuthorization, authorizationCompleteCallback);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Retrieves access token from Twitter.
        /// Call this after calling GetAuthorizationPageLink()
        /// </summary>
        /// <param name="oAuthToken">Auth Token from call to GetAuthorizationPageLink</param>
        public void RetrieveAccessToken(string oAuthToken)
        {
            if (string.IsNullOrEmpty(oAuthToken))
            {
                throw new ArgumentException("Invalid OAuth Token.", "oAuthToken");
            }

            string screenName;
            string userID;

            OAuthTwitter.AccessTokenGet(oAuthToken, OAuthAccessTokenUrl, out screenName, out userID);

            OAuthRequestScreenName = screenName;
            OAuthRequestUserID     = userID;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Asynchronously performs authorization for Silverlight apps
        /// </summary>
        /// <param name="authorizationCompleteCallback">Action you provide for when authorization completes.</param>
        public void BeginAuthorize(Action <TwitterAsyncResponse <UserIdentifier> > authorizationCompleteCallback)
        {
            if (IsAuthorized)
            {
                return;
            }

            var xauthCredentials = Credentials as XAuthCredentials;

            string postData =
                "x_auth_username="******"&" +
                "x_auth_password="******"&" +
                "x_auth_mode=client_auth";

            string url = OAuthAccessTokenUrl + "?" + postData;

            OAuthTwitter.PostAccessTokenAsync(new Uri(url), postData, authorizationCompleteCallback);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Perform authorization
        /// </summary>
        /// <param name="forceLogin">Force the user to enter their name.</param>
        public void Authorize(bool forceLogin)
        {
            if (IsAuthorized)
            {
                return;
            }

            if (GetPin == null)
            {
                throw new InvalidOperationException("GetPin must have a handler before calling Authorize.");
            }

            if (GoToTwitterAuthorization == null)
            {
                throw new InvalidOperationException("GoToTwitterAuthorization must have a handler before calling Authorize.");
            }

            string link = OAuthTwitter.AuthorizationLinkGet(OAuthRequestTokenUrl, OAuthAuthorizeUrl, "oob", forceLogin, AuthAccessType);

            GoToTwitterAuthorization(link);

            string verifier = GetPin();

            // TODO: Refactor to share similar logic with WebAuthorizer
            string oAuthToken =
                (from nameValPair in new Uri(link).Query.TrimStart('?').Split('&')
                 let pair = nameValPair.Split('=')
                            where pair[0] == "oauth_token"
                            select pair[1])
                .SingleOrDefault();

            string screenName;
            string userID;

            OAuthTwitter.AccessTokenGet(oAuthToken, verifier, OAuthAccessTokenUrl, string.Empty, out screenName, out userID);

            ScreenName = screenName;
            UserId     = userID;

            Credentials.OAuthToken  = OAuthTwitter.OAuthToken;
            Credentials.AccessToken = OAuthTwitter.OAuthTokenSecret;
            Credentials.ScreenName  = screenName;
            Credentials.UserId      = userID;
        }
Ejemplo n.º 19
0
        protected OAuthAuthorizer()
        {
            OAuthRequestTokenUrl = "https://api.twitter.com/oauth/request_token";
            OAuthAuthorizeUrl = "https://api.twitter.com/oauth/authorize";
            OAuthAccessTokenUrl = "https://api.twitter.com/oauth/access_token";

            OAuthTwitter = new OAuthTwitter();

#if SILVERLIGHT && !WINDOWS_PHONE
            if (!Application.Current.IsRunningOutOfBrowser)
            {
                ProxyUrl =
                        Application.Current.Host.Source.Scheme + "://" +
                        Application.Current.Host.Source.Host + ":" +
                        Application.Current.Host.Source.Port + "/LinqToTwitterProxy.ashx?url="; 
            }
#else
            ProxyUrl = string.Empty;
#endif
        }
Ejemplo n.º 20
0
        protected OAuthAuthorizer()
        {
            OAuthRequestTokenUrl = "https://api.twitter.com/oauth/request_token";
            OAuthAuthorizeUrl    = "https://api.twitter.com/oauth/authorize";
            OAuthAccessTokenUrl  = "https://api.twitter.com/oauth/access_token";

            OAuthTwitter = new OAuthTwitter();

#if SILVERLIGHT && !WINDOWS_PHONE
            if (!Application.Current.IsRunningOutOfBrowser)
            {
                ProxyUrl =
                    Application.Current.Host.Source.Scheme + "://" +
                    Application.Current.Host.Source.Host + ":" +
                    Application.Current.Host.Source.Port + "/LinqToTwitterProxy.ashx?url=";
            }
#else
            ProxyUrl = string.Empty;
#endif
        }
Ejemplo n.º 21
0
        /// <summary>
        /// OAuth Get
        /// </summary>
        /// <param name="url">Twitter Query</param>
        /// <returns>Request to be sent to Twitter</returns>
        public WebRequest Get(string url)
        {
            string outUrl;
            string queryString;

            OAuthTwitter.GetOAuthQueryString(HttpMethod.GET, url, string.Empty, out outUrl, out queryString);

#if SILVERLIGHT
            var req = HttpWebRequest.Create(
                ProxyUrl + url +
                (string.IsNullOrEmpty(ProxyUrl) ? "?" : "&") +
                queryString);
#else
            var req = HttpWebRequest.Create(outUrl + "?" + queryString) as HttpWebRequest;
            //req.Headers[HttpRequestHeader.Authorization] = PrepareAuthHeader(queryString);

            InitializeRequest(req);
#endif

            return(req);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Async OAuth Post
        /// </summary>
        /// <param name="request">The request with the endpoint URL and the parameters to
        /// include in the POST entity.  Must not be null.</param>
        /// <param name="postData">Hash of parameters</param>
        /// <returns>HttpWebRequest for post</returns>
        public virtual HttpWebRequest PostAsync(Request request, IDictionary <string, string> postData)
        {
            var auth = OAuthTwitter.GetOAuthQueryStringForPost(request, postData);

            var req = WebRequest.Create(
                ProxyUrl + request.Endpoint +
                (string.IsNullOrEmpty(ProxyUrl) ? "?" : "&") +
                request.QueryString)
                      as HttpWebRequest;

            if (req != null)
            {
                req.Method = HttpMethod.POST.ToString();
                req.Headers[HttpRequestHeader.Authorization] = auth;
#if !WINDOWS_PHONE && !NETFX_CORE
                req.ContentLength = 0;
#endif

                InitializeRequest(req);
            }

            return(req);
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Get the link to Twitter's authorization page for this application.
 /// </summary>
 /// <param name="readOnly">true for read-only, otherwise read/Write</param>
 /// <returns>The url with a valid request token, or a null string.</returns>
 public string GetAuthorizationPageLink(bool readOnly, bool forceLogin)
 {
     // TODO: setting readOnly to true doesn't seem to be working; no Twitter API documentation available; check again later - Joe
     // TODO: setting forceLogin to true doesn't seem to be working; no Twitter API documentation available; fix for bug in Twitter API pending; check again later - Joe
     return(OAuthTwitter.AuthorizationLinkGet(OAuthRequestTokenUrl, OAuthAuthorizeUrl, readOnly, forceLogin));
 }