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)); }
/// <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); } } }
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); }
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); }
// 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); } }
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(',')); }
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); } }
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); } }
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); }
public async Task <OAuthResponse> GetAccessTokenAsync(OAuthRequest oauthRequest) { var request = GetBaseRequest(oauthRequest, _options.UsosEndpoints.AccessToken); var response = await SendRequestAsync(request); return(await ParseTokenResponseAsync(response.Content)); }
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); }
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)); }
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)); }
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); }
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"])); }
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)); }
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"])); }
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"); } }
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); }
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); }
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); }
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)); }
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...")); }
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()); }
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); }
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); }
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); }
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; }
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; }
public void CreateRequest_ValidUnknownParameter() { var request = new OAuthRequest(); request.AddHeaderParameter("oauth_undefined", "value"); }
public void CreateRequest_ValidKnownParameter() { var request = new OAuthRequest(); request.AddHeaderParameter("oauth_callback", "value"); }
public void CreateRequest_InvalidMethod() { var request = new OAuthRequest { Method = "INVALID" }; }
public void CreateRequest_InvalidHeaderParameter() { var request = new OAuthRequest(); request.AddHeaderParameter("is_not_valid", "value"); }
public void CreateRequest_EmptyMethod() { var request = new OAuthRequest {Method = string.Empty}; }
public void CreateRequest() { var request = new OAuthRequest { Method = "POST" }; Assert.NotNull(request); }