private string GetResponse(string urlWithParameters, string userToken, string userSecret) { string normalizedRequestParameters; string normalizedUrl; OAuthBase oAuthBase = new OAuthBase(); var timestamp = oAuthBase.GenerateTimeStamp(); var nonce = oAuthBase.GenerateNonce(); var signature = oAuthBase.GenerateSignature(new Uri(urlWithParameters), _consumerCredentials.ConsumerKey, _consumerCredentials.ConsumerSecret, userToken, userSecret, "GET", timestamp, nonce, out normalizedUrl, out normalizedRequestParameters, new Dictionary<string, string>()); var signedUrl = string.Format("{0}?{1}&oauth_signature={2}", normalizedUrl, normalizedRequestParameters, signature); var request = HttpWebRequest.Create(signedUrl); var webResponse = request.GetResponse(); using (var responseStream = new StreamReader(webResponse.GetResponseStream())) { return responseStream.ReadToEnd(); } }
/// <summary> /// Gets the preview url for a sample of the song. /// Jennifer Lopez - Jenny from the Block's track id is 19589723 /// </summary> /// <param name="trackId">Track Id to get preview url for.</param> /// <returns></returns> public string GetTrackPreviewUrl(int trackId) { var url = "http://previews.7digital.com/clip/" + trackId.ToString() + "?country=US"; var oauth = new OAuthBase(); var previewUrl = oauth.GetSignedUrl(url, _thirdPartySettings.SevenDigitalOAuthConsumerKey, _thirdPartySettings.SevenDigitalOAuthConsumerSecret); return previewUrl; }
public String GetOAuthAuthorizationHeader(String resourceUrl, OAuthConsumerContext conContext, OAuthToken accessToken, Dictionary<String, String> parameter, String method) { var oAuth = new OAuthBase(); String normalizedUrl; String normalizedRequestParameters; var timestamp = oAuth.GenerateTimeStamp(); var nonce = oAuth.GenerateNonce(); var signature = oAuth.GenerateSignature(new Uri(resourceUrl), conContext.ConsumerKey, conContext.ConsumerSecret, accessToken == null ? string.Empty : accessToken.TokenKey, accessToken == null ? string.Empty : accessToken.TokenSecret, method, timestamp, nonce, conContext.SignatureMethod, out normalizedUrl, out normalizedRequestParameters); signature = HttpUtility.UrlEncode(signature); var sb = new StringBuilder("OAuth"); sb.Append(", oauth_version=1.0"); sb.AppendFormat(", oauth_nonce={0}", nonce); sb.AppendFormat(", oauth_timestamp={0}", timestamp); sb.AppendFormat(", oauth_consumer_key={0}", conContext.ConsumerKey); if (accessToken != null) { sb.AppendFormat(", , oauth_token={0}", accessToken.TokenKey); } sb.Append(", oauth_signature_method=\"HMAC-SHA1\""); sb.AppendFormat(", oauth_signature={0}", signature); return sb.ToString(); }
public void getImageOAuth() { string consumerKey = "HJFMg2LvexMhIKrDs2qaVUxNem27kAxhdfiAYJMW"; string consumerSecret = "mPdJjtpeyXvRaUQaAaHP7KJMOWWAh8NfSf3T5NuO"; Uri uri = new Uri("https://api.500px.com/v1/users"); Uri requestToken = new Uri("https://api.500px.com/v1/oauth/request_token"); Uri accessToken = new Uri("https://api.500px.com/v1/oauth/access_token"); Uri authorizeURL = new Uri("https://api.500px.com/v1/oauth/authorize"); OAuthBase oAuth = new OAuthBase(); string nonce = oAuth.GenerateNonce(); string timeStamp = oAuth.GenerateTimeStamp(); string o1 = ""; string o2 = ""; string sig = oAuth.GenerateSignature(uri, consumerKey, consumerSecret, string.Empty, string.Empty, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out o1, out o2); sig = HttpUtility.UrlEncode(sig); StringBuilder sb = new StringBuilder(uri.ToString()); sb.AppendFormat("?oauth_consumer_key={0}&", consumerKey); sb.AppendFormat("oauth_nonce={0}&", nonce); sb.AppendFormat("oauth_timestamp={0}&", timeStamp); sb.AppendFormat("oauth_signature_method={0}&", "HMAC-SHA1"); sb.AppendFormat("oauth_version={0}&", "1.0"); sb.AppendFormat("oauth_signature={0}", sig); System.Diagnostics.Debug.WriteLine(sb.ToString()); }
/// <summary> /// リクエスト ヘッダー文字列を生成します。 /// </summary> /// <param name="context">リクエストに使用されるトークンセット。</param> /// <param name="method"></param> /// <param name="requestUrl"></param> /// <param name="queryDictionary"></param> /// <returns></returns> public static string GenerateRequestHeader(TwitterContext context, string method, string requestUrl, StringDictionary queryDictionary = null) { Debug.WriteLine("-\t## リクエスト ヘッダーを構築します"); string header = String.Empty; string headerParams = String.Empty; var oauth = new OAuthBase(); string nonce = oauth.GenerateNonce(); string timeStamp = oauth.GenerateTimeStamp(); var paramDictionary = new SortedDictionary<string, string>(); AddPercentEncodedItem(paramDictionary, "oauth_consumer_key", context.ConsumerKey); AddPercentEncodedItem(paramDictionary, "oauth_nonce", nonce); AddPercentEncodedItem(paramDictionary, "oauth_signature", GenerateSignature(context, method, requestUrl, nonce, "HMAC-SHA1", timeStamp, "1.0", queryDictionary)); AddPercentEncodedItem(paramDictionary, "oauth_signature_method", "HMAC-SHA1"); AddPercentEncodedItem(paramDictionary, "oauth_timestamp", timeStamp); AddPercentEncodedItem(paramDictionary, "oauth_token", context.AccessToken != null ? context.AccessToken : null); AddPercentEncodedItem(paramDictionary, "oauth_version", "1.0"); foreach (var kvp in paramDictionary) { if (kvp.Value != null) headerParams += (headerParams.Length > 0 ? ", " : String.Empty) + kvp.Key + "=\"" + kvp.Value + "\""; } header = "OAuth " + headerParams; Debug.WriteLine("-\t## リクエスト ヘッダー構築完了: [Authorization] " + header); return header; }
public void GenerateSignatureTest() { OAuthBase target = new OAuthBase(); // TODO: Initialize to an appropriate value Uri url = null; // TODO: Initialize to an appropriate value string consumerKey = string.Empty; // TODO: Initialize to an appropriate value string consumerSecret = string.Empty; // TODO: Initialize to an appropriate value string token = string.Empty; // TODO: Initialize to an appropriate value string tokenSecret = string.Empty; // TODO: Initialize to an appropriate value string verifier = string.Empty; // TODO: Initialize to an appropriate value string httpMethod = string.Empty; // TODO: Initialize to an appropriate value string timeStamp = string.Empty; // TODO: Initialize to an appropriate value string nonce = string.Empty; // TODO: Initialize to an appropriate value OAuthBase.SignatureTypes signatureType = new OAuthBase.SignatureTypes(); // TODO: Initialize to an appropriate value string normalizedUrl = string.Empty; // TODO: Initialize to an appropriate value string normalizedUrlExpected = string.Empty; // TODO: Initialize to an appropriate value string normalizedRequestParameters = string.Empty; // TODO: Initialize to an appropriate value string normalizedRequestParametersExpected = string.Empty; // TODO: Initialize to an appropriate value string expected = string.Empty; // TODO: Initialize to an appropriate value string actual; actual = target.GenerateSignature(url, consumerKey, consumerSecret, token, tokenSecret, verifier, httpMethod, timeStamp, nonce, signatureType, out normalizedUrl, out normalizedRequestParameters); Assert.AreEqual(normalizedUrlExpected, normalizedUrl); Assert.AreEqual(normalizedRequestParametersExpected, normalizedRequestParameters); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
public string GetRequestTokenResponse() { var client = new WebClient(); string baseuristr = "http://api.netflix.com/oauth/request_token"; Uri baseUri = new Uri(baseuristr); var OAuth = new OAuthBase(); var timeStamp = OAuth.GenerateTimeStamp(); var nonce = OAuth.GenerateNonce(); var QStr = string.Format("?oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method=HMAC-SHA1&oauth_timestamp={2}&oauth_version=1.0", ConsumerKey, nonce, timeStamp); var baseUrlwithQStr = baseuristr + QStr; var oauth_signature = OAuth.GenerateSignature(baseUri, ConsumerKey, SharedSecret, "", "", "GET", timeStamp, nonce, out baseuristr, out QStr); var finalUrl = string.Format("{0}&oauth_signature={1}", baseUrlwithQStr, OAuth.UrlEncode(oauth_signature)); for (var a = 0; a < 5; a++) { try { return client.DownloadString(finalUrl); } catch (Exception e) { if (a == 4) { throw e; } } } return ""; }
public string GetAccessTokenResponse(string token, string tokenSecret) { var client = new WebClient(); string baseuristr = "http://api.netflix.com/oauth/access_token"; Uri baseUri = new Uri(baseuristr); var OAuth = new OAuthBase(); var timeStamp = OAuth.GenerateTimeStamp(); var nonce = OAuth.GenerateNonce(); var QStr = string.Format("?oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method=HMAC-SHA1&oauth_timestamp={2}&oauth_version=1.0" + "&oauth_token={3}", ConsumerKey, nonce, timeStamp, token); var baseUrlwithQStr = baseuristr + QStr; var oauth_signature = OAuth.GenerateSignature(baseUri, ConsumerKey, SharedSecret, token, tokenSecret, "GET", timeStamp, nonce, out baseuristr, out QStr); var finalUrl = string.Format("{0}&oauth_signature={1}", baseUrlwithQStr, OAuth.UrlEncode(oauth_signature)); for (var a = 0; a <= 20; a++) { try { return client.DownloadString(finalUrl); } catch (Exception e) { if (a == 20) { throw e; } } } return ""; //http://api.netflix.com/oauth/access_token?oauth_consumer_key=e99kjwajtpcyjfpgvt3amzts&oauth_nonce=2652002&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1341449398&oauth_version=1.0oauth_token=ftkkv968chcywzr9ugr4h7ze&oauth_signature=IujYO5+zuuNp+zN11Xe+K9Puhps= //http://api.netflix.com/oauth/access_token?oauth_consumer_key=e99kjwajtpcyjfpgvt3amzts&oauth_nonce=249946915344920&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1341447989&oauth_token=yaqg4cfepwn7zvpq7hzka9v8&oauth_version=1.0&oauth_signature=JdH%2F4xaKl4nHdyP%2F%2FYouofAJCTQ%3D }
public string GetAccessTokenForPortalUser(string username, string password, BaseConst.Realm realm, string consumerKey, string consumerSecret) { OAuthBase oAuth = new OAuthBase(); string url = GetTokenURI(realm, BaseConst.PortalAccessTokenURL); string creds = OAuthBase.BuildCredentials(username, password); string results = null; //begin WebResponse webResponse = GetWebResponse(realm, OAuthBase.HMACSHA1SignatureType, "appliation/xml", "POST", url, creds, consumerKey, consumerSecret); StreamReader sr = new StreamReader(webResponse.GetResponseStream()); if (webResponse.Headers["oauth_token"] != null) { AccessToken = webResponse.Headers["oauth_token"].ToString(); } if (webResponse.Headers["oauth_token_secret"] != null) { AccessTokenSecret = webResponse.Headers["oauth_token_secret"].ToString(); } results = sr.ReadToEnd().Trim(); webResponse.Close(); //end return results; }
/// <summary> /// Retrieve the URL that the client should redirect the user to to perform the OAuth authorization /// </summary> /// <param name="provider"></param> /// <returns></returns> protected override string GetAuthorizationUrl(String callbackUrl) { OAuthBase auth = new OAuthBase(); String requestUrl = provider.Host + provider.RequestTokenUrl; Uri url = new Uri(requestUrl); String requestParams = ""; String signature = auth.GenerateSignature(url, provider.ClientId, provider.Secret, null, null, provider.RequestTokenMethod ?? "POST", auth.GenerateTimeStamp(), auth.GenerateTimeStamp() + auth.GenerateNonce(), out requestUrl, out requestParams, new OAuthBase.QueryParameter(OAuthBase.OAuthCallbackKey, auth.UrlEncode(callbackUrl))); requestParams += "&oauth_signature=" + HttpUtility.UrlEncode(signature); WebClient webClient = new WebClient(); byte[] response; if (provider.RequestTokenMethod == "POST" || provider.RequestTokenMethod == null) { response = webClient.UploadData(url, Encoding.ASCII.GetBytes(requestParams)); } else { response = webClient.DownloadData(url + "?" + requestParams); } Match m = Regex.Match(Encoding.ASCII.GetString(response), "oauth_token=(.*?)&oauth_token_secret=(.*?)&oauth_callback_confirmed=true"); String requestToken = m.Groups[1].Value; String requestTokenSecret = m.Groups[2].Value; // we need a way to save the request token & secret, so that we can use it to get the access token later (when they enter the pin) // just stick it in the session for now HttpContext.Current.Session[OAUTH1_REQUEST_TOKEN_SESSIONKEY] = requestToken; HttpContext.Current.Session[OAUTH1_REQUEST_TOKEN_SECRET_SESSIONKEY] = requestTokenSecret; return provider.Host + provider.UserApprovalUrl + "?oauth_token=" + HttpUtility.UrlEncode(requestToken); }
/// <summary> /// A constructor that take the consumer key, consumer secret and signature method. /// </summary> /// <param name="consumerKey">Consumer key</param> /// <param name="consumerSecret">Consumer secret</param> /// <param name="signatureMethod">Signature encryption method</param> public OAuthConsumer(string consumerKey, string consumerSecret, OAuthBase.SignatureTypes signatureMethod) { this.consumerKey = consumerKey; this.consumerSecret = consumerSecret; this.signatureMethod = signatureMethod; oAuth = new OAuthBase(); }
/// <summary> /// A constructor that only takes the encryption method. The consumer key /// and secret are defaulted to string.Empty. /// </summary> /// <param name="signatureMethod">The signature encryption method</param> public OAuthConsumer(OAuthBase.SignatureTypes signatureMethod) { consumerKey = string.Empty; consumerSecret = string.Empty; this.signatureMethod = signatureMethod; oAuth = new OAuthBase(); }
/// <summary> /// A Parameterless constructor. Defaults the consumer key and secret to string.Empty /// and the encryption method to HMAC-SHA1. /// </summary> public OAuthConsumer() { consumerKey = string.Empty; consumerSecret = string.Empty; signatureMethod = OAuthBase.SignatureTypes.HMACSHA1; oAuth = new OAuthBase(); }
public HttpWebRequest CreateAuthorizedRequest(string url, string requestMethod, ApiFilter filter,string act, string atsc) { AccessToken = act; AccessTokenSecret = atsc; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + filter.ToString()); OAuthBase oAuth = new OAuthBase(); string nonce = oAuth.GenerateNonce(); string timeStamp = oAuth.GenerateTimeStamp(); string parameters; string normalizedUrl; string signature = oAuth.GenerateSignature(new Uri(url), ConsumerKey, ConsumerSecret, AccessToken, AccessTokenSecret, requestMethod, timeStamp, nonce, OAuthBase.SignatureTypes.PLAINTEXT, out normalizedUrl, out parameters); StringBuilder sb = new StringBuilder("OAuth "); sb.AppendFormat("oauth_token=\"{0}\",", AccessToken); sb.AppendFormat("oauth_version=\"{0}\",", "1.0"); sb.AppendFormat("oauth_signature_method=\"{0}\",", "PLAINTEXT"); sb.AppendFormat("oauth_nonce=\"{0}\",", nonce); sb.AppendFormat("oauth_timestamp=\"{0}\",", timeStamp); sb.AppendFormat("oauth_consumer_key=\"{0}\",", ConsumerKey); sb.AppendFormat("oauth_signature=\"{0}\"", signature); request.Headers[HttpRequestHeader.Authorization] = sb.ToString(); request.Method = requestMethod; //request.ContentType = "application/json"; request.Accept = "text/html,application/xhtml+xml,application/json,application/xml;q=0.9,*/*;q=0.8";//application/json, request.KeepAlive = true; return request; }
static private String GenerateSignedUrl(String baseRequestTokenUrl, String method, OAuthConsumerContext context, OAuthToken token) { String normalizedUrl; String normalizedRequestParameters; var oAuth = new OAuthBase(); string nonce = oAuth.GenerateNonce(); string timeStamp = oAuth.GenerateTimeStamp(); string sig = oAuth.GenerateSignature( new Uri(baseRequestTokenUrl), context.ConsumerKey, context.ConsumerSecret, token == null ? string.Empty : token.TokenKey, token == null ? string.Empty : token.TokenSecret, method.ToString(), timeStamp, nonce, context.SignatureMethod, out normalizedUrl, out normalizedRequestParameters); // // The signature as self has to be encoded to be ensure that no not url compatibale characters // will be used. The SHA1 hash can contain a bunch of this characters // sig = HttpUtility.UrlEncode(sig); var sb = new StringBuilder(normalizedUrl); sb.AppendFormat("?"); sb.AppendFormat(normalizedRequestParameters); sb.AppendFormat("&oauth_signature={0}", sig); return sb.ToString(); }
public void GenerateNonceTest() { OAuthBase target = new OAuthBase(); // TODO: Initialize to an appropriate value string expected = string.Empty; // TODO: Initialize to an appropriate value string actual; actual = target.GenerateNonce(); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
public OAuthMessageHandler(HttpMessageHandler handler, string apiKey, string appSecret, UserLogin login) : base(handler) { _apiKey = apiKey; _appSecret = appSecret; _login = login; _authBase = new OAuthBase(); }
private void BeginAuthorization() { var uri = new Uri("http://smeitproducts.com/magento-beta/oauth/initiate"); OAuthBase oAuth = new OAuthBase(); string nonce = oAuth.GenerateNonce(); string timeStamp = oAuth.GenerateTimeStamp(); string parameters; string normalizedUrl; string signature = oAuth.GenerateSignature(uri, ConsumerKey, ConsumerSecret, String.Empty, String.Empty, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.PLAINTEXT, out normalizedUrl, out parameters); StringBuilder requestUri = new StringBuilder(uri.ToString()); requestUri.AppendFormat("?oauth_consumer_key={0}&", ConsumerKey); requestUri.AppendFormat("oauth_callback={0}&", "http://localhost:4893/Default.aspx"); requestUri.AppendFormat("oauth_nonce={0}&", nonce); requestUri.AppendFormat("oauth_timestamp={0}&", timeStamp); requestUri.AppendFormat("oauth_signature_method={0}&", "PLAINTEXT"); requestUri.AppendFormat("oauth_version={0}&", "1.0"); requestUri.AppendFormat("oauth_signature={0}", signature); var imgclient = new RestClient(requestUri.ToString()); var imgrequest = new RestSharp.RestRequest(RestSharp.Method.POST) { RequestFormat = RestSharp.DataFormat.Xml }; var imgresponse = imgclient.Execute(imgrequest); var dd = imgresponse.Content; string[] res = dd.Split('&'); string tok = res[0]; string[] authToken = tok.Split('='); string tok2 = res[1]; string[] authToken2 = tok2.Split('='); Session["oauth_token_secret"] = authToken2[1]; string redirectUrl = "http://smeitproducts.com/magento-beta/index.php/admin/oauth_authorize?oauth_token=" + authToken[1]; Response.Redirect(redirectUrl); }
static string getSign(string strUri, string consumerKey, string consumerSecret) { var uri = new Uri(strUri); string url, param; var oAuth = new OAuthBase(); var nonce = oAuth.GenerateNonce(); var timeStamp = oAuth.GenerateTimeStamp(); var signature = oAuth.GenerateSignature(uri, consumerKey, consumerSecret, string.Empty, string.Empty, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out url, out param); return string.Format("{0}?{1}&oauth_signature={2}", url, param, signature); }
internal static String GenerateOAuthUrl(OAuthConsumer consumer, OAuthToken token, Dictionary<String, String> additionalFields, String baseUrl) { var oauth = new OAuthBase(); string timestamp = oauth.GenerateTimeStamp(); string nonce = oauth.GenerateNonce(); string normUrl; string normParms; string url = String.Format("{0}?{1}", baseUrl, GetQueryString(additionalFields)); var uri = new Uri(url); var signature = oauth.GenerateSignature(uri, consumer.Key, consumer.Secret, token.Key, token.Secret, "GET", timestamp, nonce, out normUrl, out normParms); return String.Format("{0}?{1}&oauth_signature={2}", normUrl, normParms, OAuthBase.UrlEncode(signature)); }
private bool checkTokens() { if(tokens.Count<1) return false; WebClient wc = new WebClient(); OAuthBase ooo = new OAuthBase(); string normalizedUrl = ""; string normalizedRequestParameters = ""; string adr = "https://api.flickr.com/services/rest" + "?nojsoncallback=1" + "&format=json" + "&oauth_consumer_key="+Consumer_Key + "&oauth_signature_method=HMAC-SHA1" + "&oauth_version=1.0" + "&method=flickr.auth.oauth.checkToken"; string strSignature = ooo.GenerateSignature(new Uri(adr), Consumer_Key, Consumer_Secret, tokens["oauth_token"], tokens["oauth_token_secret"], "GET", ooo.GenerateTimeStamp(), ooo.GenerateNonce(), out normalizedUrl, out normalizedRequestParameters); string address = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + strSignature; label1.Text = strSignature; try { string str = wc.DownloadString(address); if (!str.Equals("")) { foreach (string s in str.Split('&')) { string[] kv = s.Split('='); //tokens.Add(kv[0], kv[1]); } return true; } } catch (Exception ex) { string sksks = ex.Message; label1.Text = sksks; } return false; }
private static Dictionary<string, string> SetupHeaders(Decimal TwitterAccountID) { string format = "OAuth realm=\"{0}\", oauth_consumer_key=\"{1}\", oauth_signature_method=\"HMAC-SHA1\", oauth_token=\"{2}\", oauth_timestamp=\"{3}\", oauth_nonce=\"{4}\", oauth_version=\"1.0\", oauth_signature=\"{5}\""; string str1 = "http://api.twitter.com/"; string uriString = "https://api.twitter.com/1/account/verify_credentials.json"; Dictionary<string, string> dictionary = new Dictionary<string, string>(); OAuthBase oauthBase = new OAuthBase(); string timeStamp = oauthBase.GenerateTimeStamp(); string nonce = oauthBase.GenerateNonce(); string normalizedUrl; string normalizedRequestParameters; string str2 = HttpUtility.UrlEncode(oauthBase.GenerateSignature(new Uri(uriString), SettingsData.Instance.TwitterConsumerKey, SettingsData.Instance.TwitterConsumerSecret, App.AppState.Accounts[TwitterAccountID].Settings.UserAuthToken, App.AppState.Accounts[TwitterAccountID].Settings.UserAuthSecret, "GET", timeStamp, nonce, out normalizedUrl, out normalizedRequestParameters)); string str3 = string.Format((IFormatProvider) CultureInfo.InvariantCulture, format, (object) str1, (object) SettingsData.Instance.TwitterConsumerKey, (object) App.AppState.Accounts[TwitterAccountID].Settings.UserAuthToken, (object) timeStamp, (object) nonce, (object) str2); dictionary.Add("X-App-Key", NestService.NestAPIKey); dictionary.Add("X-Auth-Service-Provider", uriString); dictionary.Add("X-Verify-Credentials-Authorization", str3); return dictionary; }
protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); string normReqUrl; string normReqParams; OAuthBase oAuth = new OAuthBase(); string nonce = oAuth.GenerateNonce(); string timeStamp = oAuth.GenerateTimeStamp(); Uri uri = new Uri("https://api.test.worapay.com/access/public?device_id=" + HttpUtility.UrlEncode("0123456789123456").ToUpper() + "&phone_number=" + HttpUtility.UrlEncode("0825532732").ToUpper() + "&version=1"); string sig = oAuth.GenerateSignature(uri, "R59qhvU27TgcDctQd7", "6duxju5QFM2ETgt2AaJvJ4kdTN4ktnFw", string.Empty, string.Empty, "POST", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out normReqUrl, out normReqParams); sig = HttpUtility.UrlEncode(sig); string data = normReqParams + "&oauth_signature=" + sig; var req = (HttpWebRequest)WebRequest.Create(normReqUrl); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; byte[] reqData = Encoding.UTF8.GetBytes(data); //byte[] reqData = Encoding.UTF8.GetBytes(""); req.ContentLength = reqData.Length; var handler = new HttpClientHandler { Credentials = new NetworkCredential("MyUSER", "MyPASS")}; var client = new HttpClient(handler); client.DefaultRequestHeaders.Add("ContentType", "application/x-www-form-urlencoded"); var response = await client.PostAsync(new Uri(normReqUrl), new ByteArrayContent(reqData)); }
/// <summary> /// Construct a URL for a given API call with the tokens returned from the last /// authorization or authentication call. Passing through the tokens is required in /// order to generate a signature that takes their values into account. /// </summary> /// <param name="baseUrl">The fully qualified base URL</param> /// <param name="requestType">A GET or PUT string</param> /// <param name="tokenString">OAuth token string</param> /// <param name="tokenStringSecret">OAuth token secret string</param> /// <returns>A URL string with the requested parameters</returns> public static string Uri(string baseUrl, string requestType, string tokenString, string tokenStringSecret) { string webUrl; string requestParam; string fullUrl = APIServer + baseUrl; OAuthBase oAuth = new OAuthBase(); string nonce = oAuth.GenerateNonce(); string timeStamp = oAuth.GenerateTimeStamp(); string sig = oAuth.GenerateSignature(new Uri(fullUrl), ConsumerKey, ConsumerSecret, tokenString, tokenStringSecret, requestType, timeStamp, nonce, out webUrl, out requestParam); sig = HttpUtility.UrlEncode(sig); return webUrl + "?" + requestParam + "&oauth_signature=" + sig; }
public string Search(string term, string location, int radiusInMiles) { radiusInMiles = NormalizeRadiusInMiles(radiusInMiles); var oauth = new OAuthBase(); var query = new Uri(String.Format("http://api.yelp.com/v2/search?term={0}&location={1}&radius_filter={2}", Uri.EscapeDataString(term), Uri.EscapeDataString(location), ConvertToMeters(radiusInMiles))); string url; string parameters; var signature = oauth.GenerateSignature(query, settings.ConsumerKey, settings.ConsumerSecret, settings.Token, settings.TokenSecret, "GET", oauth.GenerateTimeStamp(), oauth.GenerateNonce(), OAuthBase.SignatureTypes.HMACSHA1, out url, out parameters); using (var web = new WebClient()) { var newUrl = String.Format("{0}?{1}&oauth_signature={2}", url, parameters, Uri.EscapeDataString(signature)); return web.DownloadString(newUrl); } }
private static void GenerateOauthRequest(Context context, Uri baseUrl, string methodLocation, RestRequest request) { var consumerKey = string.IsNullOrEmpty(context.Authentication.Username) ? context.BitBucket.ConsumerKey : context.Authentication.Username; var consumerSecret = string.IsNullOrEmpty(context.Authentication.Password) ? context.BitBucket.ConsumerSecretKey : context.Authentication.Password; var oAuth = new OAuthBase(); var nonce = oAuth.GenerateNonce(); var timeStamp = oAuth.GenerateTimeStamp(); string normalizedUrl; string normalizedRequestParameters; var sig = oAuth.GenerateSignature(new Uri(baseUrl + methodLocation), consumerKey, consumerSecret, null, null, "GET", timeStamp, nonce, out normalizedUrl, out normalizedRequestParameters); request.Resource = string.Format(methodLocation); request.Method = Method.GET; request.AddParameter("oauth_consumer_key", consumerKey); request.AddParameter("oauth_nonce", nonce); request.AddParameter("oauth_timestamp", timeStamp); request.AddParameter("oauth_signature_method", "HMAC-SHA1"); request.AddParameter("oauth_version", "1.0"); request.AddParameter("oauth_signature", sig); }
public void GetAccessToken(string OauthTokenSecret, string oauth_request_token, string oauth_verifier, out string oauth_token, out string oauth_token_secret) { string urlBase = "https://www.fatsecret.com/oauth/access_token?"; urlBase = urlBase + "oauth_token=" + oauth_request_token; urlBase = urlBase + "&oauth_verifier=" + oauth_verifier; OAuthBase oAuth = new OAuthBase(); Uri url = new Uri(urlBase); string normalizedUrl, normalizedRequestParameters; string signature = oAuth.GenerateSignature(url, ConsumerKey, ConsumerSecret, null, OauthTokenSecret, out normalizedUrl, out normalizedRequestParameters); var result = GetQueryResponse(normalizedUrl, normalizedRequestParameters + "&" + OAuthBase.OAUTH_SIGNATURE + "=" + HttpUtility.UrlEncode(signature)); string[] p = result.Split('&'); oauth_token = p[0].Replace("oauth_token=", ""); oauth_token_secret = p[1].Replace("oauth_token_secret=", ""); }
private void bgetTokens_Click(object sender, EventArgs e) { tokens.Clear(); WebClient wc = new WebClient(); OAuthBase ooo = new OAuthBase(); string normalizedUrl = ""; string normalizedRequestParameters = ""; string adr = "https://www.flickr.com/services/oauth/request_token" + "?oauth_signature_method=HMAC-SHA1" + "&oauth_version=1.0" + "&oauth_callback=" + Consumer_Callback; string strSignature = ooo.GenerateSignature(new Uri(adr), Consumer_Key, Consumer_Secret, "", "", "GET", ooo.GenerateTimeStamp(), ooo.GenerateNonce(),out normalizedUrl,out normalizedRequestParameters); string address = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + strSignature; label1.Text = strSignature; try { string str = wc.DownloadString(address); if (!str.Equals("")) { foreach (string s in str.Split('&')) { string[] kv = s.Split('='); tokens.Add(kv[0], kv[1]); bgetAuth.Enabled = true; } bgetAcTok.Enabled = checkTokens(); } } catch(Exception ex){ string sksks = ex.Message; label1.Text = sksks; } }
private static OAuthToken GetAccessToken(OAuthToken oauthToken) { var uri = "https://api.dropbox.com/1/oauth/access_token"; OAuthBase oAuth = new OAuthBase(); var nonce = oAuth.GenerateNonce(); var timeStamp = oAuth.GenerateTimeStamp(); string parameters; string normalizedUrl; var signature = oAuth.GenerateSignature(new Uri(uri), SeConsumerKey, SeConsumerSecret, oauthToken.Token, oauthToken.Secret, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out parameters); signature = HttpUtility.UrlEncode(signature); var requestUri = new StringBuilder(uri); requestUri.AppendFormat("?oauth_consumer_key={0}&", SeConsumerKey); requestUri.AppendFormat("oauth_token={0}&", oauthToken.Token); requestUri.AppendFormat("oauth_nonce={0}&", nonce); requestUri.AppendFormat("oauth_timestamp={0}&", timeStamp); requestUri.AppendFormat("oauth_signature_method={0}&", "HMAC-SHA1"); requestUri.AppendFormat("oauth_version={0}&", "1.0"); requestUri.AppendFormat("oauth_signature={0}", signature); var request = (HttpWebRequest)WebRequest.Create(requestUri.ToString()); request.Method = WebRequestMethods.Http.Get; var response = request.GetResponse(); var reader = new StreamReader(response.GetResponseStream()); var accessToken = reader.ReadToEnd(); var parts = accessToken.Split('&'); var token = parts[1].Substring(parts[1].IndexOf('=') + 1); var secret = parts[0].Substring(parts[0].IndexOf('=') + 1); return(new OAuthToken(token, secret)); }
/*OAuthするためのHeaderを作る*/ public string GenerateAuthHeader(string requestUrl, string requestMethod) { OAuthBase oauthBase = new OAuthBase(); string timestamp = oauthBase.GenerateTimeStamp(); string nonce = oauthBase.GenerateNonce(); string normalizedUrl, normalizedReqParams; normalizedUrl = normalizedReqParams = string.Empty; Uri uri = new Uri(requestUrl); string signature = oauthBase.GenerateSignature( uri, consumerKey, consumerSecret, accessToken.token, accessToken.tokenSecret, requestMethod, timestamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out normalizedReqParams); signature = WebUtility.UrlEncode(signature); string authHeader = string.Format( AUTHHEADER_BASE, consumerKey, nonce, signature, "HMAC-SHA1", timestamp, accessToken.token, "1.0" ); return(authHeader); }
public HttpClient createClient() { string accessToken = "p8u4y59m8vtzaw7aznwzbbf85gf8fah8"; string tokenSecret = "d1r02yc5ko06eyeaanht619276vtg0oq"; string consumerKey = "9sbpacku1gj98zonh5jqumk6uchydydb"; string consumerSecret = "62551lhv0h83bech9txqvdcn1c09lgub"; string credentials = String.Format("{0}:{1}:{2}:{3}", consumerKey, consumerSecret, accessToken, tokenSecret); /////get sign /// var strUri = "http://dev-warmglass.focallabs.co.uk/V1/customers/1"; var uri = new Uri(strUri); string url, param; var oAuth = new OAuthBase(); var nonce = oAuth.GenerateNonce(); var timeStamp = oAuth.GenerateTimeStamp(); var signature = oAuth.GenerateSignature(uri, consumerKey, consumerSecret, string.Empty, string.Empty, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out url, out param); sign = string.Format("{0}?{1}&oauth_signature={2}", url, param, signature); oauth_sign = "\"" + signature + "\""; oauth_nonce = "\"" + nonce + "\""; oauth_timeStamp = "\"" + timeStamp + "\""; /////get sign var client = new HttpClient(); client.BaseAddress = new Uri("http://dev-warmglass.focallabs.co.uk/rest"); return(client); }
public static Rtone.Song GetSimilarTrackByArtist(string artist, string trackTitle) { var OAuth = new OAuthBase(); string apiUrl = string.Format( "http://ws.audioscrobbler.com/2.0/?method=artist.gettoptracks?method=track.getsimilar&artist={0}&api_key={1}&limit=1&autocorrect=1", OAuth.UrlEncode(artist), RRLastfm.API_KEY); WebRequest webRequest = WebRequest.Create(apiUrl); var xmlDoc = new XmlDocument(); var client = new WebClient(); try { var xmlString = client.DownloadString(apiUrl); xmlDoc.LoadXml(xmlString); XmlNodeList artistNodeList = xmlDoc.GetElementsByTagName("artist"); XmlNodeList urlNodeList = xmlDoc.GetElementsByTagName("url"); XmlNodeList trackNodeList = xmlDoc.GetElementsByTagName("track"); if (trackNodeList[0]["name"].InnerText.ToLower() == trackTitle.ToLower()) { return null; } var song = new Rtone.Song { Artist = artistNodeList[0]["name"].InnerText, PlayLink = urlNodeList[0].InnerText, Title = trackNodeList[0]["name"].InnerText }; return song; } catch (Exception) { return null; } }
public static RestRequest CreateNewRestletRequest(string jsonRequest, string restletUrl, string restletName) { string token; string tokenSecret; string consumerKey; string consumerSecret; if (restletName == "CreateCustomer") { token = tokenIDCreateCustomer; tokenSecret = tokenSecretCreateCustomer; consumerKey = consumerKeyCreateCustomer; consumerSecret = consumerSecretCreateCustomer; } else { token = tokenIDOrderImporter; tokenSecret = tokenSecretOrderImporter; consumerKey = consumerKeyOrderImporter; consumerSecret = consumerSecretOrderImporter; } Creds creds = new Creds( token, tokenSecret, consumerKey, consumerSecret, netsuiteAccount ); var request = new RestRequest(Method.POST); string authHeader = OAuthBase.GenerateAuthorizationHeader(restletUrl, "POST", creds); request.AddHeader("Content-Type", "application/json"); request.AddHeader("Authorization", authHeader); request.AddParameter("application/json; charset=utf-8", jsonRequest, ParameterType.RequestBody); return(request); }
public string GetSettings(OAuth_Token token) { HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(); request.RequestUri = new Uri("https://api.twitter.com/1.1/account/settings.json"); request.Method = HttpMethod.Get; OAuthBase _oAuthBase = new OAuthBase(); string normalizedUri; string normalizedParameters; string authHeader; string signature = _oAuthBase.GenerateSignature( request.RequestUri, null, oauthconsumerkey, oauthconsumersecret, token.oauth_token, token.oauth_token_secret, request.Method.Method, _oAuthBase.GenerateTimeStamp(), _oAuthBase.GenerateNonce(), out normalizedUri, out normalizedParameters, out authHeader); request.Headers.Authorization = new AuthenticationHeaderValue("OAuth", authHeader); var response = client.SendAsync(request).Result; if (!response.IsSuccessStatusCode) { return(null); } return(response.Content.ReadAsStringAsync().Result); }
protected void Page_Load(object sender, EventArgs e) { string ConsumerKey = "a47a1f116d74f7c0608b2ac904dec6d1"; string ConsumerSecret = "4ba049c97fd17cf0fbb275ee39f59fc9"; string oauth_token = WebConfigurationManager.AppSettings["Magento.Token"]; string oauth_token_secret = WebConfigurationManager.AppSettings["Magento.TokenSecret"]; var uri = new Uri("http://smeitproducts.com/magento-beta" + "/api/rest/products"); OAuthBase oAuth = new OAuthBase(); string nonce = oAuth.GenerateNonce(); string timeStamp = oAuth.GenerateTimeStamp(); string parameters; string normalizedUrl; string signature = oAuth.GenerateSignature(uri, ConsumerKey, ConsumerSecret, oauth_token, oauth_token_secret, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.PLAINTEXT, out normalizedUrl, out parameters); StringBuilder requestUri = new StringBuilder("OAuth "); requestUri.AppendFormat("oauth_token=\"{0}\",", oauth_token); requestUri.AppendFormat("oauth_version=\"{0}\",", "1.0"); requestUri.AppendFormat("oauth_signature_method=\"{0}\",", "PLAINTEXT"); requestUri.AppendFormat("oauth_nonce=\"{0}\",", nonce); requestUri.AppendFormat("oauth_timestamp=\"{0}\",", timeStamp); requestUri.AppendFormat("oauth_consumer_key=\"{0}\",", ConsumerKey); requestUri.AppendFormat("oauth_signature=\"{0}\"", signature); string BASE_URL = "http://smeitproducts.com/magento-beta"; RestClient restClient =new RestClient(BASE_URL); RestRequest restRequest = new RestRequest("/api/rest/products", Method.GET); restRequest.AddHeader("Authorization", requestUri.ToString()); restRequest.RequestFormat = DataFormat.Json; var response = restClient.Execute(restRequest); var data = response.Content; }
public IEnumerable <Event> GetEventData(string city) { var url = YelpApiUrl; var urlParams = new Dictionary <string, string>() { { "terms", "bars" }, { "location", city }, { "sort", "2" }, // 0 best match, 1 distance, 2 highest rating { "limit", "20" }, { "category_filter", "nightlife" } //http://www.yelp.com/developers/documentation/category_list }; url = url.AppandQueryParams(urlParams); var oauthUtil = new OAuthBase(); Console.WriteLine("URL : " + url); url = oauthUtil.GetUrl(url, YelpV2OAuth); Console.WriteLine("OAuth URL : " + url); var converter = new YelpConverter(); try { var response = HttpRequestHelper.GetJsonResponse(url); var events = new List <Event>(); foreach (var b in response.businesses) { var e = converter.GetEventObject(b); events.Add(e); } return(events); } catch (Exception e) { // TODO: Log return(null); } }
/// <summary> /// Ìåòîä ïîèñêà ïðîäóêòîâ. /// </summary> /// <param name="searchExpression">Ïîèñêîâûé çàïðîñ.</param> /// <param name="pageNumber">Íîìåð çàïðàøèâàåìîé ñòðàíèöû.</param> /// <param name="maxResults">Ìàêñèìàëüíîå êîëè÷åñòâî âûäàâàåìûõ ðåçóëüòàòîâ. Ïî óìîë÷àíèþ - 20.</param> /// <param name="format">Ôîðìàò âûõîäíûõ äàííûõ. Ìîæåò áûòü "xml" èëè "json". Ïî óìîë÷àíèþ - "json".</param> /// <returns>Ðåçóëüòàòû ïîèñêà, âêëþ÷àþùèå â ñåáÿ: /// Îáùóþ èíôîðìàöèþ: /// max_results - ìàêñèìàëüíûé ðàçìåð ñòðàíèöû ðåçóëüòàòîâ, /// total_results - îáùåå êîëè÷åñòâî íàéäåííûõ ïðîäóêòîâ, /// page_number - íîìåð ñòðàíèöû ðåçóëüòàòîâ. /// Èíôîðìàöèþ î ïðîäóêòàõ, ñîäåðæàùóþ: /// food_id – èäåíòèôèêàòîð ïðîäóêòà, /// food_name - èìÿ ïðîäóêòà, /// food_type - òèï ïðîäóêòà ("Brand" èëè "Generic"), /// brand_name - èìÿ áðåíäà (òîëüêî êîãäà food_type="Brand"), /// food_url - ññûëêà íà ïðîäóêò íà ñåðâåðå FatSecret, /// food_description - îáùàÿ èíôîðìàöèÿ î ïèùåâîé öåííîñòè äëÿ 'nominated' ïîðöèè. /// </returns> public string SearchFood(string searchExpression, int pageNumber, int maxResults = 20, string format = "json") { string urlBase = URL_BASE + "method=foods.search" + "&search_expression=" + searchExpression.Trim() + "&page_number=" + pageNumber + "&max_results=" + maxResults + "&format=" + format; OAuthBase oAuth = new OAuthBase(); Uri url = new Uri(urlBase); string normalizedUrl, normalizedRequestParameters; string signature = oAuth.GenerateSignature(url, ConsumerKey, ConsumerSecret, null, null, out normalizedUrl, out normalizedRequestParameters); return(GetQueryResponse(normalizedUrl, normalizedRequestParameters + "&" + OAuthBase.OAUTH_SIGNATURE + "=" + HttpUtility.UrlEncode(signature))); //ErrorCheck(doc); //token = doc["profile"]["auth_token"].InnerText; //secret = doc["profile"]["auth_secret"].InnerText; }
public static string Build(Uri source, string consumerKey, string consumerSecret, string token, string tokenSecret) { OAuthBase oauth = new OAuthBase(); string timeStamp = OAuthBase.GenerateTimeStamp(); string nonce = OAuthBase.GenerateNonce(); // Calling source.Query returns an urlencoded string, but we don't want that since we will use // oauth.UrlEncode ourselves var query = HttpUtility.UrlDecode(source.Query.Contains("?") ? source.Query.Remove(0, 1) : source.Query); var parameters = NameValueParser.GetCollection(query, "&"); parameters.Add("oauth_consumer_key", consumerKey); parameters.Add("oauth_timestamp", timeStamp); parameters.Add("oauth_nonce", nonce); parameters.Add("oauth_version", "1.0"); parameters.Add("oauth_signature_method", "HMAC-SHA1"); if (!String.IsNullOrEmpty(token)) parameters.Add("oauth_token", token); string signature = oauth.GenerateSignature(source, parameters, consumerKey, consumerSecret, token, tokenSecret, "POST", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1); parameters.Add("oauth_signature", signature); StringBuilder requestBuilder = new StringBuilder(512); foreach (string key in parameters) { if (requestBuilder.Length != 0) requestBuilder.Append("&"); requestBuilder.Append(key); requestBuilder.Append("="); requestBuilder.Append(OAuthBase.UrlEncode(parameters[key])); } return requestBuilder.ToString(); }
/// <summary> /// Create a new profile with a user specified ID /// </summary> /// <param name="userID">Your ID for the newly created profile</param> /// <param name="token">The token for the newly created profile is returned here</param> /// <param name="secret">The secret for the newly created profile is returned here</param> public void ProfileCreate(string userID, out string token, out string secret) { string urlBase = URL_BASE + "method=profile.create"; if (userID != null || userID != string.Empty) { urlBase += "&user_id=" + userID; } OAuthBase oAuth = new OAuthBase(); Uri url = new Uri(urlBase); string normalizedUrl, normalizedRequestParameters; string signature = oAuth.GenerateSignature(url, ConsumerKey, ConsumerSecret, null, null, out normalizedUrl, out normalizedRequestParameters); XmlDocument doc = LoadXMLDocument(GetQueryResponse(normalizedUrl, normalizedRequestParameters + "&" + OAuthBase.OAUTH_SIGNATURE + "=" + HttpUtility.UrlEncode(signature))); ErrorCheck(doc); token = doc["profile"]["auth_token"].InnerText; secret = doc["profile"]["auth_secret"].InnerText; }
internal static string GenerateToken(string OAuthToken, string OAuthTokenSecret) { OAuthBase oAuth = new OAuthBase(); string m_strNormalizedUrl, m_strNormalizedRequestParameters; string accessToken = oAuth.GenerateSignature(new Uri(ConfigurationManager.AppSettings["netFlixAccessToken"]), ConfigurationManager.AppSettings["consumerKey"], ConfigurationManager.AppSettings["sharedSecret"], OAuthToken, OAuthTokenSecret, "GET", oAuth.GenerateTimeStamp(), oAuth.GenerateNonce(), out m_strNormalizedUrl, out m_strNormalizedRequestParameters); string accessTokenResponse = ""; using (WebClient w = new WebClient()) { string accessTokenRequest = m_strNormalizedUrl + "?" + m_strNormalizedRequestParameters + "&oauth_signature=" + HttpUtility.UrlEncode(accessToken); accessTokenResponse = w.DownloadString(accessTokenRequest); } return(accessTokenResponse); }
internal static string MakeACall(string Command) { NameValueCollection accessResponse = HttpUtility.ParseQueryString( File.ReadAllText(AccessTokenFilename)); OAuthBase oAuth = new OAuthBase(); string m_strNormalizedUrl, m_strNormalizedRequestParameters; string accessToken = oAuth.GenerateSignature( new Uri(ConfigurationManager.AppSettings["netFlixCallApi"] + "/" + Command), ConfigurationManager.AppSettings["consumerKey"], ConfigurationManager.AppSettings["sharedSecret"], accessResponse["oauth_token"], accessResponse["oauth_token_secret"], "GET", oAuth.GenerateTimeStamp(), oAuth.GenerateNonce(), out m_strNormalizedUrl, out m_strNormalizedRequestParameters); using (WebClient w = new WebClient()) { string callRequest = m_strNormalizedUrl + "?" + m_strNormalizedRequestParameters + "&oauth_signature=" + HttpUtility.UrlEncode(accessToken); string strCallResponse = w.DownloadString(callRequest); if (!Directory.Exists(Environment.SpecialFolder.MyDocuments + strCACHE_PATH)) { Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + strCACHE_PATH); } using (FileStream f = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + strCACHE_PATH + "LastResponse.xml", FileMode.OpenOrCreate)) { using (StreamWriter writer = new StreamWriter(f)) { writer.Write(strCallResponse); } } return(strCallResponse); } }
/// <summary> /// Create a new session for JavaScript API users /// </summary> /// <param name="userID">Your ID for the profile</param> /// <param name="expires">The number of minutes before a session is expired after it is first started. Set this to 0 to never expire the session. (Set to any value less than 0 for default)</param> /// <param name="consumeWithin">The number of minutes to start using a session after it is first issued. (Set to any value less than 0 for default)</param> /// <param name="permittedReferrerRegex">A domain restriction for the session. (Set to null if you do not need this)</param> /// <param name="cookie">The desired session_key format.</param> /// <param name="sessionKey">The session key for the newly created session is returned here</param> public void ProfileRequestScriptSessionKey(string userID, int expires, int consumeWithin, string permittedReferrerRegex, bool cookie, out string sessionKey) { string urlBase = URL_BASE + "method=profile.request_script_session_key&user_id=" + userID; if (expires > -1) { urlBase += "&expires=" + expires; } if (consumeWithin > -1) { urlBase += "&consume_within=" + consumeWithin; } if (permittedReferrerRegex != null) { urlBase += "&permitted_referrer_regex=" + permittedReferrerRegex; } if (cookie) { urlBase += "&cookie=true"; } OAuthBase oAuth = new OAuthBase(); Uri url = new Uri(urlBase); string normalizedUrl, normalizedRequestParameters; string signature = oAuth.GenerateSignature(url, ConsumerKey, ConsumerSecret, null, null, out normalizedUrl, out normalizedRequestParameters); XmlDocument doc = LoadXMLDocument(GetQueryResponse(normalizedUrl, normalizedRequestParameters + "&" + OAuthBase.OAUTH_SIGNATURE + "=" + HttpUtility.UrlEncode(signature))); ErrorCheck(doc); sessionKey = doc["profile"]["session_key"].InnerText; }
public void SendRequest() { try { Method method = (Method)Enum.Parse(typeof(Method), _panel.Settings.Operation); var restClient = new RestSharp.RestClient(_panel.Settings.Uri); var request = new RestRequest(method); OAuthBase oAuth = new OAuthBase(); string nonce = oAuth.GenerateNonce(); string timeStamp = oAuth.GenerateTimeStamp(); string parameters; string normalizedUrl; string signature = oAuth.GenerateSignature(new Uri(_panel.Settings.Uri), _panel.Settings.ConsumerKey, _panel.Settings.ConsumerSecret, _panel.Settings.AccessToken, _panel.Settings.AccessTokenSecret, _panel.Settings.Operation, timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out parameters); /* string signature = oAuth.GenerateSignature( * new Uri("http://magento2.holbidev.co.uk/rest/V1/products/28732400HB") * , "wqn46nijaiinkddqvm7nh9yuu1gpd34e", "5becg1jr05edhlr0838a3tyacaw7ud7i", "v4jduksl8cdgr21v99vgv1shxnai96oc", "6le50ake47pjv2cen4y63yjroo8447fs", * "", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl, out parameters);*/ signature = oAuth.UrlEncode(signature); var requestParamsString = string.Format("OAuth realm={0},oauth_consumer_key={1},oauth_token={2},oauth_nonce={3},oauth_signature_method={4},oauth_timestamp={5},oauth_version={6},oauth_signature={7}", _panel.Settings.Uri, _panel.Settings.ConsumerKey, _panel.Settings.AccessToken, nonce, "HMAC-SHA1", timeStamp, "1.0", signature); request.AddHeader("Authorization", requestParamsString); request.AddHeader("Accept", "application/json"); /*if (_panel.Settings.Object != null) * request.AddJsonBody(_panel.Settings.Object);*/ _panel.Settings.RestResponse = restClient.Execute(request); _panel.Settings.OperationIsFinished(); } catch (Exception ex) { //return null; } }
public Status Update(string status, ulong?in_reply_to_status_id, string geo_lat, string geo_long) { if (status == null || status.Length == 0 || status.Length > MaxStatusLength) { throw new ArgumentException(); } string query = "?status=" + OAuthBase.UrlEncode(status); if (in_reply_to_status_id.HasValue) { query += "&in_reply_to_status_id=" + in_reply_to_status_id.Value.ToString(); } if (geo_lat != null && geo_lat.Length > 0) { query += "&lat=" + geo_lat; } if (geo_long != null && geo_long.Length > 0) { query += "&long=" + geo_long; } string json = DownloadString(new Uri(StatusesUpdateURL + query), HTTP_POST, null); return(JsonDeserializer.Deserialize <Status> ((JsonObject) new JsonValueReader(json).Read())); }
public Status SendDirectMessage(string screen_name, ulong?user_id, string text) { if (string.IsNullOrEmpty(screen_name) && (!user_id.HasValue || user_id.Value == 0)) { throw new ArgumentNullException(); } string query; if (!string.IsNullOrEmpty(screen_name)) { query = "?screen_name=" + OAuthBase.UrlEncode(screen_name); } else { query = "?user_id=" + user_id.Value.ToString(); } query += "&text=" + OAuthBase.UrlEncode(text); string json = DownloadString(new Uri(DirectMessageNewURL + query), HTTP_POST, null); JsonObject obj = (JsonObject) new JsonValueReader(json).Read(); Status status = JsonDeserializer.Deserialize <Status> (obj); SetDirectMessageInfo(status, obj); return(status); }
private string BuildAuthenticatedUrl(Uri uri) { // // Let's search for this bad boy! // string result = string.Empty; // // todo: put this info in the config file // string consumerKey = "dj0yJmk9MFBTSWVjY3Jhb2dTJmQ9WVdrOWQyRmxkMkZSTm1zbWNHbzlNek0xTmpFNE9EWXkmcz1jb25zdW1lcnNlY3JldCZ4PWI5"; string consumerSecret = "e3d1783f97fe56b22fffa2209ca45548fcc7a478"; string url, param; var oAuth = new OAuthBase(); var nonce = oAuth.GenerateNonce(); var timeStamp = oAuth.GenerateTimeStamp(); var signature = oAuth.GenerateSignature(uri, consumerKey, consumerSecret, string.Empty, string.Empty, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out url, out param); result = string.Format("{0}?{1}&oauth_signature={2}", url, param, signature); return(result); }
private static async Task <string> GetJsonStringForTranslate(string uri, string text) { try { OAuthBase oAuthBase = new OAuthBase(); var timestamp = oAuthBase.GenerateTimeStamp(); var nonce = oAuthBase.GenerateNonce(); var httpClient = new HttpClient(); var request = new HttpRequestMessage(); request.Method = HttpMethod.Post; Dictionary <string, string> pairs = new Dictionary <string, string>(); pairs.Add("name", "kevingao"); pairs.Add("key", TRANS_KEY); pairs.Add("text", text); pairs.Add("split", "1"); pairs.Add("oauth_consumer_key", TRANS_KEY); pairs.Add("oauth_token", TRANS_SECRET); pairs.Add("oauth_timestamp", timestamp); pairs.Add("oauth_nonce", nonce); pairs.Add("oauth_version", "1.0"); pairs.Add("oauth_signature", TRANS_SECRET + "&"); pairs.Add("oauth_signature_method", "PLAINTEXT"); var formContent = new HttpFormUrlEncodedContent(pairs); var response = await httpClient.PostAsync(new Uri(uri), formContent); response.EnsureSuccessStatusCode(); var responseText = await response.Content.ReadAsStringAsync(); return(responseText); } catch { return("ERROR"); } }
/// <summary> /// This method is used to send put request. /// </summary> /// <param name="HTTPMethod">HTTP request method e.g GET, POST, PUT, etc.</param> /// <param name="URL">The API endpoint URL.</param> /// <param name="body">The body of the request.</param> /// <returns> The response of the request.</returns> public static IRestResponse sendPut(string HTTPMethod, Uri URL, string body) { // It should be fused with the one above it. OAuthBase oAuth = new OAuthBase(); string nonce = oAuth.GenerateNonce(); string timeStamp = oAuth.GenerateTimeStamp(); string normalizedURl; string normalizedParameter; string signature = oAuth.GenerateSignature(URL, consumerKey, consumerSecret, oauthToken, oauthTokenSecret, HTTPMethod, timeStamp, nonce, out normalizedURl, out normalizedParameter); signature = HttpUtility.UrlEncode(signature); String url = URL + "?oauth_consumer_key=" + consumerKey + "&oauth_token=" + oauthToken + "&oauth_signature_method=HMAC-SHA1" + "&oauth_timestamp=" + timeStamp + "&oauth_nonce=" + nonce + "&oauth_version=1.0" + "&oauth_signature=" + signature; var client = new RestClient(url); client.Timeout = -1; var request = new RestRequest(Method.PUT); request.AddHeader("Content-Type", "application/json"); request.AddParameter("application/json", body, ParameterType.RequestBody); return(client.Execute(request)); }
public static ICloudStorageAccessToken BuildToken(String tokenKey, String tokenSecret, String consumerKey, String consumerSecret) { return(new GoogleDocsToken(OAuthBase.UrlEncode(tokenKey), OAuthBase.UrlEncode(tokenSecret), consumerKey, consumerSecret)); }
public ActionResult TwitterRedirectStep2(string config, string callback) { HttpContext.Response.Cache.VaryByParams["*"] = true; string htmlOutput = ""; try { string configReferenceName = config; if (string.IsNullOrEmpty(configReferenceName) || new AgilityContentRepository <AgilityContentItem>(configReferenceName).Item("") == null) { throw new HttpException(500, string.Format("Agility Comments Configuration Item '{0}' not found", configReferenceName)); } var configItem = new AgilityContentRepository <AgilityContentItem>(configReferenceName).Item(""); string token = Request.QueryString["oauth_token"]; string verifier = Request.QueryString["oauth_verifier"]; string callbackFunction = callback; Uri rq = new Uri("https://api.twitter.com/oauth/access_token"); OAuthBase oauth = new OAuthBase(); string timestamp = oauth.GenerateTimeStamp(); string nonce = oauth.GenerateNonce(); string consumerKey = configItem["TwitterAPIConsumerKey"] as string; string consumerSecret = configItem["TwitterAPIConsumerSecret"] as string; var postData = string.Format("{0}={1}", "oauth_verifier", verifier); var authorizationHeader = oauth.CreateAuthenticationAccessHeader(rq.ToString(), "POST", consumerKey, consumerSecret, token, new Dictionary <string, string> { { "oauth_verifier", verifier } }); WebClient client = new WebClient(); client.Headers.Add("Authorization", authorizationHeader); string response = client.UploadString(rq, postData); var retData = HttpUtility.ParseQueryString(response); token = retData["oauth_token"]; string secret = retData["oauth_token_secret"]; string userID = retData["user_id"]; string screenName = retData["screen_name"]; if (!string.IsNullOrWhiteSpace(secret) && !string.IsNullOrWhiteSpace(token) && !string.IsNullOrWhiteSpace(screenName)) { //make sure everything came back ok... timestamp = oauth.GenerateTimeStamp(); nonce = oauth.GenerateNonce(); //get the fullname and other details as well... string requestUrl = string.Format("https://api.twitter.com/1.1/account/verify_credentials.json"); //can't get email unless app is whitelisted https://dev.twitter.com/rest/reference/get/account/verify_credentials if (CommentsUtils.GetBool(configItem["TwitterRequestEmail"])) { requestUrl += "?include_email=true"; } rq = new Uri(requestUrl); authorizationHeader = oauth.CreateAuthenticationAccessHeader(rq.ToString(), "GET", consumerKey, consumerSecret, token, new Dictionary <string, string>(), secret); client.Headers["Authorization"] = authorizationHeader; response = client.DownloadString(rq); TwitterUser tUser = CommentsUtils.DeserializeJSONObject <TwitterUser>(response); string name = tUser.name; string twitterProfileImage = tUser.profile_image_url; string email = tUser.email; //save the larger version of the profile image twitterProfileImage = twitterProfileImage.Replace("_normal", "_bigger"); StringBuilder html = new StringBuilder(); html.Append("<html>"); html.AppendLine("<head>"); html.AppendLine("<title>Authenticating...</title>"); html.AppendLine("</head>"); html.AppendLine("<body>"); if (!string.IsNullOrEmpty(userID)) { html.AppendLine("<script>"); html.AppendLine("if(window.opener) {"); html.AppendFormat("window.opener.{5}(\"{0}\",\"{1}\",\"{2}\",\"{3}\",\"{4}\");", userID, screenName, name, twitterProfileImage, email, callbackFunction); html.AppendLine("window.close()"); html.AppendLine("} else {"); html.AppendLine("document.write(\"An error occurred during the authenticatin process. Please close your browser and try again.\");"); html.AppendLine("}"); html.AppendLine("</script>"); } else { html.AppendLine("<script>window.close()</script>"); } html.AppendLine("</body>"); html.AppendLine("</html>"); htmlOutput = html.ToString(); } return(Content(htmlOutput)); } catch (Exception ex) { Agility.Web.Tracing.WebTrace.WriteException(ex); return(Content(ex.Message)); } }
public SubscriptionWS SubscribeUser(SubscriptionWS subscriptionWs) { if (subscriptionWs == null) { throw new ArgumentNullException("subscriptionWs"); } if (subscriptionWs.user == null) { throw new ArgumentNullException("subscriptionWs.user"); } if (subscriptionWs.company == null) { throw new ArgumentNullException("subscriptionWs.company"); } if (subscriptionWs.paymentPlanId == null) { throw new ArgumentNullException("subscriptionWs.paymentPlanId"); } if (!IsAuthenticated) { return(null); } var requestUrl = OAuthBase.GetOAuthSignedUrl(SubscribeTemplateUrl, postMethod); Console.WriteLine(requestUrl); var request = BuildHttpWebRequestForUrl(requestUrl, true, false); request.ContentType = "application/xml"; var outStream = request.GetRequestStream(); _subscriptionSerializer.Serialize(outStream, subscriptionWs); outStream.Close(); HttpWebResponse response; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { var exceptionResponse = (HttpWebResponse)ex.Response; if (exceptionResponse.StatusCode == HttpStatusCode.Conflict) { throw new ConflictException(); } if ((int)exceptionResponse.StatusCode == 424) { throw new FailedDependencyException(); } throw; } if (response.StatusCode != HttpStatusCode.OK) { return(null); } var responseStream = response.GetResponseStream(); if (responseStream == null) { throw new IOException("No response stream returned"); } var result = _subscriptionSerializer.Deserialize(responseStream) as SubscriptionWS; return(result); }
internal virtual void CreateRequest() { if (this.m_HttpRequest != null) { throw new InvalidOperationException("Request instance can only be used for a single request."); } StringBuilder uriBuilder = new StringBuilder(); foreach (KeyValuePair <String, String> param in this.m_Parameters) { if (!String.IsNullOrEmpty(param.Value)) { if (uriBuilder.Length != 0) { uriBuilder.Append('&'); } uriBuilder.Append(param.Key); uriBuilder.Append('='); uriBuilder.Append(this.UrlEncode(param.Value)); } } string strData = uriBuilder.ToString(); string strUrl = this.m_RequestUri; if (oAuth_ConsumerKey != null) { OAuthBase oAuth = new OAuthBase(); string nonce = oAuth.GenerateNonce(); string timeStamp = oAuth.GenerateTimeStamp(); Uri reqUri = null; reqUri = new Uri(this.m_RequestUri + ((strData == "") ? "" : "?" + strData)); string signature = oAuth.GenerateSignature(reqUri, oAuth_ConsumerKey, oAuth_ConsumerSecret, oAuth_Token, oAuth_Secret, Method.ToString(), timeStamp, nonce, oAuthSignatureTypes, out strUrl, out strData); strData += "&oauth_signature=" + this.UrlEncode(signature); } HttpWebRequest WebReq = null; if (Method == requestMethod.GET) { WebReq = (HttpWebRequest)HttpWebRequest.Create(strUrl + ((strData == "") ? "" : "?") + strData); if (m_Headers != null) { WebReq.Headers = this.m_Headers; } WebReq.ServicePoint.Expect100Continue = false; WebReq.Method = Method.ToString(); } else if (Method == requestMethod.POST) { WebReq = (HttpWebRequest)HttpWebRequest.Create(strUrl); if (m_Headers != null) { WebReq.Headers = this.m_Headers; } //Encoding the post vars byte[] buffer = Encoding.UTF8.GetBytes(strData); //Initialisation with provided url WebReq.ServicePoint.Expect100Continue = false; //Set method to post, otherwise postvars will not be used WebReq.Method = Method.ToString(); WebReq.ContentType = "application/x-www-form-urlencoded"; WebReq.ContentLength = buffer.Length; Stream PostData = WebReq.GetRequestStream(); PostData.Write(buffer, 0, buffer.Length); //Closing is always important PostData.Close(); } else { throw new Exception("Posting using Method [" + Method + "] is not implemented"); } if (m_Credentials != null) { WebReq.Credentials = this.m_Credentials; } //WebReq.UserAgent = "Twtri"; //WebReq.Timeout = 20000; this.m_HttpRequest = WebReq; }
public static string GetBearerToken(ILogger nLogger) { string bearerToken = null; nLogger?.Info("Begin GetBearerToken"); //don't block login from completing if call fails try { var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal; var context = (BootstrapContext)claimsPrincipal?.Identities.First().BootstrapContext; nLogger?.Info("Starting harvesting of OAuth2 token"); if (context == null) { nLogger?.Error("context is null"); } var contextSecurityToken = context?.SecurityToken; if (contextSecurityToken == null) { nLogger?.Info("context?.SecurityToken is null"); } if (string.IsNullOrEmpty(context?.Token)) { nLogger?.Info("context?.Token is null or empty"); } SecurityToken finalToken; if (contextSecurityToken == null && !string.IsNullOrEmpty(context?.Token)) { var handlers = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers; finalToken = handlers.ReadToken(new XmlTextReader(new StringReader(context.Token))); if (finalToken == null) { nLogger?.Error("handlers security token is null"); } } else { finalToken = contextSecurityToken; } var progressConfiguration = new ProgressConfiguration(); var oauth = new OAuthBase(); string rpEndpoint; string appliesTo; var localTokenType = progressConfiguration.InforIonApiTokenType; nLogger?.Info($"localTokenType - {localTokenType}"); var issuer = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration.Issuer; nLogger?.Info($"issuer - {issuer}"); //on-prem install if (issuer.Contains("adfs")) { nLogger?.Info("contains adfs"); rpEndpoint = progressConfiguration.InforIonApiRpEndpoint; appliesTo = progressConfiguration.InforIonApiAppliesToEndpoint; nLogger?.Info($"rpEndpoint - {rpEndpoint}"); nLogger?.Info($"appliesTo - {appliesTo}"); } //ce install else { nLogger?.Info("ce"); var uri = new Uri(issuer); var baseUri = uri.GetLeftPart(UriPartial.Authority); nLogger?.Info($"baseUri - {baseUri}"); rpEndpoint = baseUri + progressConfiguration.InforIonApiRpEndpoint; appliesTo = baseUri + progressConfiguration.InforIonApiAppliesToEndpoint; nLogger?.Info($"rpEndpoint - {rpEndpoint}"); nLogger?.Info($"appliesTo - {appliesTo}"); } if (finalToken != null) { var xmlTokenOauthToken = (GenericXmlSecurityToken) oauth.IssueOAuth2SecurityToken(finalToken, rpEndpoint, appliesTo, localTokenType, out var rstr); if (xmlTokenOauthToken != null) { var base64Token = xmlTokenOauthToken.TokenXml?.InnerText; if (!string.IsNullOrEmpty(base64Token)) { nLogger?.Info($"base64Token - {base64Token}"); var data = Convert.FromBase64String(base64Token); nLogger?.Info($"data - {data}"); bearerToken = Encoding.UTF8.GetString(data); } else { nLogger?.Info("base64Token is empty"); } } } else { nLogger?.Info("Token Empty - Will not process further"); } } catch (Exception e) { nLogger?.ErrorException("GetBearerToken", e); } nLogger?.Info("End GetBearerToken"); return(bearerToken); }
private void GetUnauthorizedRequestToken(OAuthParameters parameters) { String requestTokenUrl = "https://www.google.com/accounts/OAuthGetRequestToken"; Uri requestUri = new Uri(string.Format("{0}?scope={1}", requestTokenUrl, OAuthBase.EncodingPerRFC3986(parameters.Scope))); // callback is only needed when getting the request token bool callbackExists = false; if (!string.IsNullOrEmpty(parameters.Callback)) { parameters.BaseProperties.Add(OAuthBase.OAuthCallbackKey, parameters.Callback); callbackExists = true; } string headers = OAuthUtil.GenerateHeader(requestUri, "GET", parameters); System.Net.WebRequest request = System.Net.WebRequest.Create(requestUri); request.Headers.Add(headers); System.Net.WebResponse response = request.GetResponse(); string result = ""; if (response != null) { System.IO.Stream responseStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(responseStream); result = reader.ReadToEnd(); } if (callbackExists) { parameters.BaseProperties.Remove(OAuthBase.OAuthCallbackKey); } // split results and update parameters SortedDictionary <string, string> responseValues = OAuthBase.GetQueryParameters(result); parameters.Token = responseValues[OAuthBase.OAuthTokenKey]; parameters.TokenSecret = responseValues[OAuthBase.OAuthTokenSecretKey]; }
public void OAuthBaseSigningTest() { Tracing.TraceMsg("Entering OAuthBaseSignatureTest"); Uri uri = new Uri("http://photos.example.net/photos?file=vacation.jpg&size=original"); string sig = OAuthBase.GenerateSignature(uri, "dpf43f3p2l4k3l03", "kd94hf93k423kf44", "nnch734d00sl2jdk", "pfkkdhi9sl3r4s00", "GET", "1191242096", "kllo9940pd9333jh", OAuthBase.SignatureTypes.HMACSHA1); Assert.AreEqual("tR3+Ty81lMeYAr/Fid0kMTYa/WM=", sig); uri = new Uri("https://www.google.com/calendar/feeds/default/owncalendars/full"); sig = OAuthBase.GenerateSignatureBase(uri, this.oAuthConsumerKey, "1/NOQv9YTpvvzo8aFC9WpDuRxDl58cSF7JJaDQV1LnXgs", "MS3p04xWG7MkEyUwk91D1xEU", "GET", "1274791118", "f425726b32231fb9a363957f44e00227", "HMAC-SHA1"); Assert.AreEqual("GET&https%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds%2Fdefault%2Fowncalendars%2Ffull&oauth_consumer_key%3Dmantek.org%26oauth_nonce%3Df425726b32231fb9a363957f44e00227%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1274791118%26oauth_token%3D1%252FNOQv9YTpvvzo8aFC9WpDuRxDl58cSF7JJaDQV1LnXgs%26oauth_version%3D1.0", sig); sig = OAuthBase.GenerateSignature(uri, this.oAuthConsumerKey, this.oAuthConsumerSecret, "1/NOQv9YTpvvzo8aFC9WpDuRxDl58cSF7JJaDQV1LnXgs", "MS3p04xWG7MkEyUwk91D1xEU", "GET", "1274791118", "f425726b32231fb9a363957f44e00227", OAuthBase.SignatureTypes.HMACSHA1); Assert.AreEqual("NrqbCmBZ4GePYLeAg6m4WHjvD1w=", sig); uri = new Uri("http://www.google.com/calendar/feeds/default/owncalendars/full?xoauth_requestor_id=admin%40mantek.org"); sig = OAuthBase.GenerateSignature(uri, this.oAuthConsumerKey, this.oAuthConsumerSecret, null, null, "GET", "1274791118", "f425726b32231fb9a363957f44e00227", OAuthBase.SignatureTypes.HMACSHA1); Assert.AreEqual("f4mWCiT6IR6Ybq7fq9zc7860xE4=", sig); sig = OAuthBase.GenerateSignature(uri, this.oAuthConsumerKey, this.oAuthConsumerSecret, null, null, "GET", "1274809835", "c198e3abc8bfb1b11ea9a79987e80252", OAuthBase.SignatureTypes.HMACSHA1); Assert.AreEqual("omsn9/am4uIQZdDxmuWzeEap3hE=", sig); }
public OAuth_Token OAuth_Request_Token() { //https://dev.twitter.com/web/sign-in/implementing //https://dev.twitter.com/oauth/overview/authorizing-requests //Step:1 Obtaining a request token HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(); request.RequestUri = new Uri("https://api.twitter.com/oauth/request_token"); request.Method = HttpMethod.Post; OAuthBase _oAuthBase = new OAuthBase(); string callback_url = "http://127.0.0.1:53284/sv/Products/Callback"; string normalizedUri; string normalizedParameters; string authHeader; string signature = _oAuthBase.GenerateSignature( request.RequestUri, callback_url, oauthconsumerkey, oauthconsumersecret, null, null, request.Method.Method, _oAuthBase.GenerateTimeStamp(), _oAuthBase.GenerateNonce(), out normalizedUri, out normalizedParameters, out authHeader); request.Headers.Authorization = new AuthenticationHeaderValue("OAuth", authHeader); var response = client.SendAsync(request).Result; if (!response.IsSuccessStatusCode) { return(null); } string message = response.Content.ReadAsStringAsync().Result; NameValueCollection qs = HttpUtility.ParseQueryString(message); OAuth_Token oauth_token = new OAuth_Token(); if (qs["oauth_token"] != null) { oauth_token.oauth_token = qs["oauth_token"]; } if (qs["oauth_token_secret"] != null) { oauth_token.oauth_token_secret = qs["oauth_token_secret"]; } if (qs["oauth_callback_confirmed"] != null && qs["oauth_callback_confirmed"].Equals("true")) { oauth_token.oauth_callback_confirmed = true; } return(oauth_token); }
/// <summary> /// This API call returns a list of the user's active videos along with it's relevant metadata. 20 videos are returned by default but this is customisable. /// </summary> /// <param name="query"></param> /// <returns></returns> public List <Video> getVideoList(VideoListQuery query) { var url = apiUrl + "/api/" + username + "/videos.json?count=" + query.count.ToString(); if (query.labels.Length > 0) { var outh = new OAuthBase(); url += "&labels=" + outh.UrlEncode(String.Join(",", query.labels)); } if (query.status != String.Empty) { url += "&status=" + query.status; } if (query.sort == VideoListSorting.ASCENDING) { url += "&sort=" + "asc"; } else { url += "&sort=" + "desc"; } if (query.title != String.Empty) { url += "&title=" + HttpUtility.UrlEncode(query.title); } var response = executeRequest(url); var jo = (JArray)JsonConvert.DeserializeObject(response); var result = new List <Video>(); foreach (var o in jo) { var video = new Video { status = (string)o["status"], statusId = String.IsNullOrEmpty(o["status_id"].ToString()) ? 0 : int.Parse(o["status_id"].ToString()), duration = String.IsNullOrEmpty(o["duration"].ToString()) ? 0 : decimal.Parse(o["duration"].ToString()), description = (string)o["description"], height = string.IsNullOrEmpty(o["height"].ToString()) ? 0 : int.Parse(o["height"].ToString()), createdAt = DateTime.Parse((string)o["created_at"].ToString()), width = string.IsNullOrEmpty(o["width"].ToString()) ? 0 : int.Parse(o["width"].ToString()), playCount = String.IsNullOrEmpty(o["play_count"].ToString()) ? 0 : Int64.Parse(o["play_count"].ToString()), version = (string)o["version"], thumbnail = (string)o["thumbnail"], url = (string)o["url"], id = String.IsNullOrEmpty(o["id"].ToString()) ? 0 : Int64.Parse(o["id"].ToString()), title = (string)o["title"], user = new VideoAuthor { videoCount = String.IsNullOrEmpty(o["user"]["video_count"].ToString()) ? 0 : Int64.Parse(o["user"]["video_count"].ToString()), name = (string)o["user"]["author_name"], account = String.IsNullOrEmpty(o["user"]["author_account"].ToString()) ? 0 : int.Parse(o["user"]["author_account"].ToString()), url = (string)o["user"]["author_url"] } }; result.Add(video); } return(result); }
/// <summary> /// OAuth验证并获取token /// </summary> /// <param name="IsToken">是否需要更新token</param> /// <param name="RedisService">Redis类接口</param> /// <returns></returns> public static async Task <string> OAuth(bool IsToken, IRedisService RedisService) { if (await RedisService.ExistsAsync(CommentConfig.MDM_Token) && !IsToken) { return((await RedisService.GetAsync <string>(CommentConfig.MDM_Token, () => null)).ToString()); } string retString = string.Empty; while (true) { //基本参数 OAuthBase oAuth = new OAuthBase(); Dictionary <string, string> dic = new Dictionary <string, string>() { { "realm", IphoneServiceKey.Realm }, { "oauth_consumer_key", IphoneServiceKey.Consumer_key }, { "oauth_token", IphoneServiceKey.Access_token }, { "oauth_signature_method", IphoneServiceKey.Oauth_signature_method } }; string timeStamp = oAuth.GenerateTimeStamp(); string nonce = oAuth.GenerateNonce(); #region 签名 //签名 string sSign = oAuth.GenerateSignature( url: new Uri(dic["realm"]), callback: null, consumerKey: dic["oauth_consumer_key"], consumerSecret: IphoneServiceKey.Consumer_secret, token: dic["oauth_token"], tokenSecret: IphoneServiceKey.Access_secret, httpMethod: "GET", timeStamp: timeStamp, nonce: nonce, signatureType: OAuthBase.SignatureTypes.HMACSHA1, verifier: null, normalizedUrl: out string normalizedUrl, normalizedRequestParameters: out string normalizedRequestParameters); #endregion dic.Add("oauth_signature", sSign); dic.Add("oauth_timestamp", timeStamp); dic.Add("oauth_nonce", nonce); dic.Add("oauth_version", "1.0"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://mdmenrollment.apple.com/session"); request.Method = "GET"; string Headers = null; //请求头 foreach (var temp in dic) { Headers += $"{temp.Key}=\"{temp.Value}\","; } Headers = Headers.Substring(0, Headers.ToString().Length - 1); request.Headers.Set("Authorization", $"OAuth {Headers}"); try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(myResponseStream); retString = streamReader.ReadToEnd(); streamReader.Close(); myResponseStream.Close(); break; } catch (Exception ex) { Thread.Sleep(30000); string message = ex.Message; } } await RedisService.SetAsync(CommentConfig.MDM_Token, retString, 1); return(retString); }
static void Main(string[] args) { try { //Fill These vars with your netsuite information ********************************************************************** String urlString = ""; //RESTlet uri String ckey = ""; //Consumer Key String csecret = ""; //Consumer Secret String tkey = ""; //Token ID String tsecret = ""; //Token Secret String netsuiteAccount = ""; //Netsuite Account to connect to (i.e 5624525_SB1) //********************************************************************************************************************** Uri url = new Uri(urlString); OAuthBase req = new OAuthBase(); String timestamp = req.GenerateTimeStamp(); String nonce = req.GenerateNonce(); String norm = ""; String norm1 = ""; String signature = req.GenerateSignature(url, ckey, csecret, tkey, tsecret, "GET", timestamp, nonce, out norm, out norm1); //Percent Encode (Hex Escape) plus character if (signature.Contains("+")) { signature = signature.Replace("+", "%2B"); } String header = "Authorization: OAuth "; header += "oauth_signature=\"" + signature + "\","; header += "oauth_version=\"1.0\","; header += "oauth_nonce=\"" + nonce + "\","; header += "oauth_signature_method=\"HMAC-SHA1\","; header += "oauth_consumer_key=\"" + ckey + "\","; header += "oauth_token=\"" + tkey + "\","; header += "oauth_timestamp=\"" + timestamp + "\","; header += "realm=\"" + netsuiteAccount + "\""; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlString); request.ContentType = "application/json"; request.Method = "GET"; request.Headers.Add(header); WebResponse response = request.GetResponse(); HttpWebResponse httpResponse = (HttpWebResponse)response; using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); Console.WriteLine(JsonConvert.DeserializeObject(reader.ReadToEnd())); } } catch (System.Net.WebException e) { HttpWebResponse response = e.Response as HttpWebResponse; switch ((int)response.StatusCode) { case 401: Console.WriteLine("Unauthorized, please check your credentials"); break; case 403: Console.WriteLine("Forbidden, please check your credentials"); break; case 404: Console.WriteLine("Invalid Url"); break; } Console.WriteLine("Code: " + (int)response.StatusCode); using (Stream responseStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(responseStream, Encoding.UTF8); Console.WriteLine("Response: " + JsonConvert.DeserializeObject(reader.ReadToEnd())); } } catch (System.Exception e) { Console.WriteLine(e.ToString()); } }
public void Add(string key, ClientName clientName, OAuthBase client, object state) { this.Cache.Add(String.Format("oauth-{0}", key), new OAuthRequest(clientName, client, state), DateTime.Now.AddMinutes(20)); }