GenerateNonce() private method

Generate a nonce
private GenerateNonce ( ) : string
return string
コード例 #1
0
ファイル: ProxyController.cs プロジェクト: gimmie/proxies
        //
        // GET: /Proxy/
        public ActionResult Index()
        {
            string key = "<GIMMIE_KEY>";
            string secret = "<GIMMIE_SECRET>";
            string user_id = "<PLAYER_ID>";

            string queryString = Request.Url.Query;
            string[] pathArray = queryString.Split(new string[] { "gimmieapi=" }, StringSplitOptions.None);
            string path = pathArray[pathArray.Length - 1];

            string gimmieRoot = "https://api.gimmieworld.com";
            string endpoint = gimmieRoot + path;

            string access_token_secret = secret;
            string access_token = user_id;
            string url = endpoint;

            var uri = new Uri(url);
            string url2, param;
            var oAuth = new OAuthBase();
            var nonce = oAuth.GenerateNonce();
            var timeStamp = oAuth.GenerateTimeStamp();
            var signature = System.Web.HttpUtility.UrlEncode(oAuth.GenerateSignature(uri, key, secret, access_token, access_token_secret, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out url2, out param));
            var requestURL = string.Format("{0}?{1}&oauth_signature={2}", url2, param, signature);

            WebRequest req = WebRequest.Create(requestURL);
            WebResponse res = req.GetResponse();

            System.IO.Stream sm = res.GetResponseStream();
            System.IO.StreamReader s = new System.IO.StreamReader(sm);

            string output = s.ReadToEnd();

            return new ContentResult { Content = output, ContentType = "application/json" };
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: ChungMasterFlex/jsonnet
            //    private static string LoadData(Uri uri)
            public static string LoadData(Uri uri)
            {
                string url, parameters;
                var oAuth = new OAuthBase();
                string nonce = oAuth.GenerateNonce();
                string timeStamp = oAuth.GenerateTimeStamp();
                string signature = oAuth.GenerateSignature(uri,
                    "-bxN4K-9DwqvkBGuvnat6Q", //change
                    "QwLAfJ-Jduq1uWUgtQzc2gAf-q8", //change
                    "tebMxjbj5At7nZ43Olz-MXI9egDnTHkJ", //change
                    "_vKhx2te-KEXmNp-ShHvbp6pbmI", //change
                    "GET",
                    timeStamp,
                    nonce,
                    OAuthBase.SignatureTypes.HMACSHA1, out url, out parameters);

                string newUrl = string.Format("{0}?{1}&oauth_signature={2}", url, parameters, HttpUtility.UrlEncode(signature));
                var request = WebRequest.Create(newUrl) as HttpWebRequest;
                WebResponse response = request.GetResponse();
                string data;
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    data = reader.ReadToEnd();
                }
                return data;
            }
コード例 #3
0
ファイル: OAuth.cs プロジェクト: mediahackday/districtsintown
        internal static RestRequest AddAuth(RestRequest request)
        {
            OAuthBase oAuth = new OAuthBase();

            string uri = Program.BASEURL + request.Resource;
            if (request.Parameters.Any())
            {
                string parameters = String.Join("&", request.Parameters.Select(p => p.Name + "=" + p.Value).ToArray());
                uri = uri + "?" + parameters;
                request.Resource = request.Resource + "?" + parameters;
                request.Parameters.Clear();
            }
            string nonce = "2nw9PgKWgzXgUsLlubDBa4tpVA6v00XE";
            nonce = oAuth.GenerateNonce();
            string timeStamp = "1435755041";
            timeStamp = oAuth.GenerateTimeStamp();
            string normalizedUrl;
            string normalizedRequestParameters;
            string sig = oAuth.GenerateSignature(new Uri(uri), Program.API_KEY, Program.API_SECRET, null, null, "GET", timeStamp, nonce, out normalizedUrl, out normalizedRequestParameters);
            sig = HttpUtility.UrlEncode(sig);

            request.Method = Method.GET;
            string authString = String.Format(@"OAuth oauth_consumer_key=""{0}"", oauth_nonce=""{1}"", oauth_signature=""{2}"", oauth_signature_method=""HMAC-SHA1"", oauth_timestamp=""{3}"", oauth_version=""1.0""", Program.API_KEY, nonce, sig, timeStamp);

            request.AddHeader("Authorization", authString);

            return request;
        }
コード例 #4
0
        private Uri SignRequest(Uri uri, OAuthToken requestToken = null)
        {
            var    nonce     = _oAuthBase.GenerateNonce();
            var    timestamp = _oAuthBase.GenerateTimeStamp();
            string parameters;
            string normalizedUrl;

            string token  = requestToken == null ? String.Empty : requestToken.Token;
            string secret = requestToken == null ? String.Empty : requestToken.Secret;

            var signature = _oAuthBase.GenerateSignature(
                uri, _consumerKey, _consumerSecret,
                token, secret, "GET", timestamp,
                nonce, OAuthBase.SignatureTypes.HMACSHA1,
                out normalizedUrl, out parameters);

            signature = HttpUtility.UrlEncode(signature);

            var requestUri = new StringBuilder(uri.ToString());

            requestUri.AppendFormat("?oauth_consumer_key={0}&", _consumerKey);
            if (!String.IsNullOrEmpty(token))
            {
                requestUri.AppendFormat("oauth_token={0}&", 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);

            return(new Uri(requestUri.ToString()));
        }
コード例 #5
0
ファイル: Auth.cs プロジェクト: sosuke/yammyy
        public string GetRequestTokenQuery(string consumerKey, string consumerSecret)
        {
            Uri uri = new Uri(Resources.OAUTH_REQUEST_TOKEN);
            string nurl;
            string nrp;

            OAuthBase oAuth = new OAuthBase();
            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string sig = oAuth.GenerateSignature(
                uri,
                consumerKey,
                consumerSecret,
                string.Empty,
                string.Empty,
                "GET",
                timeStamp,
                nonce,
                OAuthBase.SignatureTypes.HMACSHA1, out nurl, out nrp);
            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);
            string query = sb.ToString();

            return query;
        }
コード例 #6
0
        // Help formatting the request: http://stackoverflow.com/questions/6036934/accessing-yelps-oauth-1-0a-api-with-dotnetopenauth
        public string getNearestStore(string place, string location)
        {
            //string yelpSearchUrl = "http://api.yelp.com/v2/search?" +
            //"term=" + place + "&location=" + location;


            /*
             *      string formattedUri = String.Format(System.Globalization.CultureInfo.InvariantCulture, yelpSearchUrl, "");
             *      Uri urlUri = new Uri(formattedUri);
             *      string outNormalisedUrl = "";
             *      string outNormalisedRequestParameters = "";
             *
             *      OAuth.OAuthBase oauthBase = new OAuth.OAuthBase();
             *      string oauthSignature = oauthBase.GenerateSignature(
             *              urlUri,
             *              oauthConsumerKey,
             *              oauthConsumerSecret,
             *              oauthToken,
             *              oauthTokenSecret,
             *              "GET",
             *              oauthBase.GenerateTimeStamp(),
             *              oauthBase.GenerateNonce(),
             *              out outNormalisedUrl,
             *              out outNormalisedRequestParameters);
             *
             *      string urlString = outNormalisedUrl + "?" + outNormalisedRequestParameters +
             *              "&oauth_signature=" + oauthSignature;
             */
            OAuth.OAuthBase oA = new OAuth.OAuthBase();                                                                                        //authorization class object

            var    _url = String.Format("http://api.yelp.com/v2/search?term={0}&location={1}&limit=10&category_filter=food", place, location); //URL for calling RESTful api for yelp.
            string parameters, out_url;
            Uri    uri = new Uri(_url);
            //authorizing the request
            var signature = oA.GenerateSignature(uri,
                                                 ConfigurationManager.AppSettings["YelpConsumerKey"],
                                                 ConfigurationManager.AppSettings["YelpConsumerSecret"],
                                                 ConfigurationManager.AppSettings["YelpToken"],
                                                 ConfigurationManager.AppSettings["YelpTokenSecret"],
                                                 "GET",
                                                 oA.GenerateTimeStamp(),
                                                 oA.GenerateNonce(),
                                                 OAuth.OAuthBase.SignatureTypes.HMACSHA1,
                                                 out out_url,
                                                 out parameters
                                                 );
            var newURL   = string.Format("{0}?{1}&oauth_signature={2}", out_url, parameters, HttpUtility.UrlEncode(signature));
            var req      = WebRequest.Create(newURL) as HttpWebRequest;
            var response = req.GetResponse();


            var reader = new StreamReader(response.GetResponseStream()); //JSON output
            var data   = reader.ReadToEnd();                             //converting to string

            return(data);
        }
コード例 #7
0
ファイル: OAuth.cs プロジェクト: LindseyB/Bibliomania
        // generates the url for accessing data that we need to use OAuth to access
        public string getOAuthDataUrl(string url)
        {
            OAuthBase oAuth = new OAuthBase();
            Uri uri = new Uri(url);
            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string normalizedUrl, normalizedRequestParameters;

            string sig = oAuth.GenerateSignature(uri, consumerKey, consumerSecret, oauthToken, oauthTokenSecret, "GET", timeStamp, nonce, out normalizedUrl, out normalizedRequestParameters);
            sig = HttpUtility.UrlEncode(sig);
            return normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + sig;
        }
コード例 #8
0
ファイル: OAuth.cs プロジェクト: LindseyB/Bibliomania
        // gets the oauth token if we do not have one already
        public void getOAuthToken()
        {
            OAuthBase oAuth = new OAuthBase();
            string nonce, normalizedUrl, normalizedRequestParameters, sig, timeStamp;
            Uri uri;

            // TODO: verify that the tokens we currently have are active and permission has not been revoked for the app
            if (Properties.Settings.Default.OAuthToken.Equals("") || Properties.Settings.Default.Equals("")) {
                uri = new Uri("http://www.goodreads.com/oauth/request_token");

                nonce = oAuth.GenerateNonce();
                timeStamp = oAuth.GenerateTimeStamp();
                sig = oAuth.GenerateSignature(uri, consumerKey, consumerSecret, null, null, "GET", timeStamp, nonce, out normalizedUrl, out normalizedRequestParameters);

                sig = HttpUtility.UrlEncode(sig);

                string request_url = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + sig;

                oauthTokenReq(request_url, out oauthToken, out oauthTokenSecret);

                // go get authorized
                uri = new Uri("http://www.goodreads.com/oauth/authorize");
                string oauthURL = uri.ToString() + "?oauth_token=" + oauthToken;
                // open a browser and allow the user to authorize
                System.Diagnostics.Process.Start(oauthURL);

                // Instead of sleeping prompt the user to verify that they entered their credentials before proceeding to the next step
                if (MessageBox.Show("Did you allow Bibliomania access?", "Confirm Access", MessageBoxButtons.YesNo) == DialogResult.No) {
                    Properties.Settings.Default.OAuthToken = "";
                    Properties.Settings.Default.OAuthTokenSecret = "";
                    Properties.Settings.Default.Save();
                    return;
                }

                uri = new Uri("http://www.goodreads.com/oauth/access_token");
                nonce = oAuth.GenerateNonce();
                timeStamp = oAuth.GenerateTimeStamp();
                // this time we need our oauth token and oauth token secret
                sig = oAuth.GenerateSignature(uri, consumerKey, consumerSecret, oauthToken, oauthTokenSecret, "GET", timeStamp, nonce, out normalizedUrl, out normalizedRequestParameters);
                sig = HttpUtility.UrlEncode(sig);

                // notice that the sig is always being appended to the end
                string accessUrl = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + sig;

                oauthTokenReq(accessUrl, out oauthToken, out oauthTokenSecret);
                // store these in the settings
                Properties.Settings.Default.OAuthToken = oauthToken;
                Properties.Settings.Default.OAuthTokenSecret = oauthTokenSecret;
                Properties.Settings.Default.Save();
            }
        }
コード例 #9
0
ファイル: ServiceClient.cs プロジェクト: rumbabu/Yuvaas
        public ReportResponse GetReport(String userCode, int widgetId)
        {
            ReportResponse reportResponse = new ReportResponse();
            try
            {
                string serverURL = ConfigurationManager.AppSettings["ServerURL"];
                string consumerKey = ConfigurationManager.AppSettings["ConsumerKey"];
                string consumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"];

                var uri = new Uri(serverURL + "Services/MystoreReportServices.svc/jauth/GetReportByType");

                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);

                object[] reportParams = new object[4] {url,
                "UserCode=" + userCode.ToUpper() + "&ReportDate=" + DateTime.Now.ToString() + "&WidgetId=" + widgetId.ToString(),
                param,
                HttpUtility.UrlEncode(signature) };

                string reqUrl = string.Format("{0}?{1}&{2}&oauth_signature={3}", reportParams);

                WebRequest request = WebRequest.Create(reqUrl);
                request.Method = "GET";
                request.ContentType = "application/json; charset=utf-8";
                request.Timeout = 10 * 60000;

                WebResponse responce = request.GetResponse();
                Stream reader = responce.GetResponseStream();
                StreamReader sReader = new StreamReader(reader);
                string strResponse = sReader.ReadToEnd();
                sReader.Close();

                //response
                JavaScriptSerializer jsSerzer = new JavaScriptSerializer();
                reportResponse = jsSerzer.Deserialize<ReportResponse>(strResponse);
            }
            catch (Exception ex)
            {
                reportResponse.ReportCharts = null;
                reportResponse.ReportsCount = 0;
            }

            return reportResponse;
        }
コード例 #10
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!LinkedPapers.User.LoggedIn()) Response.Redirect("/");

        string consumerKey = "*********";
        string consumerSecret = "*************";
        Uri uri = new Uri("https://api.dropbox.com/0/oauth/request_token"); 

        string s1, s2;

        OAuthBase oAuth = new OAuthBase();
        string nonce = oAuth.GenerateNonce();
        string timeStamp = oAuth.GenerateTimeStamp();
        string sig = oAuth.GenerateSignature(
            uri, 
            consumerKey, consumerSecret,  
            string.Empty, string.Empty,
            "GET", timeStamp, nonce, 
            OAuthBase.SignatureTypes.HMACSHA1,
            out s1, out s2
            ); 

        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); 

        string url = sb.ToString();

        WebRequest request = WebRequest.Create(url);


        using (WebResponse response = request.GetResponse())
        {

            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                string content = reader.ReadToEnd();

                Response.Redirect("https://www.dropbox.com/0/oauth/authorize?" + content + "&oauth_callback=" + Server.UrlEncode("http://dev.linkedpapers.com/Secure/User/Dropbox/DropboxOAuthCallback.aspx"));
            }
        }
    }
コード例 #11
0
ファイル: Method.cs プロジェクト: changman/yammyy
        public static string Get(string query, Session session)
        {
            OAuthBase oAuth = new OAuthBase();
            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string nurl, nrp;

            Uri uri = new Uri(query);
            string sig = oAuth.GenerateSignature(
                uri,
                session.Auth.ConsumerKey,
                session.Auth.ConsumerSecret,
                session.Auth.TokenKey,
                session.Auth.TokenSecret,
                "GET",
                timeStamp,
                nonce,
                OAuthBase.SignatureTypes.HMACSHA1, out nurl, out nrp);
            sig = HttpUtility.UrlEncode(sig);

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(query);
            req.Method = "GET";
            req.Proxy = session.Proxy;
            string authHeader = string.Empty;
            authHeader = "OAuth " +
                "oauth_consumer_key=\"" + session.Auth.ConsumerKey + "\"," +
                "oauth_token=\"" + session.Auth.TokenKey + "\"," +
                "oauth_nonce=\"" + nonce + "\"," +
                "oauth_timestamp=\"" + timeStamp + "\"," +
                "oauth_signature_method=\"" + "HMAC-SHA1" + "\"," +
                "oauth_version=\"" + "1.0" + "\"," +
                "oauth_signature=\"" + sig + "\"";
            req.ContentType = Constants.HttpPostUrlEncodedContentType;
            req.Headers.Add(Constants.AuthorizationHeaderParameter, authHeader);

            WebResponse res = req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
            string data = reader.ReadToEnd();

            res.Close();
            reader.Close();

            return data;
        }
コード例 #12
0
        static void Main(string[] args)
        {
            var webServices = new EPayWS.EpayServiceClient();

            var x = webServices.GetCustomerBillsOfLading(new UserDetails { UserName = "******", PassWord = "******" });

            string consumerKey = "test";
            string consumerSecret = "suryabhai";
            var uri = new Uri("https://ospf.kwljm.net:81/KW_WS_Published/KingstonWharvesWS.ContainerService.svc/ContainerSecured/1");
            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);
            WebResponse webrespon = (WebResponse)WebRequest.Create(
               string.Format("{0}?{1}&oauth_signature={2}", url, param, signature)).GetResponse();
            StreamReader stream = new StreamReader(webrespon.GetResponseStream());
            var Text = stream.ReadToEnd();
            Console.WriteLine(Text);
            Console.ReadKey();
        }
コード例 #13
0
        //
        // GET: /Home/
        public ActionResult Index()
        {
            //get user information from SIS
            var userId = "USERID";
            var userEmail = "*****@*****.**";
            var userFirstName = "John";
            var userLastName = "Doe";
            var userFullName = "John Doe";

            //get integration information from Tool Provider (e.g. TaskStream)
            var targetUrl = "https://www.tempuri.org/target/url";
            var consumerKey = "consumerkey";
            var sharedSecret = "sharedsecret";

            var oauthBase = new OAuthBase();

            var vm = new OAuthRequestViewModel
                {
                    UserId = userId,
                    LisPersonContactEmailPrimary = userEmail,
                    LisPersonNameGiven = userFirstName,
                    LisPersonNameFamily = userLastName,
                    LisPersonNameFull = userFullName,

                    //these values come from the Tool Provider
                    OauthConsumerKey = consumerKey,
                    TargetUrl = targetUrl,

                    OauthTimestamp = oauthBase.GenerateTimeStamp(),
                    OauthNonce = oauthBase.GenerateNonce(),
                };

            //shared secret from tool provider
            vm.OauthSignature = generateSignature(oauthBase, vm, sharedSecret);

            return View(vm);
        }
コード例 #14
0
ファイル: Auth.cs プロジェクト: changman/yammyy
        public string GetAccessTokenQuery(string consumerKey, string consumerSecret, string tokenKey, string tokenSecret,string v )
        {
            Uri uri = new Uri(Resources.OAUTH_ACCESSTOKEN);
            string nurl;
            string nrp;

            OAuthBase oAuth = new OAuthBase();
            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string sig = oAuth.GenerateSignature(
                uri,
                consumerKey,
                consumerSecret,
                tokenKey,
                tokenSecret,
                "POST",
                timeStamp,
                nonce,
            //                OAuthBase.SignatureTypes.HMACSHA1, out nurl, out nrp);
                OAuthBase.SignatureTypes.PLAINTEXT, out nurl, out nrp);
              //      sig = HttpUtility.UrlEncode(sig);

            StringBuilder sb = new StringBuilder(uri.ToString());
            sb.AppendFormat("?oauth_consumer_key={0}&", consumerKey);
            sb.AppendFormat("oauth_token={0}&", tokenKey);
            //            sb.AppendFormat("oauth_signature_method={0}&", "HMAC-SHA1");
            sb.AppendFormat("oauth_signature_method={0}&", "PLAINTEXT");
            sb.AppendFormat("oauth_timestamp={0}&", timeStamp);
            sb.AppendFormat("oauth_nonce={0}&", nonce);
            sb.AppendFormat("oauth_verifier={0}&", v);
            sb.AppendFormat("oauth_version={0}&", "1.0");
            sb.AppendFormat("oauth_signature={0}", sig);

            string query = sb.ToString();

            return query;
        }
コード例 #15
0
        public static string GetSignature(WebMethod method, OAuthToken consumerToken, OAuthToken oauthToken, string url, out string timestamp, out string nonce)
        {
            OAuthBase oAuth = new OAuthBase();
            nonce = oAuth.GenerateNonce();
            timestamp = oAuth.GenerateTimeStamp();
            string nurl, nrp;

            string tokenKey = oauthToken == null ? String.Empty : oauthToken.TokenKey;
            string tokenSecret = oauthToken == null ? String.Empty : oauthToken.TokenSecret;

            Uri uri = new Uri(url);
            string sig = oAuth.GenerateSignature(
                uri,
                consumerToken.TokenKey,
                consumerToken.TokenSecret,
                tokenKey,
                tokenSecret,
                method.ToString(),
                timestamp,
                nonce,
                OAuthBase.SignatureTypes.HMACSHA1, out nurl, out nrp);

            return System.Web.HttpUtility.UrlEncode(sig);
        }
コード例 #16
0
ファイル: Gimmie.cs プロジェクト: gimmie/proxies
        public JObject invoke(string action, Dictionary<string, string> parameters)
        {
            if (this.user_id == "") return null;

            string gimmieRoot = this.gimmieRoot;
            string endpoint = gimmieRoot + "/1/" + action + ".json?";
            string key = this.key;
            string secret = this.secret;

            foreach (KeyValuePair<string, string> parameter in parameters)
            {
                endpoint += HttpContext.Current.Server.UrlEncode(parameter.Key) + "=" + HttpContext.Current.Server.UrlEncode(parameter.Value) + "&";
            }

            endpoint.TrimEnd('&');

            string access_token_secret = secret;
            string access_token = user_id;
            string url = endpoint;

            var uri = new Uri(url);
            string url2, param;
            var oAuth = new OAuthBase();
            var nonce = oAuth.GenerateNonce();
            var timeStamp = oAuth.GenerateTimeStamp();
            var signature = System.Web.HttpUtility.UrlEncode(oAuth.GenerateSignature(uri, key, secret, access_token, access_token_secret, "GET", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1, out url2, out param));

            WebRequest req = WebRequest.Create(string.Format("{0}?{1}&oauth_signature={2}", url2, param, signature));
            WebResponse res = req.GetResponse();

            System.IO.Stream sm = res.GetResponseStream();
            System.IO.StreamReader s = new System.IO.StreamReader(sm);

            JObject o = Newtonsoft.Json.Linq.JObject.Parse(s.ReadToEnd());

            return o;
        }
コード例 #17
0
    private void TestOAuth()
    {
        var consumerKey = "3t82hBH8dF2ymlW";
        var consumerSecret = "79acbe81-7a9b-404f-94aa-7356c641e2e5";

        //var uri = new Uri("http://www.wgit-tech.com/shop/index.php/oauth/initiate");

        var uri = new Uri("https://testing.crunch.co.uk/crunch-core/oauth/request_token");
        Dictionary<string, string> extraParams = new Dictionary<string, string>();
        extraParams.Add("oauth_callback", "oob");

        // Generate a signature
        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, "POST", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1,
        out normalizedUrl, out parameters, extraParams);

        signature = HttpUtility.UrlEncode(signature);

        StringBuilder requestUri = new StringBuilder(normalizedUrl);
        requestUri.AppendFormat("?oauth_consumer_key={0}&", consumerKey);
        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);
        requestUri.AppendFormat("oauth_callback={0}", "oob");

        var request = (HttpWebRequest)WebRequest.Create(new Uri(requestUri.ToString()));
        request.Method = WebRequestMethods.Http.Post;
        try
        {
            string result = Process(requestUri.ToString(), string.Empty);

            var parts = result.Split('&');
            var token = parts[0].Substring(parts[0].IndexOf('=') + 1);
            var tokenSecret = parts[1].Substring(parts[1].IndexOf('=') + 1);

            result = String.Format("oauth_token={0}", token);
            var authorizeUrl = "http://www.wgit-tech.com/shop/index.php/admin/oauth_authorize?" + result;

            Response.Write("<script>window.open('" + authorizeUrl + "');</script>");

            string verifier = "u1ly8ykpthwqxexvej0oqew8kw4z3iiw";

            nonce = oAuth.GenerateNonce();
            timeStamp = oAuth.GenerateTimeStamp();

            uri = new Uri("http://www.wgit-tech.com/shop/index.php/oauth/token");

            extraParams = new Dictionary<string, string>();
            extraParams.Add("oauth_token", token);
            extraParams.Add("oauth_verifier", verifier);

            signature = oAuth.GenerateSignature(uri, consumerKey, consumerSecret,
            String.Empty, tokenSecret, "POST", timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1,
            out normalizedUrl, out parameters, extraParams);

            signature = HttpUtility.UrlEncode(signature);

            StringBuilder tokenUri = new StringBuilder(normalizedUrl);
            tokenUri.AppendFormat("?oauth_consumer_key={0}&", consumerKey);
            tokenUri.AppendFormat("oauth_nonce={0}&", nonce);
            tokenUri.AppendFormat("oauth_timestamp={0}&", timeStamp);
            tokenUri.AppendFormat("oauth_signature_method={0}&", "HMAC-SHA1");
            tokenUri.AppendFormat("oauth_version={0}&", "1.0");
            tokenUri.AppendFormat("oauth_signature={0}&", signature);
            tokenUri.AppendFormat("oauth_token={0}&", token);
            tokenUri.AppendFormat("oauth_verifier={0}", verifier);

            string finalResult = Process(tokenUri.ToString(), string.Empty);

            parts = result.Split('&');
            token = parts[0].Substring(parts[0].IndexOf('=') + 1);
            tokenSecret = parts[1].Substring(parts[1].IndexOf('=') + 1);
        }
        catch (WebException ex)
        {
            var response = (HttpWebResponse)ex.Response;
            var queryString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        }

        /*
        var oauth = new OAuth.Manager();
        // the URL to obtain a temporary "request token"
        var rtUrl = "http://www.wgit-tech.com/shop/index.php/oauth/initiate?oauth_callback=http://www.wgit-tech.com/shop/oauth_admin.php";
        oauth["consumer_key"] = "mw2jxs7rn059wza9q7a9kcd39uup9bze";
        oauth["consumer_secret"] = "448svpz44w3js7x9d9pg4my254g6osdl";
        oauth.AcquireRequestToken(rtUrl, "POST");
        */
    }
コード例 #18
0
    public static string url(string key, string secret, string email, string name, string uid, bool isSecure, Dictionary<string, string> additionalFields)
    {
        var oauth       = new OAuthBase();
        var coreParams  = new Dictionary<string, string>();
        var fastpassUri = "";
        var timestamp   = oauth.GenerateTimeStamp();
        var nonce       = oauth.GenerateNonce();
        var normUrl     = "";
        var normParms   = "";

        coreParams.Add("email", email);
        coreParams.Add("name", name);
        coreParams.Add("uid", uid);

        var parms = MergeParams(additionalFields, coreParams);

        if(isSecure) {
          fastpassUri = String.Format("https://{0}/fastpass?{1}", Domain, GetQueryString(parms));
        } else {
          fastpassUri = String.Format("http://{0}/fastpass?{1}", Domain, GetQueryString(parms));
        }

        Uri uri = new Uri(fastpassUri);

        var signature = oauth.GenerateSignature( uri, key, secret, null, null, "GET", timestamp, nonce, out normUrl, out normParms);

        return String.Format("{0}?{1}&oauth_signature={2}", normUrl, normParms, OAuthBase.UrlEncode(signature));
    }
コード例 #19
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string consumerKey = "5wwb2jtkwmxfmz1";
        string consumerSecret = "sbv5vp5jn75jcrg";
        Uri uri = new Uri("https://api.dropbox.com/0/oauth/access_token");

        string s1, s2;

        OAuthBase oAuth = new OAuthBase();
        string nonce = oAuth.GenerateNonce();
        string timeStamp = oAuth.GenerateTimeStamp();
        string sig = oAuth.GenerateSignature(
            uri,
            consumerKey, consumerSecret,
            string.Empty, string.Empty,
            "GET", timeStamp, nonce,
            OAuthBase.SignatureTypes.HMACSHA1,
            out s1, out s2
            );

        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);
        sb.AppendFormat("oauth_token={0}", Request.QueryString["oauth_token"]);

        //oauth_token: The Request Token obtained previously.
        
        string url = sb.ToString();


        WebRequest request = WebRequest.Create(url);


        using (WebResponse response = request.GetResponse())
        {

            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                string content = reader.ReadToEnd();

                string[] s = content.Split('&');

                string[] secret = ((string)s[0]).Split('=');
                string[] token = ((string)s[1]).Split('=');

                LinkedPapers.User u = LinkedPapers.User.Load();

                u.dropbox_secret = secret[1];
                u.dropbox_token = token[1];

                u.Save();

                Response.Redirect("/secure/user/bookshelf.aspx?dropbox=true");

            }
        }
    }
コード例 #20
0
ファイル: Session.cs プロジェクト: changman/yammyy
        private User GetCurrentUser(OAuthKey auth, WebProxy proxy)
        {
            #region OAuth
            OAuthBase oAuth = new OAuthBase();
            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string nurl, nrp;
            string query = Resources.USERS_CURRENT + "?";

            Uri uri = new Uri(query);
            string sig = oAuth.GenerateSignature(
                uri,
                auth.ConsumerKey,
                auth.ConsumerSecret,
                auth.TokenKey,
                auth.TokenSecret,
                "GET",
                timeStamp,
                nonce,
                OAuthBase.SignatureTypes.PLAINTEXT, out nurl, out nrp);
             //   sig = HttpUtility.UrlEncode(sig);
            StringBuilder sb = new StringBuilder(uri.ToString());
            sb.AppendFormat("oauth_consumer_key={0}&", auth.ConsumerKey);
            sb.AppendFormat("oauth_token={0}&", auth.TokenKey);
              //  sb.AppendFormat("oauth_signature_method={0}&", "HMAC-SHA1");
            sb.AppendFormat("oauth_signature_method={0}&", "PLAINTEXT");
            sb.AppendFormat("oauth_timestamp={0}&", timeStamp);
            sb.AppendFormat("oauth_nonce={0}&", nonce);
            sb.AppendFormat("oauth_version={0}&", "1.0");
            sb.AppendFormat("oauth_signature={0}", sig);
            query = sb.ToString();
            #endregion

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(query);
            req.Method = "GET";
            req.PreAuthenticate = true;
            req.Accept = "text/xml, application/xml";
            req.Proxy = proxy;

            WebResponse res = req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
            string data = reader.ReadToEnd();
            reader.Close();
            res.Close();

            #region XmlDocument
            User u = new User();
            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml(data);

            u.JobTitle = xdoc.SelectSingleNode("/response/job-title").InnerText;
            u.FullName = xdoc.SelectSingleNode("/response/full-name").InnerText;
            u.MugshotUrl = new Uri(xdoc.SelectSingleNode("/response/mugshot-url").InnerText);
            u.Name = xdoc.SelectSingleNode("/response/name").InnerText;
            u.Url = new Uri(xdoc.SelectSingleNode("/response/url").InnerText);
            u.WebUrl = new Uri(xdoc.SelectSingleNode("/response/web-url").InnerText);
            u.Id = int.Parse(xdoc.SelectSingleNode("/response/id").InnerText);

            #region extend
            UserExtention ux = new UserExtention();
            ux.NetworkName = xdoc.SelectSingleNode("/response/network-name").InnerText;
            ux.NetworkId = int.Parse(xdoc.SelectSingleNode("/response/network-id").InnerText);
            ux.BirthDate = xdoc.SelectSingleNode("/response/birth-date").InnerText;
            //    ux.HireDate = DateTime.ParseExact(xdoc.SelectSingleNode("/response/hire-date").InnerText, "yyyy-MM-dd", null);
            Status s = new Status();
            s.Followers = int.Parse(xdoc.SelectSingleNode("/response/stats/followers").InnerText);
            s.Following = int.Parse(xdoc.SelectSingleNode("/response/stats/following").InnerText);
            s.Updates = int.Parse(xdoc.SelectSingleNode("/response/stats/updates").InnerText);
            ux.Status = s;

            Location l = new Location();
            //l.Id = int.Parse(xdoc.SelectSingleNode("/response/location/id").InnerText);
            //l.UserId = int.Parse(xdoc.SelectSingleNode("/response/location/user-id").InnerText);
            //l.Name = xdoc.SelectSingleNode("/response/location/name").InnerText;
            //l.Value = xdoc.SelectSingleNode("/response/location/value").InnerText;
            //l.CreatedAt = DateTime.ParseExact(
            //    xdoc.SelectSingleNode("/response/location/created-at").InnerText,
            //    "yyyy-MM-ddTHH:mm:ssZ", null);
            //l.UpdatedAt = DateTime.ParseExact(
            //    xdoc.SelectSingleNode("/response/location/updated-at").InnerText,
            //    "yyyy-MM-ddTHH:mm:ssZ", null);
            ux.Location = l;

            Contact c = new Contact();
            List<EmailAddress> emails = new List<EmailAddress>();
            foreach (XmlNode aNode in xdoc.SelectNodes("/response/contact/email-address"))
            {
                EmailAddress email = new EmailAddress();
                email.Type = aNode.SelectSingleNode("type").InnerText;
                email.Address = aNode.SelectSingleNode("address").InnerText;
                emails.Add(email);
            }
            c.EmailAddresses = emails;
            List<PhoneNumber> phones = new List<PhoneNumber>();
            foreach (XmlNode pNode in xdoc.SelectNodes("/response/contact/phone-number"))
            {
                PhoneNumber phone = new PhoneNumber();
                phone.Type = pNode.SelectSingleNode("type").InnerText;
                phone.Number = pNode.SelectSingleNode("number").InnerText;
                phones.Add(phone);
            }
            c.PhoneNumbers = phones;
            Im im = new Im();
            im.UserName = xdoc.SelectSingleNode("/response/contact/im/username").InnerText;
            im.Provider = xdoc.SelectSingleNode("/response/contact/im/provider").InnerText;
            c.Im = im;
            ux.Contact = c;

            u.Extention = ux;
            #endregion

            #endregion

            #region case LINQ
            //var xml = XElement.Parse(Encoding.UTF8.GetString(data));
            //var result = from response in xml.Root.Elements()
            //             select new User
            //             {
            //                 Id = int.Parse(response.Element("id").Value),
            //                 NetworkName = response.Element("network-name").Value,
            //                 Name = response.Element("name").Value,
            //                 FullName = response.Element("full-name").Value,
            //                 JobTitle = response.Element("job-title").Value,
            //                 NetworkId = int.Parse(response.Element("network-id").Value),
            //                 BirthDate = response.Element("birth-date").Value,
            //                 Url = new Uri(response.Element("url").Value),
            //                 MugshotUrl = new Uri(response.Element("mugshot-url").Value),
            //                 HireDate = DateTime.ParseExact(response.Element("hire-date").Value, "yyyy-MM-dd", null),
            //                 WebUrl = new Uri(response.Element("web-url").Value),
            //             };
            #endregion

            return u;
        }
コード例 #21
0
ファイル: Tambur.cs プロジェクト: tamburio/csharp-tambur
        /// <summary>
        /// Publish a message
        /// </summary>
        /// <param name="stream">Name of the stream.</param>
        /// <param name="message">Message contents (RAW, not URLencoded).</param>
        public void Publish(String stream, String message)
        {
            message = UrlEncode(message);

            // prepare URL
            var path = string.Format(ConstUrlPath, _appId, UrlEncode(stream), message);
            var url = string.Format(UseSSL ? ConstUrlSSL : ConstUrl, _apiHost, path);

            // prepare & issue signuate
            var oAuth = new OAuthBase();
            var timeStamp = oAuth.GenerateTimeStamp();
            var nonce = oAuth.GenerateNonce();

            string normalizedUrl;
            string normalizedRequestParameters;

            var res = oAuth.GenerateSignature(new Uri(url),
                                                 _apiKey, _secret,
                                                 string.Empty, string.Empty,
                                                 "POST", timeStamp, nonce, out normalizedUrl,
                                                 out normalizedRequestParameters);

            // prepare Post Body
            var postBody = normalizedRequestParameters;
            postBody += string.Format("&oauth_signature={0}", res);

            try
            {
                // post to api host
                using (var wc = new WebClient())
                {
                    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                    wc.Encoding = Encoding.UTF8;
                    wc.UploadString(url, postBody);
                }
            }
            catch (Exception exRequest)
            {
                throw new TamburClientCommunicationException(
                    string.Format("Error sending you request to {0} See InnerExpeption for details. ({1})", _apiHost,
                                  exRequest.Message), exRequest);
            }
        }
コード例 #22
0
ファイル: Form1.cs プロジェクト: bemk/rhc
        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                String personName = "";

                string consumerKey = "key";
            string consumerSecret = "secret";
            Uri uri = new Uri("https://api.twitter.com/oauth/request_token");

            OAuthBase oAuth = new OAuthBase();
            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string sig = oAuth.GenerateSignature(uri,
                consumerKey, consumerSecret,
                string.Empty, string.Empty,
                "GET", timeStamp, nonce,
                OAuthBase.SignatureTypes.HMACSHA1);

            sig = HttpUtility.UrlEncode(sig);

            StringBuilder stb = new StringBuilder(uri.ToString());
            stb.AppendFormat("?oauth_consumer_key={0}&", consumerKey);
            stb.AppendFormat("oauth_nonce={0}&", nonce);
            stb.AppendFormat("oauth_timestamp={0}&", timeStamp);
            stb.AppendFormat("oauth_signature_method={0}&", "HMAC-SHA1");
            stb.AppendFormat("oauth_version={0}&", "1.0");
            stb.AppendFormat("oauth_signature={0}", sig);

            System.Diagnostics.Debug.WriteLine(stb.ToString());

                StringBuilder sb = new StringBuilder();
                byte[] buf = new byte[8192];

                string user =
            Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(txtID.Text + ":" +
            txtPasswd.Text));

                HttpWebRequest request =
            (HttpWebRequest)WebRequest.Create("http://twitter.com/account/verify_credentials.xml");

                request.Method = "GET";

                request.Headers.Add("Authorization", "Basic " + user);
                request.ContentType = "application/x-www-form-urlencoded";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream resStream = response.GetResponseStream();

                string tempStream = null;
                int count = 0;

                do
                {
                    count = resStream.Read(buf, 0, buf.Length);

                    if (count != 0)
                    {
                        tempStream = Encoding.ASCII.GetString(buf, 0, count);
                        sb.Append(tempStream);
                    }
                }
                while (count > 0);

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(sb.ToString());

                XmlNodeList nodeList = doc.SelectNodes("/user/name");
                foreach (XmlNode node in nodeList)
                {
                    personName = node.InnerText;
                }

                lblMessage.Text = "Welcome, " + personName + "!";
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                if (ex.Message.Contains("Unauthorized"))
                {
                    lblMessage.Text = "Invalid User ID and/or Password.";
                }
                else if (ex.Message.Contains("Service Unavailable"))
                {
                    lblMessage.Text = "Twitter is busy, try again later";
                }
                else
                {
                    lblMessage.Text = ex.Message;
                }
            }
        }
コード例 #23
0
        public void GenerateSignature()
        {
            OAuthBase.SignatureTypes signatureType = OAuthBase.SignatureTypes.HMACSHA1;
            string normalizedUrl = null;
            string normalizedRequestParameters = null;
            var myOAuth = new OAuthBase();
            try
            {
                var uri = new Uri(_view.Uri);

                string consumerKey = _view.ConsumerKey;
                string consumerSecret = _view.ConsumerSecret;
                string token = _view.Token;
                string tokenSecret = _view.TokenSecret;
                string httpMethod = _view.HttpMethod;
                string timeStamp = _view.TimeStamp;
                string nonce = _view.Nonce;

                if (String.IsNullOrEmpty(timeStamp))
                {
                    timeStamp = myOAuth.GenerateTimeStamp();
                    _view.TimeStamp = timeStamp;
                }

                if (String.IsNullOrEmpty(nonce))
                {
                    nonce = myOAuth.GenerateNonce();
                    _view.Nonce = nonce;
                }

                switch (_view.SignatureMethod)
                {
                    case 0:
                        signatureType = OAuthBase.SignatureTypes.HMACSHA1;
                        break;
                    case 1:
                        signatureType = OAuthBase.SignatureTypes.PLAINTEXT;
                        break;
                    case 2:
                        signatureType = OAuthBase.SignatureTypes.RSASHA1;
                        break;
                }

                myOAuth.includeVersion = _view.IncludeVersion;

                string signature = "";
                if (httpMethod == "POST")
                {
                    Dictionary<string, string> dictionary = new OAuthPostRequest().GetFormVariables(_view.PostData);
                    signature = myOAuth.GenerateSignature(uri, consumerKey, consumerSecret, token, tokenSecret, httpMethod,
                                                          timeStamp, nonce, signatureType, out normalizedUrl,
                                                          out normalizedRequestParameters, dictionary);
                }
                else
                {
                    signature = myOAuth.GenerateSignature(uri, consumerKey, consumerSecret,
                                                          token, tokenSecret, httpMethod,
                                                          timeStamp, nonce, signatureType,
                                                          out normalizedUrl,
                                                          out normalizedRequestParameters, null);
                }

                _view.RawSignature = signature;
                _view.EncodedSignature = myOAuth.UrlEncode(signature);

                _view.GeneratedUrl = normalizedUrl + "?" + normalizedRequestParameters +
                                     "&oauth_signature=" + _view.EncodedSignature;
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }
コード例 #24
0
        protected WebResponse rawRequest(String method, Uri uri, List <QueryParameter> data)
        {
            string nonce     = oAuthBase.GenerateNonce();
            string timeStamp = oAuthBase.GenerateTimeStamp();
            string parameters;
            string normalizedUrl;
            Uri    signingUri = new Uri(uri.ToString());

            byte[] postData = null;

            if (method == "POST" || method == "PUT")
            {
                String paramString = "";
                foreach (QueryParameter p in data)
                {
                    paramString += UrlEncode(p.Key) + "=" + UrlEncode(p.Value) + "&";
                }
                paramString = paramString.Remove(paramString.Length - 1);
                if (uri.ToString().Contains("?"))
                {
                    signingUri = new Uri(uri.ToString() + "&" + paramString);
                }
                else
                {
                    signingUri = new Uri(uri.ToString() + "?" + paramString);
                }

                postData = Encoding.ASCII.GetBytes(paramString);
            }

            string signature = oAuthBase.GenerateSignature(signingUri, ConsumerKey, ConsumerSecret,
                                                           Token.Token, Token.Secret, method, timeStamp, nonce, OAuthBase.SignatureTypes.HMACSHA1,
                                                           out normalizedUrl, out parameters);

            signature = HttpUtility.UrlEncode(signature);

            StringBuilder requestUri = new StringBuilder(uri.ToString());

            if (uri.ToString().Contains("?"))
            {
                requestUri.Append("&");
            }
            else
            {
                requestUri.Append("?");
            }
            requestUri.AppendFormat("oauth_consumer_key={0}&", ConsumerKey);
            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);
            if (Token.Token != String.Empty)
            {
                requestUri.AppendFormat("&oauth_token={0}", Token.Token);
            }

            var request = (HttpWebRequest)WebRequest.Create(new Uri(requestUri.ToString()));

            request.Method = method;

            if (postData != null)
            {
                request.ContentType   = "application/x-www-form-urlencoded";
                request.ContentLength = postData.Length;
                Stream dataStream = request.GetRequestStream();
                dataStream.Write(postData, 0, postData.Length);
                dataStream.Close();
            }

            var response = request.GetResponse();

            return(response);
        }
コード例 #25
0
ファイル: TkRest.cs プロジェクト: M1Sports20/TkApi.NET
		private string RequestSync(RequestData req) {
			if (req.method.ToString() != "GET" && !allowWrite) {
				return "";
			}
			
			// Build URI
			StringBuilder sbUri = new StringBuilder(BaseUri);
			sbUri.Append(req.call);
			sbUri.Append("." + Format.ToString().ToLower());
			
			// Query Params
			if (req.queryParams != null) {
				sbUri.Append("?");
				foreach (string idx in req.queryParams.AllKeys) {
					sbUri.AppendFormat("{0}={1}&", Uri.EscapeDataString(idx), Uri.EscapeDataString(req.queryParams[idx]));
				}
				sbUri.Remove(sbUri.Length - 1, 1);
			}
			
			Uri uri = new Uri(sbUri.ToString());
			
			// Create Request
			OAuthBase oAuth = new OAuthBase();
			string nonce = oAuth.GenerateNonce();
			string timeStamp = oAuth.GenerateTimeStamp();
			string normRequestUrl;
			string normRequestParam;
			
			string sig = oAuth.GenerateSignature(uri, ConsumerKey, ConsumerSecret, AccessToken, AccessSecret, 
				req.method.ToString(), timeStamp, nonce, out normRequestUrl, out normRequestParam);
			
			ServicePointManager.ServerCertificateValidationCallback = Validator;
			// normRequestParam += "&oauth_signature=" + sig;
			//Console.WriteLine(normRequestUrl + normRequestParam);
			HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(sbUri.ToString());
			webReq.Method = req.method.ToString();
			if (req.authRequired) {
				StringBuilder authHdr = new StringBuilder();
	            authHdr.Append("OAuth ");
	            authHdr.AppendFormat("oauth_consumer_key=\"{0}\",", HttpUtility.UrlEncode(ConsumerKey));
	            authHdr.AppendFormat("oauth_token=\"{0}\",", HttpUtility.UrlEncode(AccessToken));
	            authHdr.AppendFormat("oauth_signature_method=\"{0}\",", HttpUtility.UrlEncode(OAuthSignatureMethod));
	            authHdr.AppendFormat("oauth_signature=\"{0}\",", HttpUtility.UrlEncode(sig));
	            authHdr.AppendFormat("oauth_timestamp=\"{0}\",", HttpUtility.UrlEncode(timeStamp));
	            authHdr.AppendFormat("oauth_nonce=\"{0}\",", HttpUtility.UrlEncode(nonce));
	            authHdr.AppendFormat("oauth_version=\"{0}\",", HttpUtility.UrlEncode(OAuthVersion));
				webReq.Headers.Add("Authorization", authHdr.ToString());
			}
			
			// Header Params
			if (req.headerParams != null) {
				webReq.Headers.Add(req.headerParams);
			}
			
			// POST Data
			if (!String.IsNullOrEmpty(req.postData)) {
				
				ASCIIEncoding objEncoding = new ASCIIEncoding();
				byte[] objBytes = objEncoding.GetBytes(req.postData);
				webReq.ContentLength = objBytes.Length;
				webReq.ContentType = "application/x-www-form-urlencoded";
				Stream postStream = webReq.GetRequestStream();
				postStream.Write(objBytes, 0, objBytes.Length);
			}
			
			// Send web request and colleciton response
			WebResponse webResp = webReq.GetResponse();
			Stream respStream = webResp.GetResponseStream();
			StreamReader respReader = new StreamReader(respStream);
			string resp = respReader.ReadToEnd();
			
			// Save Response Headers
			string header;
			header = webResp.Headers[RateLimitUsedHeader];
			if (!String.IsNullOrEmpty(header)) XRateLimitUsed = header;
			header = webResp.Headers[RateLimitExpireHeader];
			if (!String.IsNullOrEmpty(header)) XRateLimitExpire = header;
			header = webResp.Headers[RateLimitLimitHeader];
			if (!String.IsNullOrEmpty(header)) XRateLimitLimit = header;
			header = webResp.Headers[RateLimitRemainingHeader];
			if (!String.IsNullOrEmpty(header)) XRateLimitRemaining = header;
			
			respReader.Close();
			respStream.Close();
			webResp.Close();
			
			//Console.WriteLine(resp);
			return StripResponseProperty(resp);
		}
コード例 #26
0
ファイル: Service1.svc.cs プロジェクト: amoldp/DSOD-Project
        // Help formatting the request: http://stackoverflow.com/questions/6036934/accessing-yelps-oauth-1-0a-api-with-dotnetopenauth
        public string getNearestStore(string place,string location)
        {
            //string yelpSearchUrl = "http://api.yelp.com/v2/search?" +
            //"term=" + place + "&location=" + location;

            /*
            string formattedUri = String.Format(System.Globalization.CultureInfo.InvariantCulture, yelpSearchUrl, "");
            Uri urlUri = new Uri(formattedUri);
            string outNormalisedUrl = "";
            string outNormalisedRequestParameters = "";

            OAuth.OAuthBase oauthBase = new OAuth.OAuthBase();
            string oauthSignature = oauthBase.GenerateSignature(
            urlUri,
            oauthConsumerKey,
            oauthConsumerSecret,
            oauthToken,
            oauthTokenSecret,
            "GET",
            oauthBase.GenerateTimeStamp(),
            oauthBase.GenerateNonce(),
            out outNormalisedUrl,
            out outNormalisedRequestParameters);

            string urlString = outNormalisedUrl + "?" + outNormalisedRequestParameters +
            "&oauth_signature=" + oauthSignature;
            */
                    OAuth.OAuthBase oA = new OAuth.OAuthBase(); //authorization class object

            var _url = String.Format("http://api.yelp.com/v2/search?term={0}&location={1}&limit=10&category_filter=food", place, location); //URL for calling RESTful api for yelp.
            string parameters, out_url;
            Uri uri = new Uri(_url);
            //authorizing the request
            var signature = oA.GenerateSignature(uri,
                                    ConfigurationManager.AppSettings["YelpConsumerKey"],
                                    ConfigurationManager.AppSettings["YelpConsumerSecret"],
                                    ConfigurationManager.AppSettings["YelpToken"],
                                    ConfigurationManager.AppSettings["YelpTokenSecret"],
                                    "GET",
                                    oA.GenerateTimeStamp(),
                                    oA.GenerateNonce(),
                                    OAuth.OAuthBase.SignatureTypes.HMACSHA1,
                                    out out_url,
                                    out parameters
                                    );
            var newURL = string.Format("{0}?{1}&oauth_signature={2}", out_url, parameters, HttpUtility.UrlEncode(signature));
            var req = WebRequest.Create(newURL) as HttpWebRequest;
            var response = req.GetResponse();

            var reader = new StreamReader(response.GetResponseStream()); //JSON output
            var data = reader.ReadToEnd(); //converting to string
            return data;
        }
コード例 #27
0
ファイル: HttpUtility.cs プロジェクト: victorlxj/yammer.net
        public static string GetSignature(WebMethod method, string url, out string timestamp, out string nonce)
        {
            OAuthBase oAuth = new OAuthBase();
            nonce = oAuth.GenerateNonce();
            timestamp = oAuth.GenerateTimeStamp();
            string nurl, nrp;

            Uri uri = new Uri(url);
            string sig = oAuth.GenerateSignature(
                uri,
                Yammer.Session.Auth.Key.ConsumerKey,
                Yammer.Session.Auth.Key.ConsumerSecret,
                Yammer.Session.Auth.Key.TokenKey,
                Yammer.Session.Auth.Key.TokenSecret,
                method.ToString(),
                timestamp,
                nonce,
                OAuthBase.SignatureTypes.PLAINTEXT, out nurl, out nrp);

            return System.Web.HttpUtility.UrlEncode(sig);
        }
コード例 #28
0
ファイル: Method.cs プロジェクト: changman/yammyy
        public static string Post(string query, NameValueCollection parameters, Session session)
        {
            OAuthBase oAuth = new OAuthBase();
            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string nurl, nrp;
            string q = string.Empty;
            int count = 0;

            foreach (string key in parameters.Keys)
            {
                if (count == 0)
                {
                    q = query + "?" + key + "=" + Rfc3986.Encode(parameters[key]);
                }
                else
                {
                    q += "&" + key + "=" + Rfc3986.Encode(parameters[key]);
                }
                count++;
            }

            Uri uri = new Uri(q);
            string sig = oAuth.GenerateSignature(
                uri,
                session.Auth.ConsumerKey,
                session.Auth.ConsumerSecret,
                session.Auth.TokenKey,
                session.Auth.TokenSecret,
                "POST",
                timeStamp,
                nonce,
                OAuthBase.SignatureTypes.HMACSHA1, out nurl, out nrp);
            sig = HttpUtility.UrlEncode(sig);

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(query);

            req.Method = "POST";
            req.Proxy = session.Proxy;
            string authHeader = string.Empty;
            authHeader = "OAuth " +
                "realm=\"" + Resources.MESSAGES_POST + "\"," +
                "oauth_consumer_key=\"" + session.Auth.ConsumerKey + "\"," +
                "oauth_token=\"" + session.Auth.TokenKey + "\"," +
                "oauth_nonce=\"" + nonce + "\"," +
                "oauth_timestamp=\"" + timeStamp + "\"," +
                "oauth_signature_method=\"" + "HMAC-SHA1" + "\"," +
                "oauth_version=\"" + "1.0" + "\"," +
                "oauth_signature=\"" + sig + "\"";
            req.ContentType = Constants.HttpPostUrlEncodedContentType;
            req.Headers.Add(Constants.AuthorizationHeaderParameter, authHeader);

            count = 0;
            string wdata = string.Empty;
            foreach (string key in parameters.Keys)
            {
                if (count == 0)
                {
                    wdata = key + "=" + Rfc3986.Encode(parameters[key]);
                }
                else
                {
                    wdata += "&" + key + "=" + Rfc3986.Encode(parameters[key]);
                }
                count++;
            }

            byte[] postDataBytes = Encoding.ASCII.GetBytes(wdata);
            req.ContentLength = postDataBytes.Length;
            Stream reqStream = req.GetRequestStream();
            reqStream.Write(postDataBytes, 0, postDataBytes.Length);
            reqStream.Close();

            WebResponse res = req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8);
            string data = reader.ReadToEnd();
            reader.Close();
            res.Close();

            return data;
        }