예제 #1
0
        //[Test]
        public void Can_Authenticate_Netflix_With_OAuth()
        {
            const string consumerKey    = "";
            const string consumerSecret = "";

            var baseUrl = new Uri("http://api.netflix.com");
            var client  = new RestClient(baseUrl)
            {
                Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret)
            };
            var request  = new RestRequest("oauth/request_token");
            var response = client.Execute(request);

            Assert.NotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            var qs               = HttpUtility.ParseQueryString(response.Content);
            var oauthToken       = qs["oauth_token"];
            var oauthTokenSecret = qs["oauth_token_secret"];
            var applicationName  = qs["application_name"];

            Assert.NotNull(oauthToken);
            Assert.NotNull(oauthTokenSecret);
            Assert.NotNull(applicationName);

            var baseSslUrl = new Uri("https://api-user.netflix.com");
            var sslClient  = new RestClient(baseSslUrl);

            request = new RestRequest("oauth/login");
            request.AddParameter("oauth_token", oauthToken);
            request.AddParameter("oauth_consumer_key", consumerKey);
            request.AddParameter("application_name", applicationName);

            var url = sslClient.BuildUri(request)
                      .ToString();

            Process.Start(url);

            request = new RestRequest("oauth/access_token"); // <-- Breakpoint here, login to netflix
            client.Authenticator = OAuth1Authenticator.ForAccessToken(consumerKey, consumerSecret, oauthToken,
                                                                      oauthTokenSecret);
            response = client.Execute(request);

            Assert.NotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            qs               = HttpUtility.ParseQueryString(response.Content);
            oauthToken       = qs["oauth_token"];
            oauthTokenSecret = qs["oauth_token_secret"];

            var userId = qs["user_id"];

            Assert.NotNull(oauthToken);
            Assert.NotNull(oauthTokenSecret);
            Assert.NotNull(userId);

            client.Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, oauthToken,
                                                                            oauthTokenSecret);
            request = new RestRequest("users/{user_id}/queues/disc");
            request.AddUrlSegment("user_id", userId);
            request.AddParameter("max_results", "2");

            var queueResponse = client.Execute <Queue>(request);

            Assert.NotNull(queueResponse);
            Assert.AreEqual(HttpStatusCode.OK, queueResponse.StatusCode);
            Assert.NotNull(queueResponse.Data);
            Assert.AreEqual(2, queueResponse.Data.Items.Count);
        }
예제 #2
0
        private async Task TestOAuth10(IHttpClientFactory httpClientFactory, ISignatureProvider signatureProvider)
        {
            using (var client = new RestClient("http://oauthbin.com/v1/")
            {
                HttpClientFactory = httpClientFactory,
            })
            {
                var consumerKey    = "key";
                var consumerSecret = "secret";

                var authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret, "http://localhost/test");
                authenticator.SignatureProvider = signatureProvider;
                client.Authenticator            = authenticator;

                string requestToken, requestTokenSecret;

                {
                    var request  = new RestRequest("request-token");
                    var response = await client.Execute(request);

                    var requestTokenResponse = Encoding.UTF8.GetString(response.RawBytes);
                    Assert.DoesNotContain('\n', requestTokenResponse);

                    var tokenInfo = (from part in requestTokenResponse.Split('&')
                                     let equalSignPos = part.IndexOf('=')
                                                        let partKey = part.Substring(0, equalSignPos)
                                                                      let partValue = part.Substring(equalSignPos + 1)
                                                                                      select new
                    {
                        partKey,
                        partValue
                    }).ToDictionary(x => x.partKey, x => x.partValue);

                    Assert.Contains("oauth_token", tokenInfo.Keys);
                    Assert.Contains("oauth_token_secret", tokenInfo.Keys);

                    requestToken       = tokenInfo["oauth_token"];
                    requestTokenSecret = tokenInfo["oauth_token_secret"];
                }

                authenticator = OAuth1Authenticator.ForAccessToken(consumerKey, consumerSecret, requestToken, requestTokenSecret);
                authenticator.SignatureProvider = signatureProvider;
                client.Authenticator            = authenticator;

                string accessKey, accessSecret;

                {
                    var request  = new RestRequest("access-token");
                    var response = await client.Execute(request);

                    var accessTokenResponse = Encoding.UTF8.GetString(response.RawBytes);
                    Assert.DoesNotContain('\n', accessTokenResponse);

                    var tokenInfo = (from part in accessTokenResponse.Split('&')
                                     let equalSignPos = part.IndexOf('=')
                                                        let partKey = part.Substring(0, equalSignPos)
                                                                      let partValue = part.Substring(equalSignPos + 1)
                                                                                      select new
                    {
                        partKey,
                        partValue
                    }).ToDictionary(x => x.partKey, x => x.partValue);

                    Assert.Contains("oauth_token", tokenInfo.Keys);
                    Assert.Contains("oauth_token_secret", tokenInfo.Keys);

                    accessKey    = tokenInfo["oauth_token"];
                    accessSecret = tokenInfo["oauth_token_secret"];
                }

                authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, accessKey, accessSecret);
                authenticator.SignatureProvider = signatureProvider;
                client.Authenticator            = authenticator;

                {
                    var request = new RestRequest("echo", Method.POST);
                    request.AddOrUpdateParameter("one", "1");
                    request.AddOrUpdateParameter("two", "2");
                    var response = await client.Execute(request);

                    var text = Encoding.UTF8.GetString(response.RawBytes);
                    Assert.DoesNotContain('\n', text);

                    var data = (from part in text.Split('&')
                                let equalSignPos = part.IndexOf('=')
                                                   let partKey = part.Substring(0, equalSignPos)
                                                                 let partValue = part.Substring(equalSignPos + 1)
                                                                                 select new
                    {
                        partKey,
                        partValue
                    }).ToDictionary(x => x.partKey, x => x.partValue);
                    Assert.Contains("one", data.Keys);
                    Assert.Contains("two", data.Keys);
                    Assert.Equal("1", data["one"]);
                    Assert.Equal("2", data["two"]);
                }
            }
        }
예제 #3
0
        public void Can_Authenticate_LinkedIN_With_OAuth()
        {
            const string consumerKey    = "TODO_CONSUMER_KEY_HERE";
            const string consumerSecret = "TODO_CONSUMER_SECRET_HERE";

            // request token
            var client = new RestClient
            {
                BaseUrl       = new Uri("https://api.linkedin.com/uas/oauth"),
                Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret,
                                                                    "http://localhost")
            };
            var requestTokenRequest  = new RestRequest("requestToken");
            var requestTokenResponse = client.Execute(requestTokenRequest);

            Assert.NotNull(requestTokenResponse);
            Assert.AreEqual(HttpStatusCode.OK, requestTokenResponse.StatusCode);

            var requestTokenResponseParameters = HttpUtility.ParseQueryString(requestTokenResponse.Content);
            var requestToken  = requestTokenResponseParameters["oauth_token"];
            var requestSecret = requestTokenResponseParameters["oauth_token_secret"];

            Assert.NotNull(requestToken);
            Assert.NotNull(requestSecret);

            // redirect user
            requestTokenRequest = new RestRequest("authenticate?oauth_token=" + requestToken);

            var redirectUri = client.BuildUri(requestTokenRequest);

            Process.Start(redirectUri.ToString());

            const string requestUrl = "TODO: put browser URL here";

            // replace this via the debugger with the return url from LinkedIN. Simply copy it from the opened browser

            if (!Debugger.IsAttached)
            {
                Debugger.Launch();
            }

            Debugger.Break();

            // get the access token
            var requestTokenQueryParameters = HttpUtility.ParseQueryString(new Uri(requestUrl).Query);
            var requestVerifier             = requestTokenQueryParameters["oauth_verifier"];

            client.Authenticator = OAuth1Authenticator.ForAccessToken(
                consumerKey, consumerSecret, requestToken, requestSecret, requestVerifier);

            var requestAccessTokenRequest  = new RestRequest("accessToken");
            var requestActionTokenResponse = client.Execute(requestAccessTokenRequest);

            Assert.NotNull(requestActionTokenResponse);
            Assert.AreEqual(HttpStatusCode.OK, requestActionTokenResponse.StatusCode);

            var requestActionTokenResponseParameters = HttpUtility.ParseQueryString(requestActionTokenResponse.Content);
            var accessToken  = requestActionTokenResponseParameters["oauth_token"];
            var accessSecret = requestActionTokenResponseParameters["oauth_token_secret"];

            Assert.NotNull(accessToken);
            Assert.NotNull(accessSecret);
        }
예제 #4
0
        public void Can_Authenticate_With_OAuth()
        {
            const string consumerKey    = "";
            const string consumerSecret = "";

            var baseUrl = "http://api.twitter.com";
            var client  = new RestClient(baseUrl);

            client.Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret);
            var request  = new RestRequest("oauth/request_token", Method.POST);
            var response = client.Execute(request);

            Assert.NotNull(response);
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            var qs                 = HttpUtility.ParseQueryString(response.Content);
            var oauth_token        = qs["oauth_token"];
            var oauth_token_secret = qs["oauth_token_secret"];

            Assert.NotNull(oauth_token);
            Assert.NotNull(oauth_token_secret);

            request = new RestRequest("oauth/authorize");
            request.AddParameter("oauth_token", oauth_token);
            var url = client.BuildUri(request).ToString();

            Process.Start(url);

            var verifier = "123456";             // <-- Breakpoint here (set verifier in debugger)

            request = new RestRequest("oauth/access_token", Method.POST);
            client.Authenticator = OAuth1Authenticator.ForAccessToken(
                consumerKey, consumerSecret, oauth_token, oauth_token_secret, verifier
                );
            response = client.Execute(request);

            Assert.NotNull(response);
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            qs                 = HttpUtility.ParseQueryString(response.Content);
            oauth_token        = qs["oauth_token"];
            oauth_token_secret = qs["oauth_token_secret"];
            Assert.NotNull(oauth_token);
            Assert.NotNull(oauth_token_secret);

            request = new RestRequest("account/verify_credentials.xml");
            client.Authenticator = OAuth1Authenticator.ForProtectedResource(
                consumerKey, consumerSecret, oauth_token, oauth_token_secret
                );

            response = client.Execute(request);

            Assert.NotNull(response);
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            //request = new RestRequest("statuses/update.json", Method.POST);
            //request.AddParameter("status", "Hello world! " + DateTime.Now.Ticks.ToString());
            //client.Authenticator = OAuth1Authenticator.ForProtectedResource(
            //    consumerKey, consumerSecret, oauth_token, oauth_token_secret
            //);

            //response = client.Execute(request);

            //Assert.NotNull(response);
            //Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
예제 #5
0
 public IAuthenticator GetAuthenticatorForAccessToken(string apiKey, string sharedSecret, TemporaryToken tempToken, string verifier)
 {
     return(OAuth1Authenticator.ForAccessToken(apiKey, sharedSecret, tempToken.OAuthToken, tempToken.OAuthTokenSecret, verifier));
 }
        private string GetUserIdWithOAuth()
        {
            // Instantiate the RestSharp library object RestClient. RestSharp is free and makes it
            // very easy to build apps that use the OAuth and OpenID protocols with a provider supporting
            // these protocols
            m_Client = new RestClient(m_baseURL);

            m_Client.Authenticator =
                OAuth1Authenticator.ForRequestToken(m_ConsumerKey, m_ConsumerSecret);

            // Build the HTTP request for a Request token and execute it against the OAuth provider
            var request  = new RestRequest("OAuth/RequestToken", Method.POST);
            var response = m_Client.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                m_Client       = null;
                logOutput.Text = "couldn't request token from Autodesk oxygen provider";
                return(string.Empty);
            }

            // The HTTP request succeeded. Get the request token and associated parameters.
            var qs = HttpUtility.ParseQueryString(response.Content);

            m_oAuthReqToken       = qs["oauth_token"];
            m_oAuthReqTokenSecret = qs["oauth_token_secret"];
            var oauth_callback_confirmed  = qs["oauth_callback_confirmed"];
            var x_oauth_client_identifier = qs["x_oauth_client_identifier"];
            var xoauth_problem            = qs["xoauth_problem"];
            var oauth_error_message       = qs["oauth_error_message"];

            // For in band authorization build URL for Authorization HTTP request
            RestRequest authorizeRequest = new RestRequest
            {
                Resource = "OAuth/Authorize",
            };

            authorizeRequest.AddParameter("viewmode", "desktop");
            authorizeRequest.AddParameter("oauth_token", m_oAuthReqToken);
            Uri authorizeUri = m_Client.BuildUri(authorizeRequest);

            // Launch another window with browser control and navigate to the Authorization URL
            BrowserAuthenticate frm = new BrowserAuthenticate();

            frm.Uri = authorizeUri;
            if (frm.ShowDialog() != true)
            {
                m_Client       = null;
                logOutput.Text = "In band Authorization failed";

                return(string.Empty);
            }

            // Build the HTTP request for an access token
            request = new RestRequest("OAuth/AccessToken", Method.POST);
            m_Client.Authenticator = OAuth1Authenticator.ForAccessToken(
                m_ConsumerKey, m_ConsumerSecret, m_oAuthReqToken, m_oAuthReqTokenSecret
                );
            // Execute the access token request
            response = m_Client.Execute(request);
            if (response.StatusCode != HttpStatusCode.OK)
            {
                m_Client       = null;
                logOutput.Text = "couldn't get access token from your Autodesk account";
                return(string.Empty);
            }


            // The request for access token is successful. Parse the response and store token,token secret and session handle
            qs = HttpUtility.ParseQueryString(response.Content);
            m_oAuthAccessToken       = qs["oauth_token"];
            m_oAuthAccessTokenSecret = qs["oauth_token_secret"];
            var x_oauth_user_name = qs["x_oauth_user_name"];
            var x_oauth_user_guid = qs["x_oauth_user_guid"];


            return(x_oauth_user_guid);
        }
예제 #7
0
        //  This button allows the user to swap out the
        // request token for an access token. This access token is what is used to access
        // resources protected by the authentication provider.
        protected void btnGetAccessToken_Click(object sender, EventArgs e)
        {
            // Build the HTTP request for an access token
            var request = new RestRequest("OAuth/AccessToken", Method.POST);

            String verifier = getVerifier();

            if (verifier.Length == 0)
            {
                logOutput.Text += ("</br>Invalid PIN." + "</br>" + "-----------------------" + "</br>");
                return;
            }


            m_Client.Authenticator = OAuth1Authenticator.ForAccessToken(
                m_ConsumerKey, m_ConsumerSecret, m_oAuthReqToken, m_oAuthReqTokenSecret,
                verifier);


            // Execute the access token request
            var response = m_Client.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                m_Client        = null;
                logOutput.Text += ("</br>Oops! Something went wrong - couldn't get access token from your Autodesk account" + "</br>" + "-----------------------" + "</br>");


                btnGetAccessToken.Enabled = false;
                BtnRefreshToken.Enabled   = false;
                btnInvalideToken.Enabled  = false;
                txtVerifier.Text          = "";
                return;
            }
            else
            {
                // The request for access token is successful. Parse the response and store token,token secret and session handle
                var qs = HttpUtility.ParseQueryString(response.Content);
                m_oAuthAccessToken       = qs["oauth_token"];
                m_oAuthAccessTokenSecret = qs["oauth_token_secret"];
                var x_oauth_user_name   = qs["x_oauth_user_name"];
                var x_oauth_user_guid   = qs["x_oauth_user_guid"];
                var x_scope             = qs["x_scope"];
                var xoauth_problem      = qs["xoauth_problem"];
                var oauth_error_message = qs["oauth_error_message"];
                m_sessionHandle = qs["oauth_session_handle"];

                BtnRefreshToken.Enabled  = true;
                btnInvalideToken.Enabled = true;
            }


            var responseNamedCollection = HttpUtility.ParseQueryString(response.Content);

            string outputString = "";

            foreach (string key in responseNamedCollection.AllKeys)
            {
                outputString += key + "=" + responseNamedCollection[key] + "</br>";
            }

            //Output response log
            logOutput.Text += ("Access Token Response:</br>" + outputString + "-----------------------" + "</br>");
        }
예제 #8
0
        public AuthCredential ProcessApprovedAuthCallback(RequestToken token)
        {
            if (string.IsNullOrWhiteSpace(token.Token))
            {
                throw new Exception("RequestToken.Token must not be null");
            }
            //else if

            client.Authenticator = OAuth1Authenticator.ForRequestToken(this.ConsumerKey, this.ConsumerSecret);

            var request = new RestRequest("oauth/access_token", Method.POST);


            client.Authenticator = OAuth1Authenticator.ForAccessToken(
                this.ConsumerKey, this.ConsumerSecret, token.Token, token.Secret, token.Verifier
                );

            var response = client.Execute(request);

            //Assert.NotNull(response);
            //Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new FitbitException(response.Content, response.StatusCode);
            }

            var qs                 = HttpUtility.ParseQueryString(response.Content); //not actually parsing querystring, but body is formatted like htat
            var oauth_token        = qs["oauth_token"];
            var oauth_token_secret = qs["oauth_token_secret"];
            var encoded_user_id    = qs["encoded_user_id"];

            //Assert.NotNull(oauth_token);
            //Assert.NotNull(oauth_token_secret);

            /*
             * request = new RestRequest("account/verify_credentials.xml");
             * client.Authenticator = OAuth1Authenticator.ForProtectedResource(
             *      this.ConsumerKey, this.ConsumerSecret, oauth_token, oauth_token_secret
             * );
             *
             * response = client.Execute(request);
             *
             */

            return(new AuthCredential()
            {
                AuthToken = oauth_token,
                AuthTokenSecret = oauth_token_secret,
                UserId = encoded_user_id
            });

            //Assert.NotNull(response);
            //Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            //request = new RestRequest("statuses/update.json", Method.POST);
            //request.AddParameter("status", "Hello world! " + DateTime.Now.Ticks.ToString());
            //client.Authenticator = OAuth1Authenticator.ForProtectedResource(
            //    consumerKey, consumerSecret, oauth_token, oauth_token_secret
            //);

            //response = client.Execute(request);

            //Assert.NotNull(response);
            //Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        }
예제 #9
0
        // Connects to OAuth service, returns true if connection successful
        public async Task <bool> DoLoginAsync()
        {
            try
            {
                // The first step of authentication is to request a token
                _client.Authenticator = OAuth1Authenticator.ForRequestToken(
                    ConsumerKey,
                    ConsumerSecret);

                RestRequest requestTokenRequest = new RestRequest
                {
                    Resource = "OAuth/RequestToken",
                    Method   = Method.POST,
                };

                Uri requestUri = _client.BuildUri(requestTokenRequest);

                IRestResponse requestTokenResponse = await _client.ExecuteAsync(
                    requestTokenRequest);

                var requestTokenResponseValues =
                    ParseResponse(requestTokenResponse.Content);

                if (CheckError(requestTokenResponseValues))
                {
                    string problem = requestTokenResponseValues["xoauth_problem"];
                    string msg     = requestTokenResponseValues["oauth_error_message"];

                    OnError(problem, msg);

                    return(false);
                }

                string requestToken       = requestTokenResponseValues["oauth_token"];
                string requestTokenSecret = requestTokenResponseValues["oauth_token_secret"];

                // The second step is to authorize the user using the Autodesk login system
                RestRequest authorizeRequest = new RestRequest
                {
                    Resource = "OAuth/Authorize",
                };

                authorizeRequest.AddParameter("oauth_token", requestToken);

                switch (LoginViewMode)
                {
                case LoginViewModeEnum.iFrame:
                    authorizeRequest.AddParameter("viewmode", "iframe");
                    break;

                case LoginViewModeEnum.Mobile:
                    authorizeRequest.AddParameter("viewmode", "mobile");
                    break;

                default:
                    break;
                }

                Uri authorizeUri = _client.BuildUri(authorizeRequest);

                var callbackUri = new Uri(_client.BaseUrl + "/OAuth/Allow");

                using (LoginForm form = new LoginForm(
                           authorizeUri,
                           callbackUri))
                {
                    if (form.ShowDialog() != DialogResult.OK)
                    {
                        return(false);
                    }
                }

                // The third step is to authenticate using the request tokens
                // Once you get the access token and access token secret
                // you need to use those to make your further REST calls
                // Same in case of refreshing the access tokens or invalidating
                // the current session. To do that we need to pass in
                // the acccess token and access token secret as the token and
                // tokenSecret parameter of the OAuth1Authenticator.ForAccessToken
                // constructor

                RestRequest accessTokenRequest = new RestRequest
                {
                    Resource = "OAuth/AccessToken",
                    Method   = Method.POST,
                };

                _client.Authenticator = OAuth1Authenticator.ForAccessToken(
                    ConsumerKey,
                    ConsumerSecret,
                    requestToken,
                    requestTokenSecret);

                IRestResponse accessTokenResponse = await _client.ExecuteAsync(
                    accessTokenRequest);

                var accessTokenResponseValues =
                    ParseResponse(accessTokenResponse.Content);

                if (CheckError(accessTokenResponseValues))
                {
                    string problem = accessTokenResponseValues["xoauth_problem"];
                    string msg     = accessTokenResponseValues["oauth_error_message"];

                    OnErrorEvent(problem, msg);

                    return(false);
                }

                // Parsing reply components

                AccessToken =
                    accessTokenResponseValues["oauth_token"];

                AccessTokenSecret =
                    accessTokenResponseValues["oauth_token_secret"];

                TokenExpire = double.Parse(
                    accessTokenResponseValues["oauth_expires_in"]);

                SessionHandle =
                    accessTokenResponseValues["oauth_session_handle"];

                SessionExpire = double.Parse(
                    accessTokenResponseValues["oauth_authorization_expires_in"]);

                UserName =
                    accessTokenResponseValues["x_oauth_user_name"];

                UserGUID =
                    accessTokenResponseValues["x_oauth_user_guid"];

                return(true);
            }
            catch (Exception ex)
            {
                OnErrorEvent(ex.ToString(), ex.Message);

                return(false);
            }
        }
예제 #10
0
        // Connects to OAuth service, returns true if connection successful
        public async Task <bool> DoLogin()
        {
            try
            {
                // The first step of authentication is to request a token
                _client.Authenticator = OAuth1Authenticator.ForRequestToken(
                    ConsumerKey,
                    ConsumerSecret);

                RestRequest requestTokenRequest = new RestRequest
                {
                    Resource = "OAuth/RequestToken",
                    Method   = Method.POST,
                };

                Uri requestUri = _client.BuildUri(requestTokenRequest);

                IRestResponse requestTokenResponse =
                    await _client.ExecuteAsync(requestTokenRequest);

                var requestTokenResponseValues =
                    ParseResponse(requestTokenResponse.Content);

                if (CheckError(requestTokenResponseValues))
                {
                    string problem = requestTokenResponseValues["xoauth_problem"];
                    string msg     = requestTokenResponseValues["oauth_error_message"];

                    OnError(problem, msg);

                    return(false);
                }

                string requestToken       = requestTokenResponseValues["oauth_token"];
                string requestTokenSecret = requestTokenResponseValues["oauth_token_secret"];

                // The second step is to authorize the user using the Autodesk login system
                RestRequest authorizeRequest = new RestRequest
                {
                    Resource = "OAuth/Authorize",
                };

                authorizeRequest.AddParameter("oauth_token", requestToken);
                authorizeRequest.AddParameter("viewmode", "mobile");

                Uri authorizeUri = _client.BuildUri(authorizeRequest);

                var callbackUri = new Uri(_client.BaseUrl + "/OAuth/Allow");

                // Custom AuthenticationBroker
                //var asyncOperation = await AdnWebAuthBroker.AuthenticateAsync(

                // WinRT built-in AuthenticationBroker
                var asyncOperation = await WebAuthenticationBroker.AuthenticateAsync(

                    WebAuthenticationOptions.UseTitle,
                    authorizeUri,
                    callbackUri);

                switch (asyncOperation.ResponseStatus)
                {
                case WebAuthenticationStatus.ErrorHttp:
                    //An HTTP error like a 404 was returned
                    return(false);

                case WebAuthenticationStatus.Success:
                    break;

                case WebAuthenticationStatus.UserCancel:
                    return(false);

                default:
                    return(false);
                }

                // The third step is to authenticate using the request tokens
                // Once you get the access token and access token secret
                // you need to use those to make your further REST calls
                // Same in case of refreshing the access tokens or invalidating
                // the current session. To do that we need to pass in
                // the acccess token and access token secret as the token and
                // tokenSecret parameter of the OAuth1Authenticator.ForAccessToken
                // constructor

                RestRequest accessTokenRequest = new RestRequest
                {
                    Resource = "OAuth/AccessToken",
                    Method   = Method.POST,
                };

                _client.Authenticator = OAuth1Authenticator.ForAccessToken(
                    ConsumerKey,
                    ConsumerSecret,
                    requestToken,
                    requestTokenSecret);

                IRestResponse accessTokenResponse = await _client.ExecuteAsync(
                    accessTokenRequest);

                var accessTokenResponseValues =
                    ParseResponse(accessTokenResponse.Content);

                if (CheckError(accessTokenResponseValues))
                {
                    string problem = accessTokenResponseValues["xoauth_problem"];
                    string msg     = accessTokenResponseValues["oauth_error_message"];

                    OnErrorEvent(problem, msg);

                    return(false);
                }

                // Parsing reply components

                AccessToken =
                    accessTokenResponseValues["oauth_token"];

                AccessTokenSecret =
                    accessTokenResponseValues["oauth_token_secret"];

                TokenExpire = double.Parse(
                    accessTokenResponseValues["oauth_expires_in"]);

                SessionHandle =
                    accessTokenResponseValues["oauth_session_handle"];

                SessionExpire = double.Parse(
                    accessTokenResponseValues["oauth_authorization_expires_in"]);

                UserName =
                    accessTokenResponseValues["x_oauth_user_name"];

                UserGUID =
                    accessTokenResponseValues["x_oauth_user_guid"];

                return(true);
            }
            catch (Exception ex)
            {
                OnErrorEvent(ex.ToString(), ex.Message);

                return(false);
            }
        }
예제 #11
0
        //[Fact]
        public async void Can_Authenticate_With_OAuth()
        {
            WwwFormUrlDecoder decoder;

            var baseUrl = "https://api.twitter.com";
            var client  = new RestClient(baseUrl);

            client.Authenticator = OAuth1Authenticator.ForRequestToken(
                "CONSUMER_KEY", "CONSUMER_SECRET"
                );
            var request  = new RestRequest("oauth/request_token");
            var response = await client.ExecuteAsync(request);

            Assert.IsNotNull(response);
            Assert.AreEqual((int)HttpStatusCode.OK, response.StatusCode);

            decoder = new WwwFormUrlDecoder(response.Content);
            var oauth_token        = decoder.GetFirstValueByName("oauth_token");
            var oauth_token_secret = decoder.GetFirstValueByName("oauth_token_secret");

            //var qs = HttpUtility.ParseQueryString(response.Content);
            //var oauth_token = qs["oauth_token"];
            //var oauth_token_secret = qs["oauth_token_secret"];

            Assert.IsNotNull(oauth_token);
            Assert.IsNotNull(oauth_token_secret);

            request = new RestRequest("oauth/authorize?oauth_token=" + oauth_token);
            var url = client.BuildUri(request).ToString();
            //Process.Start(url);

            var verifier = "123456";             // <-- Breakpoint here (set verifier in debugger)

            request = new RestRequest("oauth/access_token");
            client.Authenticator = OAuth1Authenticator.ForAccessToken(
                "P5QziWtocYmgWAhvlegxw", "jBs07SIxJ0kodeU9QtLEs1W1LRgQb9u5Lc987BA94", oauth_token, oauth_token_secret, verifier
                );
            response = await client.ExecuteAsync(request);

            Assert.IsNotNull(response);
            Assert.AreEqual((int)HttpStatusCode.OK, response.StatusCode);

            decoder            = new WwwFormUrlDecoder(response.Content);
            oauth_token        = decoder.GetFirstValueByName("oauth_token");
            oauth_token_secret = decoder.GetFirstValueByName("oauth_token_secret");

            //qs = HttpUtility.ParseQueryString(response.Content);
            //oauth_token = qs["oauth_token"];
            //oauth_token_secret = qs["oauth_token_secret"];

            Assert.IsNotNull(oauth_token);
            Assert.IsNotNull(oauth_token_secret);

            request = new RestRequest("account/verify_credentials.xml");
            client.Authenticator = OAuth1Authenticator.ForProtectedResource(
                "P5QziWtocYmgWAhvlegxw", "jBs07SIxJ0kodeU9QtLEs1W1LRgQb9u5Lc987BA94", oauth_token, oauth_token_secret
                );

            response = await client.ExecuteAsync(request);

            Assert.IsNotNull(response);
            Assert.AreEqual((int)HttpStatusCode.OK, response.StatusCode);
        }
예제 #12
0
        private void forToken()
        {
            var verifier = "";

            if (init.gearalias != null)
            {
                verifier = init.gearalias;
            }
            else
            {
                verifier = init.mgrev;
            }
            Uri        baseUrl = new Uri(init.gearauthsite);
            RestClient client  = new RestClient(baseUrl.AbsoluteUri)
            {
                Authenticator = OAuth1Authenticator.ForRequestToken(init.gearkey, init.gearsecret)
            };
            RestRequest request = new RestRequest(init.requesttokenendpoint, Method.POST);

            request.AddParameter("oauth_callback", "scope=" + init.scope + "&mgrev=" + init.mgrev + "&appid=" + init.appid + "&verifier=" + verifier);
            Int32          unixTimestamp     = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
            IRestResponse  response          = client.Execute(request);
            HttpStatusCode statusCode        = response.StatusCode;
            int            numericStatusCode = (int)statusCode;

            if (numericStatusCode == 200)
            {
                NameValueCollection qs  = HttpUtility.ParseQueryString(response.Content);
                string oauthToken       = qs["oauth_token"];
                string oauthTokenSecret = qs["oauth_token_secret"];
                this.requesttoken.token      = oauthToken;
                this.requesttoken.secret     = oauthTokenSecret;
                this.requesttoken.verifier   = verifier;
                this.tokencache.requesttoken = this.requesttoken;
                string url = client.BuildUri(request).ToString();
                request = new RestRequest(init.accesstokenendpoint, Method.POST);
                request.RequestFormat = DataFormat.Json;
                client.Authenticator  = OAuth1Authenticator.ForAccessToken(init.gearkey, init.gearsecret, oauthToken,
                                                                           oauthTokenSecret);
                request.AddParameter("oauth_verifier", verifier);
                response          = client.Execute(request);
                statusCode        = response.StatusCode;
                numericStatusCode = (int)statusCode;
                if (numericStatusCode == 200)
                {
                    qs               = HttpUtility.ParseQueryString(response.Content);
                    oauthToken       = qs["oauth_token"];
                    oauthTokenSecret = qs["oauth_token_secret"];
                    string endpoint   = qs["endpoint"];
                    string revokecode = CreateToken(oauthTokenSecret + "&" + init.gearsecret, oauthToken);
                    revokecode                  = revokecode.Replace('/', '_');
                    url                         = client.BuildUri(request).ToString();
                    this.accesstoken.token      = oauthToken;
                    this.accesstoken.secret     = oauthTokenSecret;
                    this.accesstoken.endpoint   = endpoint;
                    this.accesstoken.revokecode = revokecode;
                    this.tokencache.accesstoken = this.accesstoken;
                    this.tokencache.key         = init.gearkey;
                    this.token._                = this.tokencache;
                    this.cache.set_item(this.token, "microgear-" + init.gearkey + ".cache");
                }
                else
                {
                    this.onError("Access token is not issued, please check your consumerkey and consumersecret.");
                    reset = true;
                    this.ResetToken();
                }
            }
            else
            {
                this.onError("Request token is not issued, please check your appkey and appsecret.");
            }
        }
        private AccessTokenResult RetrieveAccessToken(VerifierResult verifierResult)
        {
            if (verifierResult == null)
            {
                throw new ArgumentNullException("verifierResult");
            }

            if (string.IsNullOrEmpty(verifierResult.OAuthToken))
            {
                throw new ArgumentException("verifierResult.OAuthToken");
            }

            if (string.IsNullOrEmpty(verifierResult.OAuthToken))
            {
                throw new ArgumentException("verifierResult.OAuthVerifier");
            }

            IRestResponse response;

            try
            {
                var restRequest = new RestRequest("oauth/access_token", Method.POST);
                var restClient  = RestClientFactory.CreateRestClient(BaseUrl);
                TraceSource.TraceVerbose("Retrieving Access Token endpoint: {0}",
                                         restClient.BuildUri(restRequest).AbsoluteUri);

                restClient.Authenticator = OAuth1Authenticator.ForAccessToken(PublicApiKey, SecretApiKey,
                                                                              verifierResult.OAuthToken,
                                                                              null, verifierResult.OAuthVerifier);
                response = restClient.Execute(restRequest);
            }
            catch (Exception exception)
            {
                var errorMessage =
                    string.Format("Failed to retrieve an oauth access token from Twitter. Error Messages: {0}",
                                  exception.RecursiveErrorMessages());
                TraceSource.TraceError(errorMessage);
                throw new AuthenticationException(errorMessage, exception);
            }

            if (response == null ||
                response.StatusCode != HttpStatusCode.OK)
            {
                var errorMessage = string.Format(
                    "Failed to obtain an Access Token from Twitter OR the the response was not an HTTP Status 200 OK. Response Status: {0}. Response Description: {1}. Error Content: {2}. Error Message: {3}.",
                    response == null ? "-- null response --" : response.StatusCode.ToString(),
                    response == null ? string.Empty : response.StatusDescription,
                    response == null ? string.Empty : response.Content,
                    response == null
                        ? string.Empty
                        : response.ErrorException == null
                              ? "--no error exception--"
                              : response.ErrorException.RecursiveErrorMessages());

                TraceSource.TraceError(errorMessage);
                throw new AuthenticationException(errorMessage);
            }

            var querystringParameters = HttpUtility.ParseQueryString(response.Content);

            TraceSource.TraceVerbose("Retrieved OAuth Token - Public Key: {0}. Secret Key: {1} ",
                                     string.IsNullOrEmpty(querystringParameters[OAuthTokenKey])
                                         ? "no public key retrieved from the querystring. What Ze F**k?"
                                         : querystringParameters[OAuthTokenKey],
                                     string.IsNullOrEmpty(querystringParameters[OAuthTokenSecretKey])
                                         ? "no secret key retrieved from the querystring. What Ze F**k?"
                                         : querystringParameters[OAuthTokenSecretKey]);

            return(new AccessTokenResult
            {
                AccessToken = querystringParameters[OAuthTokenKey],
                AccessTokenSecret = querystringParameters[OAuthTokenSecretKey]
            });
        }
예제 #14
0
        //- Third leg: The third step is to authenticate using the request tokens
        //- Once you get the access token and access token secret you need to use those to make your further REST calls
        //- Same in case of refreshing the access tokens or invalidating the current session. To do that we need to pass
        //- in the acccess token and access token secret as the accessToken and tokenSecret parameter of the
        //- [AdskRESTful URLRequestForPath] function
        public static async Task <bool> AccessToken(bool refresh, string PIN)
        {
            try {
                if (_restClient == null)
                {
                    _restClient = new RestClient(UserSettings.OAUTH_HOST);
                }
                var request = new RestRequest(UserSettings.OAUTH_ACCESSTOKEN, Method.POST);

                // If we already got access tokens and now just try to refresh
                // them then we need to provide the session handle
                if (refresh)
                {
                    LogInfo("Refreshing Access Tokens");
                    if (Properties.Settings.Default.oauth_session_handle.Length == 0)
                    {
                        return(false);
                    }
                    if (isOOB)
                    {
                        _restClient.Authenticator = OAuth1Authenticator.ForAccessTokenRefresh(
                            UserSettings.CONSUMER_KEY, UserSettings.CONSUMER_SECRET,
                            Properties.Settings.Default.oauth_token, Properties.Settings.Default.oauth_token_secret,
                            PIN, Properties.Settings.Default.oauth_session_handle
                            );
                    }
                    else
                    {
                        _restClient.Authenticator = OAuth1Authenticator.ForAccessTokenRefresh(
                            UserSettings.CONSUMER_KEY, UserSettings.CONSUMER_SECRET,
                            Properties.Settings.Default.oauth_token, Properties.Settings.Default.oauth_token_secret,
                            Properties.Settings.Default.oauth_session_handle
                            );
                    }
                }
                else
                {
                    LogInfo("Acquiring new Access Tokens");
                    if (Properties.Settings.Default.oauth_token.Length == 0)
                    {
                        return(false);
                    }
                    if (isOOB)
                    {
                        // Use PIN to request access token for users account for an out of band request.
                        _restClient.Authenticator = OAuth1Authenticator.ForAccessToken(
                            UserSettings.CONSUMER_KEY, UserSettings.CONSUMER_SECRET,
                            Properties.Settings.Default.oauth_token, Properties.Settings.Default.oauth_token_secret,
                            PIN
                            );
                    }
                    else
                    {
                        _restClient.Authenticator = OAuth1Authenticator.ForAccessToken(
                            UserSettings.CONSUMER_KEY, UserSettings.CONSUMER_SECRET,
                            Properties.Settings.Default.oauth_token, Properties.Settings.Default.oauth_token_secret
                            );
                    }
                }

                Properties.Settings.Default.oauth_token          = "";
                Properties.Settings.Default.oauth_token_secret   = "";
                Properties.Settings.Default.oauth_session_handle = "";
                Properties.Settings.Default.x_oauth_user_name    = "";
                Properties.Settings.Default.x_oauth_user_guid    = "";
                Properties.Settings.Default.Save();

                Log(UserSettings.OAUTH_ACCESSTOKEN + " request sent", "Request");
                //var response =_restClient.Execute (request) ;
                var response = await _restClient.ExecuteTaskAsync(request);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    LogError("Failure! HTTP request did not work! Maybe you are having a connection problem?");
                    return(false);
                }

                // The HTTP request succeeded. Get the request token and associated parameters.
                var accessToken = HttpUtility.ParseQueryString(response.Content);
                if (accessToken.AllKeys.Contains("xoauth_problem"))
                {
                    LogError("Failure! " + accessToken ["xoauth_problem"] + ": " + accessToken ["oauth_error_message"]);
                    return(false);
                }
                if (accessToken.Count < 3 || accessToken ["oauth_session_handle"] == null)
                {
                    if (refresh)
                    {
                        LogError("Failure! Could not refresh Access Tokens!");
                    }
                    else
                    {
                        LogError("Failure! Could not get Access Tokens!");
                    }
                    return(false);
                }
                if (refresh)
                {
                    Log("Success! Access Tokens refreshed!", "Response");
                }
                else
                {
                    Log("Success! Access Tokens acquired!", "Response");
                }

                // This isn't really secure as the tokens will be stored in the application settings
                // but not protected - This code is there to help testing the sample, but you should consider
                // securing the Access Tokens in a better way, or force login each time the application starts.
                Properties.Settings.Default.oauth_token          = accessToken ["oauth_token"];
                Properties.Settings.Default.oauth_token_secret   = accessToken ["oauth_token_secret"];
                Properties.Settings.Default.oauth_session_handle = accessToken ["oauth_session_handle"];
                Properties.Settings.Default.x_oauth_user_name    = accessToken ["x_oauth_user_name"];
                Properties.Settings.Default.x_oauth_user_guid    = accessToken ["x_oauth_user_guid"];

                // The request returns other parameters that we do not use in this example.
                // They are listed here in comment in case you wanted to use them in your application.
                //double TokenExpire =double.Parse (accessToken ["oauth_expires_in"]) ;
                //double SessionExpire =double.Parse (accessToken ["oauth_authorization_expires_in"]) ;

                Properties.Settings.Default.Save();

                return(true);
            } catch (Exception ex) {
                LogError("Exception: " + ex.Message);
                return(false);
            }
        }
예제 #15
0
        public void Can_Authenticate_With_OAuth()
        {
            const string consumerKey    = "";
            const string consumerSecret = "";

            var baseUrl = new Uri("https://api.twitter.com");

            var client = new RestClient(baseUrl)
            {
                Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret)
            };
            var request  = new RestRequest("oauth/request_token", Method.POST);
            var response = client.Execute(request);

            Assert.NotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            var qs               = HttpUtility.ParseQueryString(response.Content);
            var oauthToken       = qs["oauth_token"];
            var oauthTokenSecret = qs["oauth_token_secret"];

            Assert.NotNull(oauthToken);
            Assert.NotNull(oauthTokenSecret);

            request = new RestRequest("oauth/authorize");
            request.AddParameter("oauth_token", oauthToken);

            var url = client.BuildUri(request).ToString();

            // Breakpoint here, open the URL from the url var in the browser
            // then set verifier in debugger to the value in the URL where you get redirected
            var verifier = "123456";

            request = new RestRequest("oauth/access_token", Method.POST);

            client.Authenticator = OAuth1Authenticator.ForAccessToken(
                consumerKey, consumerSecret, oauthToken,
                oauthTokenSecret, verifier
                );
            response = client.Execute(request);

            Assert.NotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);

            qs               = HttpUtility.ParseQueryString(response.Content);
            oauthToken       = qs["oauth_token"];
            oauthTokenSecret = qs["oauth_token_secret"];

            Assert.NotNull(oauthToken);
            Assert.NotNull(oauthTokenSecret);

            request = new RestRequest("/1.1/account/verify_credentials.json");

            client.Authenticator = OAuth1Authenticator.ForProtectedResource(
                consumerKey, consumerSecret, oauthToken,
                oauthTokenSecret
                );

            response = client.Execute(request);

            Assert.NotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
예제 #16
0
파일: Ally.cs 프로젝트: ryanclouser/Ally
        public async Task <bool> Stream(List <string> symbols, Action <StreamQuote> quote_callback, Action <StreamTrade> trade_callback, SynchronizationContext sc, CancellationToken ct)
        {
            var sclient = new RestClient(stream_uri)
            {
                Authenticator = OAuth1Authenticator.ForAccessToken(consumerKey, consumerSecret, OAuthToken, OAuthSecret)
            };

            var request = new RestRequest("/market/quotes.json");

            request.AddQueryParameter("symbols", string.Join(",", symbols));
            request.Timeout          = 5000;
            request.ReadWriteTimeout = 5000;

            request.ResponseWriter = (ms) =>
            {
                try
                {
                    using (var sr = new StreamReader(ms))
                    {
                        while (!sr.EndOfStream && (ct == null || !ct.IsCancellationRequested))
                        {
                            string data = string.Empty;

                            int c     = 0;
                            int count = 0;

                            while ((c = sr.Read()) != -1)
                            {
                                data += (char)c;

                                if (c == '{')
                                {
                                    count++;
                                }
                                else if (c == '}')
                                {
                                    count--;
                                }

                                if (count == 0)
                                {
                                    break;
                                }
                            }

                            try
                            {
                                var o = JObject.Parse(data);

                                if (o.ContainsKey("quote"))
                                {
                                    var j = JsonConvert.DeserializeObject <StreamQuote>(o["quote"].ToString(), new JsonSerializerSettings
                                    {
                                        Error = (sender, errorArgs) => { errorArgs.ErrorContext.Handled = true; }
                                    });

                                    if (sc != null)
                                    {
                                        sc.Post((t) => quote_callback(j), null);
                                    }
                                    else
                                    {
                                        quote_callback(j);
                                    }
                                }
                                else if (o.ContainsKey("trade"))
                                {
                                    var j = JsonConvert.DeserializeObject <StreamTrade>(o["trade"].ToString(), new JsonSerializerSettings
                                    {
                                        Error = (sender, errorArgs) => { errorArgs.ErrorContext.Handled = true; }
                                    });

                                    if (sc != null)
                                    {
                                        sc.Post((t) => trade_callback(j), null);
                                    }
                                    else
                                    {
                                        trade_callback(j);
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                break;
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            };

            sclient.ConfigureWebRequest((r) =>
            {
                r.ServicePoint.Expect100Continue = true;
                r.KeepAlive = true;
            });

            var response = await sclient.ExecuteAsync(request, ct);

            return(response.StatusCode == HttpStatusCode.OK);
        }