Esempio n. 1
0
        private void Default_Loaded(object sender, RoutedEventArgs e)
        {
            if (NavigationContext.QueryString.Count > 0)
            {
                try
                {
                    string type = NavigationContext.QueryString.Values.First();

                    if (type == "Facebook")
                    {
                        facebook.Authenticate(this.socialBrowser, AuthComplete);
                    }
                    else if (type == "Twitter")
                    {
                        orequest = new OAuthRequest()
                        {
                            RequestUri = "http://api.twitter.com/oauth/request_token",
                            AuthorizeUri = "http://api.twitter.com/oauth/authorize",
                            AccessUri = "http://api.twitter.com/oauth/access_token",
                            Method = "POST",
                            ConsumerKey = "NvL5YaZLrJ6tV3n4tK33g",
                            ConsumerSecret = "mLcwj2tIV9xkg9riBHawXC4dhzHKZUJe7LhWq8le0"
                        };

                        orequest.Authenticate(this.socialBrowser, AuthenticationComplete);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        public static OauthToken GetRequestToken(string baseUrl, AvansOauthHelperOptions options)
        {
            // Creating a new instance with a helper method
            OAuthRequest client = OAuthRequest.ForRequestToken(options.AvansClientId, options.AvansSecret);

            client.RequestUrl  = "https://publicapi.avans.nl/oauth/request_token";
            client.CallbackUrl = baseUrl + "/api/account/AvansCallback";

            // Using URL query authorization to get the request token
            string auth     = client.GetAuthorizationQuery();
            var    url      = client.RequestUrl + "?" + auth;
            var    request  = (HttpWebRequest)WebRequest.Create(url);
            var    response = (HttpWebResponse)request.GetResponse();

            Stream       receiveStream = response.GetResponseStream();
            StreamReader reader        = new StreamReader(receiveStream, Encoding.UTF8);
            string       body          = reader.ReadToEnd();

            //TY for the concistent response avans
            var uri = body.Replace("php&", "php?");

            uri = uri.Split("authentification_url=")[1];

            return(AvansOauthHelper.getTokenFormUri(uri));
        }
Esempio n. 3
0
        /// <summary>
        /// Make an API request with OAuth 1.0
        /// </summary>
        public async Task <string> requestAPIOAuthAsync(string url, Method method)
        {
            //Generate OAuthRequest data (library used: OAuth.DotNetCore from Robert Hargreaves)
            OAuthRequest client = new OAuthRequest
            {
                Method             = method.ToString(),
                SignatureTreatment = OAuthSignatureTreatment.Escaped,
                SignatureMethod    = OAuthSignatureMethod.HmacSha1,
                ConsumerKey        = consumerKey,
                ConsumerSecret     = consumerSecret,
                Token       = tokenValue,
                TokenSecret = tokenSecret,
                RequestUrl  = url,
                Version     = "1.0"
            };

            // Format authorization as header string
            string auth = client.GetAuthorizationHeader();

            using (var httpClient = new HttpClient())
            {
                using (var request = new HttpRequestMessage(new HttpMethod(client.Method), client.RequestUrl))
                {
                    request.Headers.TryAddWithoutValidation("Authorization", auth);

                    var response = await httpClient.SendAsync(request);

                    return(response.Content.ReadAsStringAsync().Result);
                }
            }
        }
Esempio n. 4
0
        public dynamic Get(string endpoint)
        {
            //Make a protected resource call!

            this.client = OAuthRequest.ForProtectedResource("GET", this.consumer_key, this.consumer_secret, this.access_token, this.access_secret);

            //INSERT API Endpoint:
            this.client.RequestUrl = this.baseUrl + endpoint;
            //client.RequestUrl = baseUrl + "api/2/ping";

            // Using URL query authorization
            string auth    = this.client.GetAuthorizationQuery();
            var    url     = this.client.RequestUrl + "?" + auth;
            var    request = (HttpWebRequest)WebRequest.Create(url);
            //request3.ContentType = "application/json; charset=utf-8";
            var response = (HttpWebResponse)request.GetResponse();

            //Console.WriteLine(StreamToString(response3.GetResponseStream()));

            string json = StreamToString(response.GetResponseStream());

            //Read the JSON from the string.
            JsonTextReader reader = new JsonTextReader(new StringReader(json));

            //Serialize the JSON text.
            JsonSerializer se = new JsonSerializer();

            //Deserialize the text and place in dynamic type, for easy manipulation.
            dynamic parsedData = se.Deserialize(reader);

            return(parsedData);
        }
Esempio n. 5
0
        public void GetAccess(string verificationCode)
        {
            this.client            = OAuthRequest.ForAccessToken(this.consumer_key, this.consumer_secret, this.request_token, this.request_secret, verificationCode);
            this.client.RequestUrl = this.accessUrl;

            // Using URL query authorization
            string auth2     = this.client.GetAuthorizationQuery();
            var    url2      = this.client.RequestUrl + "?" + auth2;
            var    request2  = (HttpWebRequest)WebRequest.Create(url2);
            var    response2 = (HttpWebResponse)request2.GetResponse();

            //Console.WriteLine(url2);
            //Console.WriteLine("STREAM!");

            //Console.WriteLine(StreamToString(response2.GetResponseStream()));

            string authQuery = StreamToString(response2.GetResponseStream());

            Console.WriteLine(authQuery);

            //Seperate the stream into an Array.
            List <string> query = new List <string>();

            //TODO: Fix ERROR!
            query = QueryToArray(authQuery);
            //Assign each query to their value.
            access_token  = query[3];
            access_secret = query[1];

            //Console.WriteLine("Access Token: " + access_token);
            //Console.WriteLine("Access Secret: " + access_secret);
        }
Esempio n. 6
0
        // Haven't actually tested this out yet
        public async Task ReconnectAccount()
        {
            var authRequest = new OAuthRequest
            {
                Method          = "GET",
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = ConsumerKey,
                ConsumerSecret  = ConsumerSecret,
                Token           = AccessToken,
                TokenSecret     = AccessTokenSecret,
                RequestUrl      = ReconnectUrl,
                Version         = OAuthVersion
            };

            var client = ReconnectUrl.WithHeaders(new
            {
                Accept        = AcceptType,
                Authorization = authRequest.GetAuthorizationHeader()
            });

            try
            {
                await client.GetAsync();
            }
            catch (FlurlHttpException ex)
            {
                throw new QuickBooksException("Unable to reconnect account.", ex.Message);
            }
        }
Esempio n. 7
0
        private void Sign(HttpRequestMessage msg, OAuthRequest req)
        {
            req.SignatureMethod = OAuthSignatureMethod.HmacSha1;
            req.ConsumerKey     = _consumer.Key;
            req.ConsumerSecret  = _consumer.Secret;
            req.RequestUrl      = msg.RequestUri.GetLeftPart(UriPartial.Path);
            req.Method          = msg.Method.Method;
            req.Version         = "1.0";

            var args = msg.RequestUri.ParseQueryString();

            if (msg.Content != null)
            {
                var contentType = msg.Content.Headers.ContentType;
                if (contentType != null && string.Equals("application/x-www-form-urlencoded", contentType.MediaType, StringComparison.OrdinalIgnoreCase))
                {
                    var body = new FormDataCollection(msg.Content.ReadAsStringAsync().Result);
                    foreach (var item in body)
                    {
                        args.Add(item.Key, item.Value);
                    }
                }
            }

            msg.Headers.Add(HttpRequestHeader.Authorization.ToString(), req.GetAuthorizationHeader(args).TrimEnd(','));
        }
Esempio n. 8
0
        public async Task <AccessTokenInfo> RequestAccessTokens(string authToken, string authTokenSecret, string oauthVerifier)
        {
            var oauthRequest = OAuthRequest.ForAccessToken(
                ConsumerKey,
                ConsumerSecret,
                authToken,
                authTokenSecret,
                oauthVerifier
                );

            oauthRequest.RequestUrl = AccessTokenUrl;
            oauthRequest.Version    = OAuthVersion;

            try
            {
                var request = await(oauthRequest.RequestUrl + "?" + oauthRequest.GetAuthorizationQuery()).GetAsync();
                var result  = await request.Content.ReadAsStringAsync();

                var accessTokens = result.Split('&').Select(x => x.Split('=')).ToDictionary(split => split[0], split => split[1]);
                return(new AccessTokenInfo {
                    AccessToken = accessTokens["oauth_token"], AccessTokenSecret = accessTokens["oauth_token_secret"]
                });
            }
            catch (FlurlHttpException ex)
            {
                throw new UnauthorizedQuickBooksClientException(
                          "Unable to get access tokens.",
                          ex.InnerException);
            }
        }
Esempio n. 9
0
        public async Task <AuthTokenInfo> GetAuthTokens()
        {
            var authRequest = new OAuthRequest
            {
                Method          = "GET",
                CallbackUrl     = CallbackUrl,
                Type            = OAuthRequestType.RequestToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = ConsumerKey,
                ConsumerSecret  = ConsumerSecret,
                RequestUrl      = RequestTokenUrl,
                Version         = OAuthVersion
            };

            try
            {
                var request = await(authRequest.RequestUrl + "?" + authRequest.GetAuthorizationQuery()).GetAsync();
                var result  = await request.Content.ReadAsStringAsync();

                var tokens = result.Split('&').Select(x => x.Split('=')).ToDictionary(split => split[0], split => split[1]);
                return(new AuthTokenInfo(AuthorizeUrl)
                {
                    OAuthToken = tokens["oauth_token"], OAuthTokenSecret = tokens["oauth_token_secret"]
                });
            }
            catch (FlurlHttpException ex)
            {
                throw new UnauthorizedQuickBooksClientException(
                          "QuickBooks returned with an unauthorized response. Be sure your consumer key and consumer secret are correct.",
                          ex.InnerException);
            }
        }
Esempio n. 10
0
        public static string TweeterCall(string url, string consumerKey, string consumerSecret)
        {
            OAuthRequest client = new OAuthRequest
            {
                Method          = "GET",
                Type            = OAuthRequestType.RequestToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = consumerKey,
                ConsumerSecret  = consumerSecret,
                RequestUrl      = url,
                Version         = "1.0a",
                Realm           = "twitter.com"
            };

            string         auth    = client.GetAuthorizationHeader();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(client.RequestUrl);

            request.Headers.Add("Authorization", auth);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            var    encoding     = Encoding.UTF8;
            var    reader       = new System.IO.StreamReader(response.GetResponseStream(), encoding);
            string responseText = reader.ReadToEnd();

            reader.Dispose();
            return(responseText);
        }
Esempio n. 11
0
        public async Task <OAuthResponse> GetAccessTokenAsync(OAuthRequest oauthRequest)
        {
            var request = GetBaseRequest(oauthRequest, _options.UsosEndpoints.AccessToken);

            var response = await SendRequestAsync(request);

            return(await ParseTokenResponseAsync(response.Content));
        }
Esempio n. 12
0
    protected void lnkbtnYandexClick(object sender, EventArgs e)
    {
        var oAuthRequest = new OAuthRequest {
            Provider = OAuthRequest.Providers.Yandex
        };

        oAuthRequest.CreateRequest(new ClaimParameters(), false);
    }
        //Get Request Token
        public async Task <RequestTokenResponse> GetRequestToken()
        {
            var requestTokenResponse = new RequestTokenResponse();


            var client         = _clientFactory.CreateClient("twitter");
            var consumerKey    = _twitterConfig.Value.AppId;
            var consumerSecret = _twitterConfig.Value.AppSecret;
            var callbackUrl    = "http://localhost:4200/login";

            client.DefaultRequestHeaders.Accept.Clear();

            var oauthClient = new OAuthRequest
            {
                Method          = "POST",
                Type            = OAuthRequestType.RequestToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = consumerKey,
                ConsumerSecret  = consumerSecret,
                RequestUrl      = "https://api.twitter.com/oauth/request_token",
                Version         = "1.0a",
                Realm           = "twitter.com",
                CallbackUrl     = callbackUrl
            };

            string auth = oauthClient.GetAuthorizationHeader();

            client.DefaultRequestHeaders.Add("Authorization", auth);



            try
            {
                var content = new StringContent("", Encoding.UTF8, "application/json");

                using (var response = await client.PostAsync(oauthClient.RequestUrl, content))
                {
                    response.EnsureSuccessStatusCode();

                    var responseString = response.Content.ReadAsStringAsync()
                                         .Result.Split("&");


                    requestTokenResponse = new RequestTokenResponse
                    {
                        oauth_token              = responseString[0],
                        oauth_token_secret       = responseString[1],
                        oauth_callback_confirmed = responseString[2]
                    };
                }
            }
            catch (Exception ex)
            {
                throw;
            }

            return(requestTokenResponse);
        }
        //Get Access Token
        public async Task <UserModelDto> GetAccessToken(string token, string oauthVerifier)
        {
            var client         = _clientFactory.CreateClient("twitter");
            var consumerKey    = _twitterConfig.Value.AppId;
            var consumerSecret = _twitterConfig.Value.AppSecret;

            var accessTokenResponse = new UserModelDto();

            client.DefaultRequestHeaders.Accept.Clear();

            var oauthClient = new OAuthRequest
            {
                Method          = "POST",
                Type            = OAuthRequestType.AccessToken,
                SignatureMethod = OAuthSignatureMethod.HmacSha1,
                ConsumerKey     = consumerKey,
                ConsumerSecret  = consumerSecret,
                RequestUrl      = "https://api.twitter.com/oauth/access_token",
                Token           = token,
                Version         = "1.0a",
                Realm           = "twitter.com"
            };

            string auth = oauthClient.GetAuthorizationHeader();

            client.DefaultRequestHeaders.Add("Authorization", auth);


            try
            {
                var content = new FormUrlEncodedContent(new[] {
                    new KeyValuePair <string, string>("oauth_verifier", oauthVerifier)
                });

                using (var response = await client.PostAsync(oauthClient.RequestUrl, content))
                {
                    response.EnsureSuccessStatusCode();

                    //twiiter responds with a string concatenated by &
                    var responseString = response.Content.ReadAsStringAsync()
                                         .Result.Split("&");

                    //split by = to get acual values
                    accessTokenResponse = new UserModelDto
                    {
                        Token       = responseString[0].Split("=")[1],
                        TokenSecret = responseString[1].Split("=")[1],
                        UserId      = responseString[2].Split("=")[1],
                        Username    = responseString[3].Split("=")[1]
                    };
                }
            }
            catch (Exception ex)
            {
            }

            return(accessTokenResponse);
        }
Esempio n. 15
0
        public async Task <OAuthResponse> GetRequestTokenAsync(OAuthRequest oauthRequest)
        {
            var scopes  = _options.DefaultScopes.ToScopes();
            var request = GetBaseRequest(oauthRequest, $"{_options.UsosEndpoints.RequestToken}?scopes={scopes}");

            var response = await SendRequestAsync(request);

            return(await ParseTokenResponseAsync(response.Content));
        }
Esempio n. 16
0
        public NameValueCollection GetOAuthToken(string consumerKey, string consumerSecret, string oauthToken, string oauthVerifier)
        {
            // Creating a new instance with a helper method
            var oAuthRequest = OAuthRequest.ForAccessToken(consumerKey, consumerSecret, oauthToken, "", oauthVerifier);

            oAuthRequest.RequestUrl = "https://api.twitter.com/oauth/access_token";

            return(HttpUtility.ParseQueryString(ExecuteRequest(GetRequest(oAuthRequest, new Dictionary <string, string>())).Content));
        }
Esempio n. 17
0
        private string GetAuthorizationHeader(Uri uri)
        {
            OAuthRequest client = OAuthRequest.ForProtectedResource("GET", "qLT42Pa4Pm7FxY4v7fqtBw", "s49oOJabVbS305j5yMVWcHOp3YX9XExl8pUHEv9g", "39523825-pCBfpmVcbyopUEXtwdOmMERq7VMtPk937YKO911tj", "E2EpHYquZTRJ3NYLK9JYeGN0jGD5P8jH9bQHtdFb7JI");

            client.RequestUrl = uri.AbsoluteUri;

            var authorizationHeader = client.GetAuthorizationHeader();

            return(authorizationHeader);
        }
Esempio n. 18
0
        public string GetOAuthRedirect(string consumerKey, string consumerSecret, string callbackUrl)
        {
            // Creating a new instance with a helper method
            var oAuthRequest = OAuthRequest.ForRequestToken(consumerKey, consumerSecret, callbackUrl);

            oAuthRequest.RequestUrl = "https://api.twitter.com/oauth/request_token";
            var qscoll = OAuthQuery(oAuthRequest);

            return(string.Format("https://api.twitter.com/oauth/authorize?oauth_token={0}", qscoll["oauth_token"]));
        }
Esempio n. 19
0
        private NameValueCollection OAuthQuery(OAuthRequest oAuthRequest)
        {
            var auth    = oAuthRequest.GetAuthorizationHeader();
            var request = new Common.Http.HttpRequest(oAuthRequest.RequestUrl);

            request.Headers.Add("Authorization", auth);
            var response = _httpClient.Get(request);

            return(HttpUtility.ParseQueryString(response.Content));
        }
Esempio n. 20
0
        public string GetOAuthRedirect(string consumerKey, string consumerSecret, string callbackUrl)
        {
            // Creating a new instance with a helper method
            var oAuthRequest = OAuthRequest.ForRequestToken(consumerKey, consumerSecret, callbackUrl);

            oAuthRequest.RequestUrl = "https://api.twitter.com/oauth/request_token";
            var qscoll = HttpUtility.ParseQueryString(ExecuteRequest(GetRequest(oAuthRequest, new Dictionary <string, string>())).Content);

            return(string.Format("https://api.twitter.com/oauth/authorize?oauth_token={0}", qscoll["oauth_token"]));
        }
Esempio n. 21
0
        public static bool UpdateLocation(HttpContext context, Location location, Uri callback)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (location == null)
            {
                throw new ArgumentNullException("location");
            }

            if (callback == null)
            {
                throw new ArgumentNullException("callback");
            }

            // Update the user's location
            var request = OAuthRequest.Create(
                new EndPoint("https://fireeagle.yahooapis.com/api/0.1/update", "POST"),
                FireEagle.OAuthService,
                callback,
                HttpContext.Current.Session.SessionID);

            request.VerificationHandler = AspNetOAuthRequest.HandleVerification;

            // Send the location latitude and longitude with the request
            OAuthResponse response = request.GetResource(
                new NameValueCollection()
            {
                { "lat", location.Point.Latitude.ToString(CultureInfo.InvariantCulture) },
                { "lon", location.Point.Longitude.ToString(CultureInfo.InvariantCulture) }
            });

            if (!response.HasProtectedResource)
            {
                throw new AuthorizationRequiredException()
                      {
                          AuthorizationUri = FireEagle.OAuthService.BuildAuthorizationUrl(response.Token)
                      }
            }
            ;

            // Store the access token
            context.Session["access_token"] = response.Token;

            // Load the response XML
            XmlDocument responseXml = new XmlDocument();

            responseXml.Load(response.ProtectedResource.GetResponseStream());

            // Check the response status
            return(responseXml.SelectSingleNode("rsp/@stat").Value == "ok");
        }
    }
Esempio n. 22
0
        public override object RequestAction(string action, IDictionary <string, string> query)
        {
            if (action == "startOAuth")
            {
                if (query["callbackUrl"].IsNullOrWhiteSpace())
                {
                    throw new BadRequestException("QueryParam callbackUrl invalid.");
                }

                var oAuthRequest = OAuthRequest.ForRequestToken(null, null, query["callbackUrl"]);
                oAuthRequest.RequestUrl = Settings.OAuthRequestTokenUrl;
                var qscoll = OAuthQuery(oAuthRequest);

                var url = string.Format("{0}?oauth_token={1}&oauth_callback={2}", Settings.OAuthUrl, qscoll["oauth_token"], query["callbackUrl"]);

                return(new
                {
                    OauthUrl = url,
                    RequestTokenSecret = qscoll["oauth_token_secret"]
                });
            }
            else if (action == "getOAuthToken")
            {
                if (query["oauth_token"].IsNullOrWhiteSpace())
                {
                    throw new BadRequestException("QueryParam oauth_token invalid.");
                }

                if (query["requestTokenSecret"].IsNullOrWhiteSpace())
                {
                    throw new BadRequestException("Missing requestTokenSecret.");
                }

                var oAuthRequest = OAuthRequest.ForAccessToken(null, null, query["oauth_token"], query["requestTokenSecret"], "");
                oAuthRequest.RequestUrl = Settings.OAuthAccessTokenUrl;
                var qscoll = OAuthQuery(oAuthRequest);

                Settings.AccessToken       = qscoll["oauth_token"];
                Settings.AccessTokenSecret = qscoll["oauth_token_secret"];

                var user = GetUser(Settings.UserId);

                return(new
                {
                    Settings.AccessToken,
                    Settings.AccessTokenSecret,
                    RequestTokenSecret = "",
                    UserId = user.Item1,
                    UserName = user.Item2
                });
            }

            return(new { });
        }
        private HttpWebResponse ConsumerHandshake(OAuthRequest client, string jsessionid, string setCookieHeader, string domain)
        {
            var authReq =
                (HttpWebRequest)
                WebRequest.Create(serviceConfig.ServerRoot + AcsApiClientConfig.AuthUrl + "?" + OauthTokenKey + "=" +
                                  HttpUtility.UrlEncode(client.Token));

            authReq.AllowAutoRedirect = false;
            authReq.CookieContainer   = new CookieContainer();

            authReq.CookieContainer.Add(new Cookie(SessionIdKey.ToUpper(), jsessionid)
            {
                Domain = domain
            });
            authReq.CookieContainer.Add(new Cookie(ConsumerTypeIdKey, ConsumerTypeValue)
            {
                Domain = domain
            });

            cookies.Add(new Cookie(ConsumerTypeIdKey, ConsumerTypeValue, "/", domain));

            CookieCollection newRequiredCookies = new CookieCollection();

            try
            {
                newRequiredCookies = AcsApiSetCookieHeaderParser.GetAllCookiesFromHeader(setCookieHeader,
                                                                                         new Uri(serviceConfig.ServerRoot).Host);
            }
            catch (Exception e)
            {
                throw new AcsApiException("Could not parse cookie for final request!");
            }
            RefreshCookies(newRequiredCookies, authReq);

            HttpWebResponse authReqResp;

            try
            {
                authReqResp = authReq.GetResponse() as HttpWebResponse;
            }
            catch (WebException wex)
            {
                throw new AcsApiException(AcsApiError.ServerError.ToString(), wex);
            }

            // bbax: response streams being closed while dealing with exceptions... yey..
            // todo: clean this up more...
            if (authReqResp?.Headers == null)
            {
                authReqResp?.Close();
                throw new AcsApiException(AcsApiError.CouldNotLogin);
            }
            return(authReqResp);
        }
Esempio n. 24
0
        private static string GetRequestToken(string url)
        {
            OAuthRequest client = OAuthRequest.ForRequestToken(ConsumerKey, ConsumerSecret);

            client.RequestUrl      = url;
            client.Method          = "POST";
            client.SignatureMethod = OAuthSignatureMethod.HmacSha1;
            string urlRet = client.GetAuthorizationQuery();

            return(url + '?' + urlRet);
        }
Esempio n. 25
0
        public async Task <RestResponse <OAuthData> > LoginAsync(OAuthRequest request)
        {
            request.Header("Accept-Language", CultureInfo.CurrentCulture.TwoLetterISOLanguageName);
            var response = await request.ToResponseAsync();

            if (response.IsSuccessStatusCode)
            {
                Login(response.DeserializedResponse.Username, response.DeserializedResponse.AccessToken);
            }
            return(response);
        }
Esempio n. 26
0
        private HttpRequest GetRequest(OAuthRequest oAuthRequest, Dictionary <string, string> customParams)
        {
            var auth    = oAuthRequest.GetAuthorizationHeader(customParams);
            var request = new HttpRequest(oAuthRequest.RequestUrl);

            request.Headers.Add("Authorization", auth);

            request.Method = oAuthRequest.Method == "POST" ? HttpMethod.Post : HttpMethod.Get;

            return(request);
        }
        public Task <HttpResponseMessage> GetResponse(string url, User user)
        {
            var client = OAuthRequest.ForProtectedResource("GET",
                                                           user.ConsumerKey, user.ConsumerSecret, user.TokenValue, user.TokenSecret);

            client.RequestUrl = URL_PREFIX + url;

            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", client.GetAuthorizationHeader());
            return(httpClient.GetAsync(client.RequestUrl));
        }
Esempio n. 28
0
        public IActionResult Authenticate(OAuthRequest request)
        {
            Console.WriteLine("Received GitHub intall: '{0}', '{1}'", request.code, request.state);
            OAuthResponse response = RequestAccessToken(request.code, request.state);

            Console.WriteLine("Received GitHub OAuth: '{0}', '{1}'", request.code, response.access_token);
            UserManager.Instance.AddGitHubAuth(request.state, response.access_token);

            Response.Headers["REFRESH"] = String.Format("3;URL={0}", _options.WEBSITE_BASE_URL); // Redirect to the base URL after three seconds

            return(Ok("Successfully authenticated. Now redirecting..."));
        }
Esempio n. 29
0
        private async Task <List <UsosUser> > GetCourseEditionUsers(OAuthRequest oauthRequest, string termId, string field)
        {
            var request = GetBaseRequest(oauthRequest, $"{_options.UsosEndpoints.CoursesCourseEdition}?course_id={GetCourseCode()}&term_id={termId}&fields={field}");

            var response = await SendRequestAsync(request);

            var value = await response.Content.ReadAsStringAsync();

            var users = JsonConvert.DeserializeObject <Dictionary <string, UsosUser[]> >(value);

            return(users.GetValueOrDefault(field).ToList());
        }
Esempio n. 30
0
        public async Task <string> GetCourseUrl(OAuthRequest oauthRequest, string courseId)
        {
            var field    = "profile_url";
            var request  = GetBaseRequest(oauthRequest, $"{_options.UsosEndpoints.CoursesCourse}?course_id={courseId}&fields={field}");
            var response = await SendRequestAsync(request);

            var data = await response.Content.ReadAsStringAsync();

            var url = JsonConvert.DeserializeObject <Dictionary <string, string> >(data).GetValueOrDefault(field);

            return(url);
        }
Esempio n. 31
0
    protected void lnkbtnGoogleClick(object sender, EventArgs e)
    {
        var oAuthRequest = new OAuthRequest {
            Provider = OAuthRequest.Providers.Google
        };
        var parameters = new FetchParameters();

        parameters.OpenidUserInformation.Add(RequestParameters.AxSchemaParams.Contact.email);
        parameters.OpenidUserInformation.Add(RequestParameters.AxSchemaParams.NamePerson.First);
        parameters.OpenidUserInformation.Add(RequestParameters.AxSchemaParams.NamePerson.Last);
        oAuthRequest.CreateRequest(parameters);
    }
Esempio n. 32
0
        public void Can_get_request_token_with_http_header()
        {
            var client = new OAuthRequest
                             {
                                 Method = "GET",
                                 ConsumerKey = _consumerKey,
                                 ConsumerSecret = _consumerSecret,
                                 RequestUrl = string.Format(BaseUrl, "request_token")
                             };

            var auth = client.GetAuthorizationHeader();
            
            var request = (HttpWebRequest) WebRequest.Create(client.RequestUrl);
            
            request.Headers.Add("Authorization", auth);

            var response = (HttpWebResponse) request.GetResponse();

            Assert.IsNotNull(response);

            Assert.AreEqual(200, (int)response.StatusCode);
        }
Esempio n. 33
0
            public OAuthRequest TwitterStatusUpdateRequest(
                String status,
                String access_token,
                String access_token_secret,
                String consumer_key,
                String consumer_secret)
            {
                System.Net.ServicePointManager.Expect100Continue = false;

                if (String.IsNullOrEmpty(status))
                    return null;

                String suffix = "...";
                if (status.Length > MAX_STATUS_LENGTH)
                    status = status.Substring(0, MAX_STATUS_LENGTH - suffix.Length) + suffix;

                OAuthRequest orequest = new OAuthRequest(plugin, "http://api.twitter.com/1/statuses/update.json");
                orequest.Method = HTTPMethod.POST;
                orequest.request.ContentType = "application/x-www-form-urlencoded";

                /* Set the Post Data */

                byte[] data = Encoding.UTF8.GetBytes("status=" + OAuthRequest.UrlEncode(Encoding.UTF8.GetBytes(status)));

                // Parameters required by the Twitter OAuth Protocol
                orequest.parameters.Add(new KeyValuePair<string, string>("oauth_consumer_key", consumer_key));
                orequest.parameters.Add(new KeyValuePair<string, string>("oauth_nonce", Guid.NewGuid().ToString("N")));
                orequest.parameters.Add(new KeyValuePair<string, string>("oauth_signature_method", "HMAC-SHA1"));
                orequest.parameters.Add(new KeyValuePair<string, string>("oauth_token", access_token));
                orequest.parameters.Add(new KeyValuePair<string, string>("oauth_timestamp", ((long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds).ToString()));
                orequest.parameters.Add(new KeyValuePair<string, string>("oauth_version", "1.0"));
                orequest.parameters.Add(new KeyValuePair<string, string>("status", OAuthRequest.UrlEncode(Encoding.UTF8.GetBytes(status))));

                // Compute and add the signature
                String signature = orequest.Signature(consumer_secret, access_token_secret);
                orequest.parameters.Add(new KeyValuePair<string, string>("oauth_signature", OAuthRequest.UrlEncode(signature)));

                // Add the OAuth authentication header
                String OAuthHeader = orequest.Header();
                orequest.request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequired;
                orequest.request.Headers["Authorization"] = OAuthHeader;

                // Add the POST body
                orequest.request.ContentLength = data.Length;
                Stream sout = orequest.request.GetRequestStream();
                sout.Write(data, 0, data.Length);
                sout.Close();

                return orequest;
            }
Esempio n. 34
0
            public OAuthRequest TwitterRequestTokenRequest()
            {
                OAuthRequest orequest = new OAuthRequest(plugin, "http://api.twitter.com/oauth/request_token");
                orequest.Method = HTTPMethod.POST;
                orequest.request.ContentLength = 0;

                // Parameters required by the Twitter OAuth Protocol
                orequest.parameters.Add(new KeyValuePair<string, string>("oauth_callback", OAuthRequest.UrlEncode("oob")));
                orequest.parameters.Add(new KeyValuePair<string, string>("oauth_consumer_key", twitter_consumer_key));
                orequest.parameters.Add(new KeyValuePair<string, string>("oauth_nonce", Guid.NewGuid().ToString("N")));
                orequest.parameters.Add(new KeyValuePair<string, string>("oauth_timestamp", ((long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds).ToString()));
                orequest.parameters.Add(new KeyValuePair<string, string>("oauth_signature_method", "HMAC-SHA1"));
                orequest.parameters.Add(new KeyValuePair<string, string>("oauth_version", "1.0"));

                // Compute and add the signature
                String signature = orequest.Signature(twitter_consumer_secret, null);
                orequest.parameters.Add(new KeyValuePair<string, string>("oauth_signature", OAuthRequest.UrlEncode(signature)));

                // Add the OAuth authentication header
                String OAuthHeader = orequest.Header();
                orequest.request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequired;
                orequest.request.Headers["Authorization"] = OAuthHeader;

                return orequest;
            }
Esempio n. 35
0
 public void CreateRequest_ValidUnknownParameter()
 {
     var request = new OAuthRequest();
     request.AddHeaderParameter("oauth_undefined", "value");
 }
Esempio n. 36
0
 public void CreateRequest_ValidKnownParameter()
 {
     var request = new OAuthRequest();
     request.AddHeaderParameter("oauth_callback", "value");
 }
Esempio n. 37
0
 public void CreateRequest_InvalidMethod()
 {
     var request = new OAuthRequest { Method = "INVALID" };
 }
Esempio n. 38
0
 public void CreateRequest_InvalidHeaderParameter()
 {
     var request = new OAuthRequest();
     request.AddHeaderParameter("is_not_valid", "value");
 }
Esempio n. 39
0
 public void CreateRequest_EmptyMethod()
 {
     var request = new OAuthRequest {Method = string.Empty};
 }
Esempio n. 40
0
 public void CreateRequest()
 {
     var request = new OAuthRequest { Method = "POST" };
     Assert.NotNull(request);
 }