/// <summary>
        /// https://api.twitter.com/oauth/request_token
        /// </summary>
        /// <param name="requestTokenEndpoint"></param>
        /// <param name="consumerKey"></param>
        /// <param name="consumerSecret"></param>
        /// <param name="callbackUrl"></param>
        public OAuthRequestResult <OAuthv1Token> RequestToken(string requestTokenEndpoint, string consumerKey, string consumerSecret, string callbackUrl)
        {
            var _oauthRestClient = new RestClient(requestTokenEndpoint)
            {
                Authenticator = OAuth1Authenticator
                                .ForRequestToken(consumerKey,
                                                 consumerSecret,
                                                 callbackUrl)
            };

            var request = new RestRequest(Method.POST);

            try
            {
                var response = _oauthRestClient.Execute(request);

                if (!response.IsSuccessful)
                {
                    return(OAuthRequestResult <OAuthv1Token> .Fail(response.Content));
                }

                var parsed    = HttpUtility.ParseQueryString(response.Content);
                var tokenStr  = parsed["oauth_token"];
                var secretStr = parsed["oauth_token_secret"];

                var token = OAuthv1Token.Create(tokenStr, secretStr);

                return(OAuthRequestResult <OAuthv1Token> .Success(token));
            }
            catch (Exception ex)
            {
                return(OAuthRequestResult <OAuthv1Token> .Fail(ex.Message));
            }
        }
Beispiel #2
0
 public RestClient GetTrelloRestClient()
 {
     return(new RestClient(_baseUrl)
     {
         Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret)
     });
 }
Beispiel #3
0
        public AuthCredential ProcessApprovedAuthCallback(string TempAuthToken, string Verifier)
        {
            //var verifier = "123456"; // <-- Breakpoint here (set verifier in debugger)

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

            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, TempAuthToken, "123456", Verifier
                );

            var response = client.Execute(request);

            //Assert.NotNull(response);
            //Assert.Equal(HttpStatusCode.OK, 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);
        }
Beispiel #4
0
    public async Task Can_Query_Vimeo() {
        const string consumerKey    = "TODO_CONSUMER_KEY_HERE";
        const string consumerSecret = "TODO_CONSUMER_SECRET_HERE";

        // arrange
        var client = new RestClient("http://vimeo.com/api/rest/v2") {
            Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret)
        };
        var request = new RestRequest();

        request.AddParameter("format", "json");
        request.AddParameter("method", "vimeo.videos.search");
        request.AddParameter("query", "weather");
        request.AddParameter("full_response", 1);

        // act
        var response = await client.ExecuteAsync(request);

        // assert
        Assert.NotNull(response);
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        Assert.NotNull(response.Content);
        response.Content.Should().NotContain("\"stat\":\"fail\"");
        response.Content.Should().Contain("\"stat\":\"ok\"");
    }
Beispiel #5
0
        public async Task TestBitbucketOAuth10()
        {
            var secret = ConfigurationManager.AppSettings["bitbucket-api-secret"];
            var key    = ConfigurationManager.AppSettings["bitbucket-api-key"];

            using (var client = new RestClient("https://bitbucket.org/api/")
            {
                CookieContainer = new CookieContainer()
            })
            {
                client.AddHandler("application/x-www-form-urlencoded", new DictionaryDeserializer());

                var auth = OAuth1Authenticator.ForRequestToken(key, secret,
                                                               "https://testapp.local/callback");
                auth.ParameterHandling = OAuthParameterHandling.UrlOrPostParameters;
                client.Authenticator   = auth;

                //string token, token_secret;
                {
                    var request  = new RestRequest("1.0/oauth/request_token", HttpMethod.Post);
                    var response = await client.Execute <IDictionary <string, string> >(request);

                    Assert.True(response.Data.ContainsKey("oauth_callback_confirmed"));
                    Assert.Equal("true", response.Data["oauth_callback_confirmed"]);

                    //token_secret = response.Data["oauth_token_secret"];
                    //token = response.Data["oauth_token"];
                }
            }
        }
Beispiel #6
0
    public string GetConfirmUrl(out string oauth_token_secret, string callbackUrl_ = null)
    {
        if (callbackUrl_ == null)
        {
            callbackUrl_ = "oob";
        }

        restClient.Authenticator = OAuth1Authenticator.ForRequestToken(appKey, sharedSecret, callbackUrl_);

        RestRequest restRequest = new RestRequest("oauth/request_token", Method.POST);

        restRequest.AddParameter("scope", Permissions);

        IRestResponse response = restClient.Execute(restRequest);

        if (response.StatusCode != System.Net.HttpStatusCode.OK)
        {
            oauth_token_secret = null;
            return(null);
        }

        NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(response.Content);

        oauth_token_secret = queryString["oauth_token_secret"];
        //string oauth_token = queryString["oauth_token"];

        return(queryString["login_url"]);
    }
Beispiel #7
0
        public string GetConfirmUrlWithTempTokens(out string oauth_token, out string oauth_token_secret, List <ScopesEnum> scopes_, string callbackUrl = null)
        {
            scopes = scopes_;
            restClient.Authenticator = OAuth1Authenticator.ForRequestToken(appKey, sharedSecret, callbackUrl ?? "oob");

            var restRequest = new RestRequest("oauth/request_token", Method.POST);

            if (scopes.Count > 1)
            {
                restRequest.AddQueryParameter("scopes", Permissions);
            }
            var response = restClient.Execute(restRequest);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                oauth_token        = null;
                oauth_token_secret = null;
                return(null);
            }

            NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(response.Content);

            oauth_token        = queryString["oauth_token"];
            oauth_token_secret = queryString["oauth_token_secret"];

            return(queryString["login_url"]);
        }
Beispiel #8
0
        public async Task <ActionResult <TwitterRequestTokenResponse> > GetTwitterOAuthTokenUsingResharpAsync()
        {
            var consumerKey     = _configuration["Authentication:Twitter:ConsumerKey"];
            var consumerSecrete = _configuration["Authentication:Twitter:ConsumerSecrete"];
            var callbackUrl     = _configuration["Authentication:Twitter:CallbackUrl"];

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

            client.Authenticator = OAuth1Authenticator.ForRequestToken(
                consumerKey,
                consumerSecrete,
                callbackUrl // Value for the oauth_callback parameter
                );

            var request  = new RestRequest("/oauth/request_token", Method.Post);
            var response = await client.ExecuteAsync(request);

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

            var _token                = qs["oauth_token"];
            var _tokenSecret          = qs["oauth_token_secret"];
            var _callbackUrlConfirmed = qs["oauth_callback_confirmed"];

            return(new TwitterRequestTokenResponse()
            {
                OAuthToken = _token, OAuthTokenSecrete = _tokenSecret, OAuthCallBackConfirmed = _callbackUrlConfirmed
            });
        }
Beispiel #9
0
        /// <summary>
        /// Requests authorization of your application by first sending the RequestToken request and then generate an LinkedIN URL to which users can be redirected. This is the first stage of OAuth.
        /// </summary>
        /// <param name="callbackUri">The <see cref="Uri"/> to which the user is redirected when returning from the LinkedIN authorization screen.</param>
        /// <param name="token">The <see cref="RequestToken"/>. Keep this somewhere safely stored with the user's session. You will need the provide this later in method <see cref="ExchangeCodeForAccessToken"/>.</param>
        /// <returns>Returns the LinkedIN authorization <see cref="Uri"/> to which users must be redirected in order give access to your application.</returns>
        /// <exception cref="ArgumentNullException">Thrown when <paramref name="callbackUri"/> is null.</exception>
        /// <exception cref="LinkedINHttpResponseException">Thrown when LinkedIN did not respond properly while requesting the request token.</exception>
        public Uri RequestAuthorizationToken(Uri callbackUri, out RequestToken token)
        {
            // validate arguments
            if (callbackUri == null)
            {
                throw new ArgumentNullException("callbackUri");
            }

            // create the client
            var client = new RestClient
            {
                BaseUrl       = OAuthBaseUrl,
                Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret, callbackUri.ToString())
            };

            // create the request
            var requestTokenRequest = new RestRequest("requestToken");

            // execute the request
            var requestTokenResponse = ExecuteRequest(client, requestTokenRequest);

            // extract the token from the query string
            var requestTokenResponseParameters = HttpUtility.ParseQueryString(requestTokenResponse.Content);
            var requestToken  = requestTokenResponseParameters["oauth_token"];
            var requestSecret = requestTokenResponseParameters["oauth_token_secret"];

            token = new RequestToken(requestToken, requestSecret);

            // build the redirect uri
            requestTokenRequest = new RestRequest("authenticate?oauth_token=" + requestToken);
            return(client.BuildUri(requestTokenRequest));
        }
Beispiel #10
0
 public UsosApi(IConfiguration configuration)
 {
     _configuration = configuration;
     Client         = new RestClient("https://apps.usos.pw.edu.pl/services/");
     Client.UseNewtonsoftJson();
     Client.Authenticator = OAuth1Authenticator.ForRequestToken(ConsumerKey, ConsumerSecret, _configuration["MobileAuthRedirectUrl"]);
 }
Beispiel #11
0
        /// <summary>
        /// Issues request for request token and returns result.
        /// </summary>
        private void QueryRequestToken()
        {
            var client = _factory.CreateClient(RequestTokenServiceEndpoint);

            client.Authenticator = OAuth1Authenticator.ForRequestToken(
                Configuration.ClientId, Configuration.ClientSecret, Configuration.RedirectUri);

            var request = _factory.CreateRequest(RequestTokenServiceEndpoint, Method.POST);

            BeforeGetAccessToken(new BeforeAfterRequestArgs
            {
                Client        = client,
                Request       = request,
                Configuration = Configuration
            });

            var response = client.ExecuteAndVerify(request);

            AfterGetAccessToken(new BeforeAfterRequestArgs
            {
                Response = response,
            });

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

            AccessToken       = collection.GetOrThrowMissingValue(OAuthTokenKey);
            AccessTokenSecret = collection.GetOrThrowMissingValue(OAuthTokenSecretKey);
        }
Beispiel #12
0
        /// <summary>
        /// Use this method first to retrieve the url to redirect the user to to allow the url.
        /// Once they are done there, Fitbit will redirect them back to the predetermined completion URL
        /// </summary>
        /// <returns></returns>
        public string GetAuthUrlToken()
        {
            var baseUrl = "https://api.fitbit.com";
            var client  = new RestClient(baseUrl);

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

            var request  = new RestRequest("oauth/request_token", Method.POST);
            var response = client.Execute(request);


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

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception("Request Token Step Failed");
            }

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

            RequestToken       = qs["oauth_token"];
            RequestTokenSecret = qs["oauth_token_secret"];

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

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

            //Process.Start(url);

            return(url);
        }
Beispiel #13
0
        /// <summary>
        /// Issues request for request token and returns result.
        /// </summary>
        /// <returns>The task the request token gets queried on</returns>
        private async Task QueryRequestToken()
        {
            var client = _factory.CreateClient(RequestTokenServiceEndpoint);

            client.Authenticator = OAuth1Authenticator.ForRequestToken(
                Configuration.ClientId,
                Configuration.ClientSecret,
                Configuration.RedirectUri);

            var request = _factory.CreateRequest(RequestTokenServiceEndpoint, Method.POST);

            BeforeGetAccessToken(
                new BeforeAfterRequestArgs
            {
                Client        = client,
                Request       = request,
                Configuration = Configuration
            });

            var response = await client.ExecuteAndVerify(request).ConfigureAwait(false);

            AfterGetAccessToken(
                new BeforeAfterRequestArgs
            {
                Response = response,
            });

            var collection = response.Content.ParseQueryString();

            AccessToken       = collection.GetOrThrowUnexpectedResponse(_oAuthTokenKey);
            AccessTokenSecret = collection.GetOrThrowUnexpectedResponse(_oAuthTokenSecretKey);
        }
        /// <summary>
        /// Start authenticating the user by getting the auth token and then sending them off to the browser to authenticate with Readability.
        /// </summary>
        internal async void BeginAuth()
        {
            IsolatedStorageSettings isss = IsolatedStorageSettings.ApplicationSettings;

            if (AccessToken == null || AccessToken == "")
            {
                var client = new RestClient(ApiBaseUrl);
                client.Authenticator = OAuth1Authenticator.ForRequestToken(ConsumerKey, ConsumerSecret);
                var request  = new RestRequest("oauth/request_token");
                var response = await client.ExecuteTaskAsync(request);

                OAuthToken       = Utilities.GetQueryParameter(response.Content, "oauth_token");
                OAuthTokenSecret = Utilities.GetQueryParameter(response.Content, "oauth_token_secret");

                if (isss.Contains("oath_token"))
                {
                    isss.Remove("oauth_token");
                }
                if (isss.Contains("oauth_token_secret"))
                {
                    isss.Remove("oauth_token_secret");
                }
                isss.Add("oauth_token", OAuthToken);
                isss.Add("oauth_token_secret", OAuthTokenSecret);
                isss.Save();

                string authorizeUrl = ApiBaseUrl + "oauth/authorize?oauth_token=" + OAuthToken + "&oauth_callback=nowreadable:Home";
                await Launcher.LaunchUriAsync(new Uri(authorizeUrl));
            }
        }
Beispiel #15
0
        internal override async Task <(string url, string secret)> GenerateStartRequestUrl(HttpRequest request)
        {
            var callback = CreateCallbackUrl(request);

            _restClient.Authenticator = OAuth1Authenticator.ForRequestToken(_apiDetails.PublicKey, _apiDetails.PrivateKey, callback);
            var restRequest = new RestRequest("oauth/request_token", Method.POST);

            var response = await _restClient.ExecuteTaskAsync <TokenResult>(restRequest);

            // Grrrr, errors come back as json, correct response querystring like thing


            if (response?.IsSuccessful != true)
            {
                var error        = response.Data?.Errors.FirstOrDefault();
                var errorMessage = error != null
                    ? $"Twitter Error {error.Code}: {error.Message}"
                    : "There was an issue starting a login request with Twitter";
                throw new NogginNetCoreAuthException(errorMessage);
            }

            if (response.Data.OauthToken == null || response.Data.OauthTokenSecret == null)
            {
                throw new NogginNetCoreAuthException("Missing token or secret from Twitter");
            }

            return($"https://api.twitter.com/oauth/authenticate?oauth_token={response.Data.OauthToken}", response.Data.OauthTokenSecret);
        }
Beispiel #16
0
        public string GetAuthorizeUrl()
        {
            var baseUrl = new Uri(_config.TokenUrl);
            var client  = new RestClient(baseUrl)
            {
                Authenticator = OAuth1Authenticator.ForRequestToken(_config.ConsumerKey, _config.ConsumerSecret, "oob")
            };

            var request  = new RestRequest("/oauth/request_token");
            var response = client.Execute(request);

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

            _config.OauthToken       = oauthToken;
            _config.OauthTokenSecret = oauthTokenSecret;

            var applicationName = qs["application_name"];

            var baseSslUrl = new Uri(_config.AuthorizeUrl);
            var sslClient  = new RestClient(baseSslUrl);

            request = new RestRequest("authorize");
            request.AddParameter("key", _config.ConsumerKey);
            request.AddParameter("token", oauthToken);


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

            return(url);
        }
Beispiel #17
0
        /*
         * Step one: get the temporary token from withings and generates the withings url the user will access to authorize our app
         *
         * First requests https://oauth.withings.com/account/request_token, signing it with Consumer Secret and adding the Consumer token through GET method
         * This request returns a temporary request token and a temp. request token secret that are stored in the user credentials
         *
         * Then generates and returns the url the caller must send the user to to authorize the token.
         */
        public string GenerateAuthUrlToken()
        {
            var baseUrl = this.BaseUrl;
            var client  = new RestClient(baseUrl);

            client.Authenticator = OAuth1Authenticator.ForRequestToken(this.ConsumerKey, this.ConsumerSecret, this.CallbackUrl);
            ((OAuth1Authenticator)client.Authenticator).ParameterHandling = OAuthParameterHandling.UrlOrPostParameters;

            var request  = new RestRequest("account/request_token", Method.GET);
            var response = client.Execute(request);

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

            UserCredentials.OauthToken       = qs["oauth_token"];
            UserCredentials.OauthTokenSecret = qs["oauth_token_secret"];

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception("Request Token Step Failed");
            }

            request = new RestRequest("account/authorize");

            request.AddParameter("oauth_token", UserCredentials.OauthToken);
            var url = client.BuildUri(request).ToString();

            return(url);
        }
        public static string GetToken()
        {
            string key         = ConfigurationManager.AppSettings["TwitterKey"];
            string SecretKey   = ConfigurationManager.AppSettings["TwitterSecret"];
            string CallBackUrl = HttpContext.Current.Request.UrlReferrer + "Twitter/oauth2callback";
            var    client      = new RestClient("https://api.twitter.com");

            client.Authenticator = OAuth1Authenticator.ForRequestToken(key, SecretKey, CallBackUrl);
            var request = new RestRequest("/oauth/request_token", Method.POST);

            request.AddHeader("Cache-Control", "no-cache");
            var response = client.Execute(request);
            var qs       = HttpUtility.ParseQueryString(response.Content);

            var request2 = new RestRequest("/oauth/authorize?oauth_token=" + qs["oauth_token"]);

            if (response.IsSuccessful)
            {
                return(client.BuildUri(request2).ToString());
            }
            else
            {
                return(null);
            }
        }
Beispiel #19
0
        public void Can_Authenticate_OAuth1_With_Querystring_Parameters()
        {
            const string consumerKey    = "enterConsumerKeyHere";
            const string consumerSecret = "enterConsumerSecretHere";
            const string baseUrl        = "http://restsharp.org";

            var expected = new List <string>
            {
                "oauth_consumer_key",
                "oauth_nonce",
                "oauth_signature_method",
                "oauth_timestamp",
                "oauth_version",
                "oauth_signature"
            };

            var client        = new RestClient(baseUrl);
            var request       = new RestRequest(Method.GET);
            var authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret);

            authenticator.ParameterHandling = OAuthParameterHandling.UrlOrPostParameters;
            authenticator.Authenticate(client, request);

            var requestUri = client.BuildUri(request);
            var actual     = HttpUtility.ParseQueryString(requestUri.Query).AllKeys.ToList();

            Assert.IsTrue(actual.SequenceEqual(expected));
        }
Beispiel #20
0
        /// <summary>
        /// This is Authenticate method which authenticate URL by passing key and secret
        /// </summary>
        /// <param name="client">client</param>
        /// <param name="request">request</param>
        /// <returns>Auth header if authentication gets passed</returns>
        public override void Authenticate(IRestClient client, IRestRequest request)
        {
            request.AddParameter("consumerKey", ((OAuth1Context)authContext).GetConsumerKey());
            request.AddParameter("consumerSecret", ((OAuth1Context)authContext).GetConsumerSecret());

            client.Authenticator = OAuth1Authenticator.ForRequestToken(((OAuth1Context)authContext).GetConsumerKey(), ((OAuth1Context)authContext).GetConsumerSecret());
        }
Beispiel #21
0
 /// <summary>
 /// Getting the authorization code from the Web Service for requesting the Access Token.
 /// </summary>
 /// <returns>Authorization Code</returns>
 public string GetAuthCode()
 {
     try
     {
         token.Response_Type = "code";
         var restclient = new RestClient(token.URL);
         restclient.Authenticator = OAuth1Authenticator.ForRequestToken(token.Client_ID, token.Client_Secret);
         RestRequest request = new RestRequest("oauth/authorize")
         {
             Method = Method.GET
         };
         request.AddParameter("client_id", token.Client_ID);
         request.AddParameter("client_secret", token.Client_Secret);
         request.AddParameter("response_type", token.Response_Type);
         request.AddParameter("redirect_uri", token.Redirect_Url);
         var tResponse = restclient.Execute(request);
         if (tResponse.ResponseUri.IsAbsoluteUri)
         {
             return(tResponse.ResponseUri.AbsoluteUri);
         }
         else
         {
             return("");
         }
     }
     catch
     {
         MessageBox.Show("May be because the Internet connection is lost or other things.");
         return("Error");
     }
 }
Beispiel #22
0
        public Task <Uri> RequestTokenAsync(string callbackUrl = "oob")
        {
            var taskCompletionSource = new TaskCompletionSource <Uri>();
            var client = new RestClient(AUTHENTIFICATION_URL);

            client.Authenticator = OAuth1Authenticator.ForRequestToken(_key, _secretKey, callbackUrl);
            var request = new RestRequest("oauth/request_token", Method.POST);

            request.UseDefaultCredentials = true;
            client.ExecuteAsync(request, response =>
            {
                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    var exception = new BitbucketException("OAuth step failed.");
                    taskCompletionSource.SetException(exception);
                }
                var queryString   = HttpUtility.ParseQueryString(response.Content);
                _oauthToken       = queryString["oauth_token"];
                _oauthTokenSecret = queryString["oauth_token_secret"];

                if ((string.IsNullOrWhiteSpace(_oauthToken) == true) ||
                    (string.IsNullOrWhiteSpace(_oauthTokenSecret) == true))
                {
                    var exception = new BitbucketException("OAuth tokens not received.");
                    taskCompletionSource.SetException(exception);
                }
                request = new RestRequest("oauth/authenticate", Method.GET);
                request.AddParameter("oauth_token", _oauthToken);
                var uri = client.BuildUri(request);
                taskCompletionSource.SetResult(uri);
            }
                                );
            return(taskCompletionSource.Task);
        }
Beispiel #23
0
        public static OAuthTicket GetRequestToken(OAuthTicket ticket, string callback, string requestTokenUrl, string baseUrl)
        {
            var restClient = new RestSharp.RestClient(baseUrl);

            restClient.Authenticator = OAuth1Authenticator.ForRequestToken(ticket.ConsumerKey, ticket.ConsumerSecret, callback);

            var request  = new RestRequest(requestTokenUrl, Method.POST);
            var response = restClient.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new ApiAccessException(response.StatusDescription)
                      {
                          StatusCode        = response.StatusCode,
                          StatusDescription = response.StatusDescription,
                          RequestUrl        = response.ResponseUri.AbsoluteUri
                      };
            }
            else
            {
                var qs = HttpUtility.ParseQueryString(response.Content);
                ticket.AccessToken       = qs["oauth_token"];
                ticket.AccessTokenSecret = qs["oauth_token_secret"];
                return(ticket);
            }
        }
Beispiel #24
0
        private string GenerateAuthUrlToken(bool forceLogoutBeforeAuth)
        {
            var baseUrl = "https://api.fitbit.com";
            var client  = new RestClient(baseUrl);

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

            var request  = new RestRequest("oauth/request_token", Method.POST);
            var response = client.Execute(request);

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

            RequestToken       = qs["oauth_token"];
            RequestTokenSecret = qs["oauth_token_secret"];

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception("Request Token Step Failed");
            }

            if (forceLogoutBeforeAuth)
            {
                request = new RestRequest("oauth/logout_and_authorize"); //this url will force the user to type in username and password
            }
            else
            {
                request = new RestRequest("oauth/authorize");           //this url will show allow/deny if a user is currently logged in
            }
            request.AddParameter("oauth_token", RequestToken);
            var url = client.BuildUri(request).ToString();

            return(url);
        }
Beispiel #25
0
        /// <summary>
        /// Get a requset token from an oauth server
        /// </summary>
        /// <param name="callbackUrl">The url to use to callback to after authorization</param>
        /// <param name="realm">The realm requesting access to</param>
        /// <returns>A token and secret</returns>
        public override IOAuthToken GetRequestToken(Realm realm, string callbackUrl)
        {
            DefaultOAuthToken retVal = null;

            if (realm != null && !string.IsNullOrEmpty(callbackUrl))
            {
                RestClient          restClient    = new RestClient(this.OAuthEndpoints.ServiceUri);
                OAuth1Authenticator authenticator = OAuth1Authenticator.ForRequestToken(this.ConsumerKey, this.ConsumerSecret, callbackUrl);
                authenticator.Realm      = realm.ToString();
                restClient.Authenticator = authenticator;
                RestRequest request  = new RestRequest(this.OAuthEndpoints.RequestTokenUri, Method.GET);
                var         response = restClient.Execute(request);

                var    qs          = HttpUtility.ParseQueryString(response.Content);
                string token       = qs[Constants.TokenParameter];
                string tokenSecret = qs[Constants.TokenSecretParameter];

                if (!string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(tokenSecret))
                {
                    retVal        = new DefaultOAuthToken();
                    retVal.Token  = token;
                    retVal.Secret = tokenSecret;
                }
            }

            return(retVal);
        }
Beispiel #26
0
        public void GetRequestToken(string callbackUrl, Action <OAuthRequestToken> action)
        {
            var client = new RestClient(_baseUrl);

            client.Authenticator = OAuth1Authenticator.ForRequestToken(ConsumerKey, ConsumerSecret, callbackUrl);
            var request = new RestRequest("oauth/request_token");

            client.ExecuteAsync(request,
                                resp =>
            {
                // Handle any non-OK status codes
                if (resp.StatusCode != HttpStatusCode.OK)
                {
                    XDocument doc    = XDocument.Parse(resp.Content);
                    var errorMessage = (string)doc.Element("errors").Element("error");
                    throw new RestRequestException(errorMessage, resp.StatusCode);
                }

                var parameters   = Parse.QueryString(resp.Content);
                var requestToken = new OAuthRequestToken
                {
                    Token       = parameters["oauth_token"],
                    TokenSecret = parameters["oauth_token_secret"]
                };

                if (String.IsNullOrEmpty(requestToken.Token) || String.IsNullOrEmpty(requestToken.TokenSecret))
                {
                    throw new RestRequestException("Error while attempting to request a token.", resp.StatusCode, resp.Content);
                }

                action(requestToken);
            });
        }
Beispiel #27
0
    public void Can_Authenticate_OAuth1_With_Querystring_Parameters() {
        const string consumerKey    = "enterConsumerKeyHere";
        const string consumerSecret = "enterConsumerSecretHere";
        const string baseUrl        = "http://restsharp.org";

        var expected = new List<string> {
            "oauth_consumer_key",
            "oauth_nonce",
            "oauth_signature_method",
            "oauth_timestamp",
            "oauth_version",
            "oauth_signature"
        };

        var client        = new RestClient(baseUrl);
        var request       = new RestRequest();
        var authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret);
        authenticator.ParameterHandling = OAuthParameterHandling.UrlOrPostParameters;
        authenticator.Authenticate(client, request);

        var requestUri = client.BuildUri(request);
        var actual     = requestUri.ParseQuery().Select(x => x.Key).ToList();

        actual.Should().BeEquivalentTo(expected);
    }
Beispiel #28
0
        public void Can_Query_Vimeo()
        {
            const string consumerKey    = "TODO_CONSUMER_KEY_HERE";
            const string consumerSecret = "TODO_CONSUMER_SECRET_HERE";

            // arrange
            RestClient client = new RestClient
            {
                BaseUrl       = new Uri("http://vimeo.com/api/rest/v2"),
                Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret)
            };
            RestRequest request = new RestRequest();

            request.AddParameter("format", "json");
            request.AddParameter("method", "vimeo.videos.search");
            request.AddParameter("query", "weather");
            request.AddParameter("full_response", 1);

            // act
            IRestResponse response = client.Execute(request);

            // assert
            Assert.NotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.NotNull(response.Content);
            Assert.False(response.Content.Contains("\"stat\":\"fail\""));
            Assert.True(response.Content.Contains("\"stat\":\"ok\""));
        }
Beispiel #29
0
        public void Can_Authenticate_With_OAuth()
        {
            var baseUrl = new Uri("https://api.twitter.com");

            var client = new RestClient(baseUrl)
            {
                Authenticator = OAuth1Authenticator.ForRequestToken("CONSUMER_KEY", "CONSUMER_SECRET")
            };
            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"];

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

            request = new RestRequest("oauth/authorize?oauth_token=" + oauthToken);

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

            Process.Start(url);

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

            request = new RestRequest("oauth/access_token");

            client.Authenticator = OAuth1Authenticator.ForAccessToken(
                "P5QziWtocYmgWAhvlegxw", "jBs07SIxJ0kodeU9QtLEs1W1LRgQb9u5Lc987BA94", 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("account/verify_credentials.xml");

            client.Authenticator = OAuth1Authenticator.ForProtectedResource(
                "P5QziWtocYmgWAhvlegxw", "jBs07SIxJ0kodeU9QtLEs1W1LRgQb9u5Lc987BA94", oauthToken,
                oauthTokenSecret
                );
            response = client.Execute(request);

            Assert.NotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
Beispiel #30
0
        public RedirectResult Start()
        {
            // 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_OAuthBaseURL);

            // for in-band, you can specify a callback url,  which will be redirect to
            // after the user is authenticated
            // the callback url parameter can be ommited if you do not want to use callback
            string scheme      = this.Url.RequestContext.HttpContext.Request.Url.Scheme;
            string callbackUrl = this.Url.Action("AuthCallback", "Authenticate", null, scheme);

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


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

            request.AddHeader("Content-Type", "application/json");
            var response = m_Client.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                m_Client = null;
                //NetLog.WriteTextLog("</br>Oops! Something went wrong - couldn't request token Autodesk oxygen provider" + "</br>" + "-----------------------" + "</br>");

                string errorUrl = this.Url.Action("AuthenticationFailed", "Authenticate", new { reason = "Couldn't request token Autodesk oxygen provider" }, this.Request.Url.Scheme);
                return(new RedirectResult(errorUrl));
            }
            else
            {
                //get the request token successfully
                //Get the request token and associated parameters.
                var qs = HttpUtility.ParseQueryString(response.Content);
                m_oAuthReqToken       = qs["oauth_token"];
                m_oAuthReqTokenSecret = qs["oauth_token_secret"];


                //build URL for Authorization HTTP request
                RestRequest authorizeRequest = new RestRequest
                {
                    Resource = "OAuth/Authorize",
                    Method   = Method.GET //must be GET, POST will cause "500 - Internal server error."
                };

                authorizeRequest.AddParameter("viewmode", "full");
                authorizeRequest.AddParameter("oauth_token", m_oAuthReqToken);
                authorizeRequest.AddHeader("Content-Type", "application/json");

                Uri authorizeUri = m_Client.BuildUri(authorizeRequest);
                var url          = authorizeUri.ToString();

                // navigate to the Authorization URL

                return(new RedirectResult(url));
            }
        }