GenerateSignature() 공개 메소드

Generates a signature using the specified signatureType
public GenerateSignature ( Uri url, string consumerKey, string consumerSecret, string token, string tokenSecret, string httpMethod, string timeStamp, string nonce, SignatureTypes signatureType, string &normalizedUrl, string &normalizedRequestParameters ) : string
url System.Uri The full url that needs to be signed including its non OAuth url parameters
consumerKey string The consumer key
consumerSecret string The consumer seceret
token string The token, if available. If not available pass null or an empty string
tokenSecret string The token secret, if available. If not available pass null or an empty string
httpMethod string The http method used. Must be a valid HTTP method verb (POST,GET,PUT, etc)
timeStamp string
nonce string
signatureType SignatureTypes The type of signature to use
normalizedUrl string
normalizedRequestParameters string
리턴 string
예제 #1
0
        //
        // 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
            //    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
        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
        // 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
        // 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
        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;
        }
    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"));
            }
        }
    }
        public bool Authenticate(OperationContext operationContext)
        {
            bool Authenticated = false;

            string normalizedUrl;
            string normalizedRequestParameters;

            // to get the httpmethod

            HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)(operationContext.RequestContext.RequestMessage).Properties[HttpRequestMessageProperty.Name];

            string httpmethod = requestProperty.Method;

            // HttpContext.Current is null, so forget about it
            // HttpContext context = HttpContext.Current;

            NameValueCollection pa = HttpUtility.ParseQueryString(operationContext.IncomingMessageProperties.Via.Query);

            if (pa != null && pa["oauth_consumer_key"] != null)
            {
                // to get uri without oauth parameters
                string uri = operationContext.IncomingMessageProperties
                .Via.OriginalString.Replace
                   (operationContext.IncomingMessageProperties
                .Via.Query, "");

                string consumersecret = "secret";

                OAuthBase oauth = new OAuthBase();

                string hash = oauth.GenerateSignature(
                    new Uri(uri),
                    pa["oauth_consumer_key"],
                    consumersecret,
                    null, // totken
                    null, //token secret
                    httpmethod,
                    pa["oauth_timestamp"],
                    pa["oauth_nonce"],
                    out normalizedUrl,
                    out normalizedRequestParameters
                    );
                Authenticated = pa["oauth_signature"] == hash;
            }
            return Authenticated;
        }
예제 #12
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;
        }
예제 #13
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();
        }
예제 #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;
        }
    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");
        */
    }
예제 #16
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));
    }
    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");

            }
        }
    }
예제 #18
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;
        }
예제 #19
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);
        }
        private string generateSignature(OAuthBase oauthBase, OAuthRequestViewModel vm, string sharedSecret)
        {
            var url = new StringBuilder(vm.TargetUrl);

            //if there were no querystring parameters and the last character of the url isn't a ?, add one
            //otherwise add an ampersand
            url.Append(url[url.Length - 1] != '?' ? '?' : '&');

            #region append all properties to query string

            url.AppendFormat("{0}={1}&", "context_id", string.IsNullOrEmpty(vm.ContextId) ? null : oauthBase.UrlEncode(vm.ContextId));
            url.AppendFormat("{0}={1}&", "context_label", string.IsNullOrEmpty(vm.ContextLabel) ? null : oauthBase.UrlEncode(vm.ContextLabel));
            url.AppendFormat("{0}={1}&", "context_title", string.IsNullOrEmpty(vm.ContextTitle) ? null : oauthBase.UrlEncode(vm.ContextTitle));
            url.AppendFormat("{0}={1}&", "context_type", string.IsNullOrEmpty(vm.ContextType) ? null : oauthBase.UrlEncode(vm.ContextType));
            url.AppendFormat("{0}={1}&", "ext_lms", string.IsNullOrEmpty(vm.ExtLms) ? null : oauthBase.UrlEncode(vm.ExtLms));
            url.AppendFormat("{0}={1}&", "launch_presentation_document_target", string.IsNullOrEmpty(vm.LaunchPresentationDocumentTarget) ? null : oauthBase.UrlEncode(vm.LaunchPresentationDocumentTarget));
            url.AppendFormat("{0}={1}&", "launch_presentation_locale", string.IsNullOrEmpty(vm.LaunchPresentationLocale) ? null : oauthBase.UrlEncode(vm.LaunchPresentationLocale));
            url.AppendFormat("{0}={1}&", "launch_presentation_return_url", string.IsNullOrEmpty(vm.LaunchPresentationReturnUrl) ? null : oauthBase.UrlEncode(vm.LaunchPresentationReturnUrl));
            url.AppendFormat("{0}={1}&", "lis_course_offering_sourcedid", string.IsNullOrEmpty(vm.LisCourseOfferingSourcedid) ? null : oauthBase.UrlEncode(vm.LisCourseOfferingSourcedid));
            url.AppendFormat("{0}={1}&", "lis_course_section_sourcedid", string.IsNullOrEmpty(vm.LisCourseSectionSourcedid) ? null : oauthBase.UrlEncode(vm.LisCourseSectionSourcedid));
            url.AppendFormat("{0}={1}&", "lis_person_contact_email_primary", string.IsNullOrEmpty(vm.LisPersonContactEmailPrimary) ? null : oauthBase.UrlEncode(vm.LisPersonContactEmailPrimary));
            url.AppendFormat("{0}={1}&", "lis_person_name_family", string.IsNullOrEmpty(vm.LisPersonNameFamily) ? null : oauthBase.UrlEncode(vm.LisPersonNameFamily));
            url.AppendFormat("{0}={1}&", "lis_person_name_full", string.IsNullOrEmpty(vm.LisPersonNameFull) ? null : oauthBase.UrlEncode(vm.LisPersonNameFull));
            url.AppendFormat("{0}={1}&", "lis_person_name_given", string.IsNullOrEmpty(vm.LisPersonNameGiven) ? null : oauthBase.UrlEncode(vm.LisPersonNameGiven));
            url.AppendFormat("{0}={1}&", "lti_message_type", string.IsNullOrEmpty(vm.LtiMessageType) ? null : oauthBase.UrlEncode(vm.LtiMessageType));
            url.AppendFormat("{0}={1}&", "lti_version", string.IsNullOrEmpty(vm.LtiVersion) ? null : oauthBase.UrlEncode(vm.LtiVersion));
            url.AppendFormat("{0}={1}&", "oauth_callback", string.IsNullOrEmpty(vm.OauthCallback) ? null : oauthBase.UrlEncode(vm.OauthCallback));
            url.AppendFormat("{0}={1}&", "oauth_consumer_key", string.IsNullOrEmpty(vm.OauthConsumerKey) ? null : oauthBase.UrlEncode(vm.OauthConsumerKey));
            url.AppendFormat("{0}={1}&", "oauth_nonce", string.IsNullOrEmpty(vm.OauthNonce) ? null : oauthBase.UrlEncode(vm.OauthNonce));
            url.AppendFormat("{0}={1}&", "oauth_signature", string.IsNullOrEmpty(vm.OauthSignature) ? null : oauthBase.UrlEncode(vm.OauthSignature));
            url.AppendFormat("{0}={1}&", "oauth_signature_method", string.IsNullOrEmpty(vm.OauthSignatureMethod) ? null : oauthBase.UrlEncode(vm.OauthSignatureMethod));
            url.AppendFormat("{0}={1}&", "oauth_timestamp", string.IsNullOrEmpty(vm.OauthTimestamp) ? null : oauthBase.UrlEncode(vm.OauthTimestamp));
            url.AppendFormat("{0}={1}&", "oauth_version", string.IsNullOrEmpty(vm.OauthVersion) ? null : oauthBase.UrlEncode(vm.OauthVersion));
            url.AppendFormat("{0}={1}&", "resource_link_id", string.IsNullOrEmpty(vm.ResourceLinkId) ? null : oauthBase.UrlEncode(vm.ResourceLinkId));
            url.AppendFormat("{0}={1}&", "resource_link_title", string.IsNullOrEmpty(vm.ResourceLinkTitle) ? null : oauthBase.UrlEncode(vm.ResourceLinkTitle));
            url.AppendFormat("{0}={1}&", "tool_consumer_info_product_family_code", string.IsNullOrEmpty(vm.ToolConsumerInfoProductFamilyCode) ? null : oauthBase.UrlEncode(vm.ToolConsumerInfoProductFamilyCode));
            url.AppendFormat("{0}={1}&", "tool_consumer_info_version", string.IsNullOrEmpty(vm.ToolConsumerInfoVersion) ? null : oauthBase.UrlEncode(vm.ToolConsumerInfoVersion));
            url.AppendFormat("{0}={1}&", "tool_consumer_instance_description", string.IsNullOrEmpty(vm.ToolConsumerInstanceDescription) ? null : oauthBase.UrlEncode(vm.ToolConsumerInstanceDescription));
            url.AppendFormat("{0}={1}&", "tool_consumer_instance_guid", string.IsNullOrEmpty(vm.ToolConsumerInstanceGuid) ? null : oauthBase.UrlEncode(vm.ToolConsumerInstanceGuid));
            url.AppendFormat("{0}={1}&", "tool_consumer_instance_name", string.IsNullOrEmpty(vm.ToolConsumerInstanceName) ? null : oauthBase.UrlEncode(vm.ToolConsumerInstanceName));
            url.AppendFormat("{0}={1}&", "tool_consumer_instance_url", string.IsNullOrEmpty(vm.ToolConsumerInstanceUrl) ? null : oauthBase.UrlEncode(vm.ToolConsumerInstanceUrl));
            url.AppendFormat("{0}={1}&", "user_id", string.IsNullOrEmpty(vm.UserId) ? null : oauthBase.UrlEncode(vm.UserId));

            #endregion

            string normalizedUrl;
            string normalizedRequestParameters;

            return oauthBase.GenerateSignature(new Uri(url.ToString()),
                vm.OauthConsumerKey,
                sharedSecret,
                null,
                null,
                "POST",
                vm.OauthTimestamp,
                vm.OauthNonce,
                out normalizedUrl, out normalizedRequestParameters);
        }
예제 #21
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;
                }
            }
        }
예제 #22
0
    public string GetAccessToken(string consumer_key, string consumer_secret)
    {
        System.Net.ServicePointManager.Expect100Continue = false;
        OAuthBase oAuth = new OAuthBase();
        Uri uri = new Uri("http://twitter.com/oauth/request_token");
        //OAuthBace.csを用いてsignature生成
        string normalizedUrl, normalizedRequestParameters;
        string signature = oAuth.GenerateSignature(
                                    uri ,
                                    consumer_key, consumer_secret, "", "",
                                    "GET", GenerateTimestamp() , GenerateNonce(), OAuthBase.SignatureTypes.HMACSHA1,
                                    out normalizedUrl, out normalizedRequestParameters);

        //oauth_token,oauth_token_secret取得
        string param = string.Format("http://twitter.com/oauth/request_token?{0}&oauth_signature={1}",
                                      normalizedRequestParameters, signature);
        HttpWebRequest webreq = (System.Net.HttpWebRequest)WebRequest.Create(param);
        webreq.Method = "GET";
        HttpWebResponse webres = (HttpWebResponse)webreq.GetResponse();

        Stream st = webres.GetResponseStream();
        StreamReader sr = new StreamReader(st, Encoding.GetEncoding(932));

        string result = sr.ReadToEnd();

        sr.Close();
        st.Close();
        Console.WriteLine(result);

        //正規表現でoauth_token,oauth_token_secret取得
        string token       = Regex.Match(result, @"oauth_token=(.*?)&oauth_token_secret=.*?&oauth_callback.*").Groups[1].Value;
        string tokenSecret = Regex.Match(result, @"oauth_token=(.*?)&oauth_token_secret=(.*?)&oauth_callback.*").Groups[2].Value;

        //ブラウザからPIN確認
        string AuthorizeURL = (string.Format("http://twitter.com/oauth/authorize?{0}", result));
        System.Diagnostics.Process.Start(AuthorizeURL);
        Console.Write("PIN:");
        string PIN = Console.ReadLine();

        //oauth_token,oauth_token_secretを用いて再びsignature生成
        signature = oAuth.GenerateSignature(
                            uri,
                            consumer_key, consumer_secret, token, tokenSecret,
                            "POST", GenerateTimestamp(), GenerateNonce(), OAuthBase.SignatureTypes.HMACSHA1,
                            out normalizedUrl, out normalizedRequestParameters);
        string req_param = string.Format("http://twitter.com/oauth/access_token?{3}&oauth_signature={0}&oauth_verifier={2}",
                                          signature, result, PIN, normalizedRequestParameters);
        webreq = (System.Net.HttpWebRequest)WebRequest.Create(req_param);

        //oauth_token,oauth_token_secretの取得
        webreq.Method = "POST";
        webres = (System.Net.HttpWebResponse)webreq.GetResponse();

        st = webres.GetResponseStream();
        sr = new StreamReader(st, Encoding.GetEncoding(932));

        result = sr.ReadToEnd();

        sr.Close();
        st.Close();

        return result;
        //デスクトップ\oauth_token.txtに保存
        //File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\oauth_token.txt",result);
    }
        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
		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);
		}
예제 #25
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;
        }
예제 #26
0
        private static void getAccessToken( string consumer_key, string consumer_secret )
        {
            System.Net.ServicePointManager.Expect100Continue = false;
            OAuthBase oAuth = new OAuthBase();

            System.Uri uri = new Uri( OAuth.APIKey.ReqestToken );

            //OAuthBace.csを用いてsignature生成
            OAuth.OAuthConsumer consumer = new OAuthConsumer( consumer_key, consumer_secret );
            string signature = oAuth.GenerateSignature( uri, consumer, "GET", "" );

            //oauth_token,oauth_token_secret取得
            HttpWebRequest webreq = (System.Net.HttpWebRequest)WebRequest.Create( OAuth.APIKey.ReqestToken + string.Format( "?{0}&oauth_signature={1}", oAuth.NormalizedRequestParameters, signature ) );
            webreq.Method = "GET";
            HttpWebResponse webres = (HttpWebResponse)webreq.GetResponse();

            string result;
            using ( System.IO.Stream st = webres.GetResponseStream() )
            using ( System.IO.StreamReader sr = new System.IO.StreamReader( st, Encoding.GetEncoding( 932 ) ) ) {
                result = sr.ReadToEnd();
            }

            Console.WriteLine( result );

            //正規表現でoauth_token,oauth_token_secret取得
            Match match = Regex.Match( result, @"oauth_token=(.*?)&oauth_token_secret=(.*?)&oauth_callback.*" );
            string token = match.Groups[1].Value;
            string tokenSecret = match.Groups[2].Value;

            //ブラウザからPIN確認
            string AuthorizeURL = OAuth.APIKey.Authorize + "?" + result;
            System.Diagnostics.Process.Start( AuthorizeURL );
            Console.Write( "PIN:" );
            string PIN = Console.ReadLine();

            //oauth_token,oauth_token_secretを用いて再びsignature生成
            consumer = new OAuthConsumer( consumer_key, consumer_secret );
            consumer.SetTokenWithSecret( token, tokenSecret );
            signature = oAuth.GenerateSignature( uri, consumer, "POST", "" );
            webreq = (System.Net.HttpWebRequest)WebRequest.Create( OAuth.APIKey.AccessToken + string.Format( "?{3}&oauth_signature={0}&oauth_verifier={2}", signature, result, PIN, oAuth.NormalizedRequestParameters ) );

            //oauth_token,oauth_token_secretの取得
            webreq.Method = "POST";
            webres = (System.Net.HttpWebResponse)webreq.GetResponse();

            using ( System.IO.Stream st = webres.GetResponseStream() )
            using ( System.IO.StreamReader sr = new System.IO.StreamReader( st, Encoding.GetEncoding( 932 ) ) ) {
                result = sr.ReadToEnd();
            }

            Console.WriteLine( result );

            //正規表現でoauth_token,oauth_token_secret取得
            match = Regex.Match( result, @"oauth_token=(.*?)&oauth_token_secret=(.*?)&.*" );
            token = match.Groups[1].Value;
            tokenSecret = match.Groups[2].Value;

            Console.WriteLine( "public const string token = \"" + token + "\";" );
            Console.WriteLine( "public const string tokenSecret = \"" + tokenSecret + "\";" );

            //デスクトップ\oauth_token.txtに保存
            File.WriteAllText( Environment.GetFolderPath( Environment.SpecialFolder.Desktop ) + @"\oauth_token.txt", result );
        }
예제 #27
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);
        }
예제 #28
0
        /// <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);
            }
        }
예제 #29
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;
        }
예제 #30
0
        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);
        }
예제 #31
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;
        }