/// <summary>
        /// Checks a single entry agasint vulnDB Search API.
        /// </summary>
        /// <param name="consumerkey"></param>
        /// <param name="consumersecret"></param>
        /// <param name="Application"></param>
        /// <returns></returns>
        public static string vulndb_appCheck(String consumerkey, String consumersecret, String Application)
        {
            try
            {
                var requestEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/request_token");
                var authorizeEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/authorize");
                var accessEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/access_token");
                var ctx = new OAuthConsumerContext
                {
                    ConsumerKey = consumerkey,
                    ConsumerSecret = consumersecret,
                    SignatureMethod = SignatureMethod.HmacSha1
                };
                var genericSession = new OAuthSession(ctx, requestEndPoint, authorizeEndPoint, accessEndPoint);
                var targetServiceUri = new Uri("https://vulndb.cyberriskanalytics.com/api/v1/vulnerabilities/search_query?query=\"" + Application.ToString() +"\"");
                var respText = genericSession.Request().Get().ForUri(targetServiceUri).ToString();
               
                return respText;

            }
            catch (WebException ex)
            {
                using (var stream = ex.Response.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    Console.WriteLine(reader.ReadToEnd());
                    return "Nothing Found for: " + Application.ToString();
                }
            }
        }
        /// <summary>
        /// Used to Check if the API key is valid or not.
        /// </summary>
        /// <param name="consumerkey"></param>
        /// <param name="consumersecret"></param>
        /// <returns></returns>
        public static string CMS_Auditor(String consumerkey, String consumersecret)
        {
            try
            {
                var requestEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/request_token");
                var authorizeEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/authorize");
                var accessEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/access_token");
                var ctx = new OAuthConsumerContext
                {
                    ConsumerKey = consumerkey,
                    ConsumerSecret = consumersecret,
                    SignatureMethod = SignatureMethod.HmacSha1
                };
                var genericSession = new OAuthSession(ctx, requestEndPoint, authorizeEndPoint, accessEndPoint);
                var targetServiceUri = new Uri("https://vulndb.cyberriskanalytics.com/api/v1/vulnerabilities/search_query?utf8=✓&query=teamviewer");
                var respText = genericSession.Request().Get().ForUri(targetServiceUri).ToString();

                return respText;

            }
            catch (WebException ex)
            {
                using (var stream = ex.Response.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    Console.WriteLine(reader.ReadToEnd());
                    return "Please Check your API Key and Secret";
                }
            }
        }
		public void GoogleConsumer()
		{
			X509Certificate2 certificate = TestCertificates.OAuthTestCertificate();

			string requestUrl = "https://www.google.com/accounts/OAuthGetRequestToken";
			string userAuthorizeUrl = "https://www.google.com/accounts/accounts/OAuthAuthorizeToken";
			string accessUrl = "https://www.google.com/accounts/OAuthGetAccessToken";
			string callBackUrl = "http://www.mysite.com/callback";

			var consumerContext = new OAuthConsumerContext
			{
				ConsumerKey = "weitu.googlepages.com",
				SignatureMethod = SignatureMethod.RsaSha1,
				Key = certificate.PrivateKey
			};

			var session = new OAuthSession(consumerContext, requestUrl, userAuthorizeUrl, accessUrl)
				.WithQueryParameters(new { scope = "http://www.google.com/m8/feeds" });

			// get a request token from the provider
			IToken requestToken = session.GetRequestToken();

			// generate a user authorize url for this token (which you can use in a redirect from the current site)
			string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callBackUrl);

			// exchange a request token for an access token
			IToken accessToken = session.ExchangeRequestTokenForAccessToken(requestToken);

			// make a request for a protected resource
			string responseText = session.Request().Get().ForUrl("http://www.google.com/m8/feeds/contacts/default/base").ToString();
		}
        /// <summary>        
        /// Creates a HttpRequest with oAuthSession (OAuth Token) and gets the response with invalidating user
        /// from QuickBooks for this app
        /// For Authorization: The request header must include the OAuth parameters defined by OAuth Core 1.0 Revision A.
        /// 
        /// If the disconnect is successful, then the HTTP status code is 200 and 
        /// the XML response includes the <ErrorCode> element with a 0 value.  
        /// If an HTTP error is detected, then the HTTP status code is not 200.  
        /// If an HTTP error is not detected but the disconnect is unsuccessful, 
        /// then the HTTP status code is 200 and the response XML includes the <ErrorCode> element with a non-zero value.   
        /// For example,  if the OAuth access token expires or is invalid for some other reason, then the value of <ErrorCode> is 270.
        /// </summary>
        //
        // GET: /CleanUpOnDisconnect/
        public ActionResult Disconnect()
        {
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
               {
               ConsumerKey = ApplicationUserAppValues.ConsumerKey,
               SignatureMethod = SignatureMethod.HmacSha1,
               ConsumerSecret = ApplicationUserAppValues.ConsumerSecret
               };

            OAuthSession oSession = new OAuthSession(consumerContext, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlRequestToken,
                                  Constants.OauthEndPoints.AuthorizeUrl,
                                  Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlAccessToken);

            oSession.ConsumerContext.UseHeaderForOAuthParameters = true;
            if ((SessionWrapper.accessToken + "").Length > 0)
            {
                oSession.AccessToken = new TokenBase
                {
                    Token = SessionWrapper.accessToken,
                    ConsumerKey = ApplicationUserAppValues.ConsumerKey,
                    TokenSecret = SessionWrapper.accessTokenSecret
                };

                IConsumerRequest conReq = oSession.Request();
                conReq = conReq.Get();
                conReq = conReq.ForUrl(Constants.IaEndPoints.DisconnectUrl);
                try
                {
                    conReq = conReq.SignWithToken();
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                //Used just see the what header contains
                string header = conReq.Context.GenerateOAuthParametersForHeader();

                //This method will clean up the OAuth Token
                GlobalVariablesWrapper.TxtServiceResponse = conReq.ReadBody();

                // Add the invalid access token into session for the display of the Disconnect btn
                SessionWrapper.InvalidAccessToken = SessionWrapper.accessToken;

                // Dont remove the access token since this is required for Reconnect btn in the Blue dot menu
                // HttpContext.Current.Session.Remove("accessToken");

                // Dont Remove flag since we need to display the blue dot menu for Reconnect btn in the Blue dot menu
                // HttpContext.Current.Session.Remove("Flag");
                GlobalVariablesWrapper.DisconnectFlg = "User is Disconnected from QuickBooks!";

            }
            return View("Disconnect");
        }
示例#5
0
        /// <summary>        
        /// Creates a HttpRequest with oAuthSession (OAuth Token) and gets the response with invalidating user
        /// from QuickBooks for this app
        /// For Authorization: The request header must include the OAuth parameters defined by OAuth Core 1.0 Revision A.
        /// 
        /// If the disconnect is successful, then the HTTP status code is 200 and 
        /// the XML response includes the <ErrorCode> element with a 0 value.  
        /// If an HTTP error is detected, then the HTTP status code is not 200.  
        /// If an HTTP error is not detected but the disconnect is unsuccessful, 
        /// then the HTTP status code is 200 and the response XML includes the <ErrorCode> element with a non-zero value.   
        /// For example,  if the OAuth access token expires or is invalid for some other reason, then the value of <ErrorCode> is 270.
        /// </summary>
        /// <param name="sender">Sender of the event.</param>
        /// <param name="e">Event args.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(),
                SignatureMethod = SignatureMethod.HmacSha1,
                ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"].ToString()
            };

            OAuthSession oSession = new OAuthSession(consumerContext, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlRequestToken,
                                  Constants.OauthEndPoints.AuthorizeUrl,
                                  Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlAccessToken);

            oSession.ConsumerContext.UseHeaderForOAuthParameters = true;
            if ((Session["accessToken"] + "").Length > 0)
            {
                oSession.AccessToken = new TokenBase
                {
                    Token = HttpContext.Current.Session["accessToken"].ToString(),
                    ConsumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(),
                    TokenSecret = HttpContext.Current.Session["accessTokenSecret"].ToString()
                };

                IConsumerRequest conReq = oSession.Request();
                conReq = conReq.Get();
                conReq = conReq.ForUrl(Constants.IaEndPoints.DisconnectUrl);
                try
                {
                    conReq = conReq.SignWithToken();
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                //Used just see the what header contains
                string header = conReq.Context.GenerateOAuthParametersForHeader();

                //This method will clean up the OAuth Token
                txtServiceResponse = conReq.ReadBody();

                // Add the invalid access token into session for the display of the Disconnect btn
                HttpContext.Current.Session["InvalidAccessToken"] = HttpContext.Current.Session["accessToken"];

                // Dont remove the access token since this is required for Reconnect btn in the Blue dot menu
                // HttpContext.Current.Session.Remove("accessToken");

                // Dont Remove flag since we need to display the blue dot menu for Reconnect btn in the Blue dot menu
                // HttpContext.Current.Session.Remove("Flag");
                DisconnectFlg = "User is Disconnected from QuickBooks!";
            }
        }
示例#6
0
        private static void Main()
        {
            string requestUrl = "https://apis.daum.net/oauth/requestToken";
            string userAuthorizeUrl = "https://apis.daum.net/oauth/authorize";
            string accessUrl = "https://apis.daum.net/oauth/accessToken";
            string callbackUrl = "oob";

            var consumerContext = new OAuthConsumerContext
            {
                //TODO:Daum OAuth소개 페이지(https://apis.daum.net/oauth/consumer/list)에서 등록된 Consumer 정보 입력
                ConsumerKey = "eb3eff10-b95d-455c-8572-e7858a2b34d0",
                ConsumerSecret = "suz6.HUjzlaG-S9ezBzFQ11FtKhQvv8cdT-9C_hWBFthpUmMTsOuUA00",
                SignatureMethod = SignatureMethod.HmacSha1,
            };

            //OAuth 준비
            var session = new OAuthSession(consumerContext, requestUrl, userAuthorizeUrl, accessUrl);
            session.WithQueryParameters(new Dictionary<string,string>(){ { "oauth_callback", callbackUrl } });

            // 1. request token 받기
            DevDefined.OAuth.Framework.IToken requestToken = session.GetRequestToken();

            // 인증주소 받기
            string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callbackUrl);

            // 2. 사용자 인증 하기
            System.Console.WriteLine("웹브라우저를 실행하여 다음 URL을 접속하세요.");
            System.Console.WriteLine(authorizationLink);
            System.Console.Write("\n\n웹브라우저에서 인증 후 반환 된 값을 입력하세요:");
            string inputVerifier = System.Console.ReadLine();

            // 얻어진 Verifier값을 포함시키기
            session.WithQueryParameters(new Dictionary<string, string>() { { "oauth_verifier", inputVerifier } });

            // 3. 인증 후 얻은 Verifier값을 이용하여 엑세스 토큰 얻기
            DevDefined.OAuth.Framework.IToken accessToken = session.ExchangeRequestTokenForAccessToken(requestToken);

            // '게시글 쓰기(한줄메모장)' API를 호출
            System.Console.WriteLine("OAuth를 통한 인증으로 '게시글 쓰기(한줄메모장)'를 호출하고 XML로 응답 받는 테스트를 합니다.");
            string apiUrl = "http://apis.daum.net/cafe/write_article/{cafeCode}/{boardId}.xml?";
            //{cafeCode} - 카페코드 :
            //{boardId}
            apiUrl += string.Format("content={0}&", "여기는 메모를 삽입합니다.");
            apiUrl += string.Format("hideyn={0}&", "N"); //비밀글일때 Y

            string responseText = session.Request().Get().ForUrl(apiUrl).ToString();

            System.Console.WriteLine(responseText);
            System.Console.ReadLine();
        }
示例#7
0
        private static void Main()
        {
            string requestUrl = "https://apis.daum.net/oauth/requestToken";
            string userAuthorizeUrl = "https://apis.daum.net/oauth/authorize";
            string accessUrl = "https://apis.daum.net/oauth/accessToken";
            string callbackUrl = "oob";

            var consumerContext = new OAuthConsumerContext
            {
                //TODO:Daum OAuth소개 페이지(https://apis.daum.net/oauth/consumer/list)에서 등록된 Consumer 정보 입력
                ConsumerKey = "eb3eff10-b95d-455c-8572-e7858a2b34d0",
                ConsumerSecret = "suz6.HUjzlaG-S9ezBzFQ11FtKhQvv8cdT-9C_hWBFthpUmMTsOuUA00",
                SignatureMethod = SignatureMethod.HmacSha1,
            };

            //OAuth 준비
            var session = new OAuthSession(consumerContext, requestUrl, userAuthorizeUrl, accessUrl);
            session.WithQueryParameters(new Dictionary<string,string>(){ { "oauth_callback", callbackUrl } });

            // 1. request token 받기
            DevDefined.OAuth.Framework.IToken requestToken = session.GetRequestToken();

            // 인증주소 받기
            string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callbackUrl);

            // 2. 사용자 인증 하기
            System.Console.WriteLine("웹브라우저를 실행하여 다음 URL을 접속하세요.");
            System.Console.WriteLine(authorizationLink);
            System.Console.Write("\n\n웹브라우저에서 인증 후 반환 된 값을 입력하세요:");
            string inputVerifier = System.Console.ReadLine();

            // 얻어진 Verifier값을 포함시키기
            session.WithQueryParameters(new Dictionary<string, string>() { { "oauth_verifier", inputVerifier } });

            session.WithQueryParameters(new Dictionary<string, string>() { { "content", System.Web.HttpUtility.HtmlEncode("~다!음@ #요$즘% ^특&수*문(자) -_\'발=+송\\| \"테<스>;트/") } });
            //session.WithQueryParameters(new Dictionary<string, string>() { { "content", System.Web.HttpUtility.UrlEncode("한글") } });

            // 3. 인증 후 얻은 Verifier값을 이용하여 엑세스 토큰 얻기
            DevDefined.OAuth.Framework.IToken accessToken = session.ExchangeRequestTokenForAccessToken(requestToken);

            // '요즘 가입여부 확인하기' API를 통해 인증 확인하기
            System.Console.WriteLine("OAuth를 통한 인증으로 '요즘 가입여부 확인하기'를 테스트합니다.");
            string responseText = session.Request().Post().ForUrl("https://apis.daum.net/cafe/write_article/JJGO/JVYh.xml?").ToString();

            System.Console.WriteLine(responseText);
            System.Console.ReadLine();
        }
示例#8
0
文件: Program.cs 项目: BangC/apis
        private static void Main()
        {
            string requestUrl = "https://apis.daum.net/oauth/requestToken";
            string userAuthorizeUrl = "https://apis.daum.net/oauth/authorize";
            string accessUrl = "https://apis.daum.net/oauth/accessToken";
            string callBackUrl = "oob";

            var consumerContext = new OAuthConsumerContext
            {
                //TODO:Daum OAuth소개 페이지(https://apis.daum.net/oauth/consumer/list)에서 등록된 Consumer 정보 입력
                ConsumerKey = "{발급 받은 Key를 입력하세요.}",
                ConsumerSecret = "{발급 받은 Secret를 입력하세요.}",
                SignatureMethod = SignatureMethod.HmacSha1,
            };

            //OAuth 준비
            var session = new OAuthSession(consumerContext, requestUrl, userAuthorizeUrl, accessUrl);
            session.WithQueryParameters(new Dictionary<string,string>(){ { "oauth_callback", callBackUrl } });

            // 1. request token 받기
            DevDefined.OAuth.Framework.IToken requestToken = session.GetRequestToken();

            // 인증주소 받기
            string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callBackUrl);

            // 2. 사용자 인증 하기
            System.Console.WriteLine("웹브라우저를 실행하여 다음 URL을 접속하세요.");
            System.Console.WriteLine(authorizationLink);
            System.Console.Write("\n\n웹브라우저에서 인증 후 반환 된 값을 입력하세요:");
            string inputVerifier = System.Console.ReadLine();

            // 얻어진 Verifier값을 포함시키기
            session.WithQueryParameters(new Dictionary<string, string>() { { "oauth_verifier", inputVerifier } });

            // 3. 인증 후 얻은 Verifier값을 이용하여 엑세스 토큰 얻기
            DevDefined.OAuth.Framework.IToken accessToken = session.ExchangeRequestTokenForAccessToken(requestToken);

            // '요즘 가입여부 확인하기' API를 통해 인증 확인하기
            System.Console.WriteLine("OAuth를 통한 인증으로 '요즘 글쓰기'를 테스트합니다.");
            ConsumerRequest cr = session.Request().Post().ForUrl("https://apis.daum.net/yozm/v1_0/message/add.xml");
            cr = cr.WithFormParameters(new Dictionary<string, string>() { { "message", System.Web.HttpUtility.UrlEncode("%$가나다^$%^%$^RTY<><><><><") } });
            string responseText = cr.ToString();

            System.Console.WriteLine(responseText);
            System.Console.ReadLine();
        }
示例#9
0
文件: OAuthTest.cs 项目: cryrin/apis
        static void Main(string[] args)
        {
            string requestUrl = "https://apis.daum.net/oauth/requestToken";
            string userAuthorizeUrl = "https://apis.daum.net/oauth/authorize";
            string accessUrl = "https://apis.daum.net/oauth/accessToken";
            string callbackUrl = "oob";

            var consumerContext = new OAuthConsumerContext
            {
                //Daum OAuth소개 페이지(http://dna.daum.net/myapi/authapi)에서 등록된 Consumer 정보 입력
                ConsumerKey = "[프로필 API용 OAuth 컨슈머 등록한 뒤 발급된 Cosumer키를 입력하세요]",
                ConsumerSecret = "[프로필 API용 OAuth 컨슈머 등록한 뒤  발급된 Cosumer Secret키를 입력하세요]",
                SignatureMethod = SignatureMethod.HmacSha1,
            };

            //OAuth 준비
            var session = new OAuthSession(consumerContext, requestUrl, userAuthorizeUrl, accessUrl);
            session.WithQueryParameters(new Dictionary<string,string>(){ { "oauth_callback", callbackUrl } });

            // 1. request token 받기
            DevDefined.OAuth.Framework.IToken requestToken = session.GetRequestToken();

            // 인증주소 받기
            string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callbackUrl);

            // 2. 사용자 인증 하기
            System.Console.WriteLine("웹브라우저를 실행하여 다음 URL을 접속하세요.");
            System.Console.WriteLine(authorizationLink);
            System.Console.Write("\n\n웹브라우저에서 인증 후 반환 된 값을 입력하세요:");
            string inputVerifier = System.Console.ReadLine();

            // 얻어진 Verifier값을 포함시키기
            session.WithQueryParameters(new Dictionary<string, string>() { { "oauth_verifier", inputVerifier } });

            // 3. 인증 후 얻은 Verifier값을 이용하여 엑세스 토큰 얻기
            DevDefined.OAuth.Framework.IToken accessToken = session.ExchangeRequestTokenForAccessToken(requestToken);

            // '프로필 정보보기' API를 통해 인증 확인하기
            System.Console.WriteLine("OAuth를 통한 인증으로 '프로필 정보보기'를 테스트합니다.");
            string responseText = session.Request().Post().ForUrl("https://apis.daum.net/profile/show.xml").ToString();

            System.Console.WriteLine(responseText);
            System.Console.ReadLine();
        }
        public static string callPlatform(IppRealmOAuthProfile profile, string url)
        {
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(),
                SignatureMethod = SignatureMethod.HmacSha1,
                ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"].ToString()
            };

            OAuthSession oSession = new OAuthSession(consumerContext, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlRequestToken,
                                  Constants.OauthEndPoints.AuthorizeUrl,
                                  Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlAccessToken);

            oSession.ConsumerContext.UseHeaderForOAuthParameters = true;
            if (profile.accessToken.Length > 0)
            {
                oSession.AccessToken = new TokenBase
                {
                    Token = profile.accessToken,
                    ConsumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(),
                    TokenSecret = profile.accessSecret
                };

                IConsumerRequest conReq = oSession.Request();
                conReq = conReq.Get();
                conReq = conReq.ForUrl(url);
                try
                {
                    conReq = conReq.SignWithToken();
                    return conReq.ReadBody();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return "";
        }
示例#11
0
        public string callPlatform(string url)
        {
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey = ConfigurationSettings.AppSettings["consumerKey"],
                SignatureMethod = SignatureMethod.HmacSha1,
                ConsumerSecret = ConfigurationSettings.AppSettings["consumerSecret"]
            };

            OAuthSession oSession = new OAuthSession(consumerContext, "http://www.example.com", "http://www.example.com", "http://www.example.com");

            oSession.ConsumerContext.UseHeaderForOAuthParameters = true;

            if (_ippRealmOAuthProfile.accessToken.Length > 0)
            {
                oSession.AccessToken = new TokenBase
                {
                    Token = _ippRealmOAuthProfile.accessToken,
                    ConsumerKey = ConfigurationSettings.AppSettings["consumerKey"],
                    TokenSecret = _ippRealmOAuthProfile.accessSecret
                };

                IConsumerRequest conReq = oSession.Request();
                conReq = conReq.Get();
                conReq = conReq.ForUrl(url);
                try
                {
                    conReq = conReq.SignWithToken();
                    return conReq.ReadBody();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            return "";
        }
        public BaseResponse read_next_page() {
            if (!has_next_page()) {
                return null;
            }

            parameter("page", next_page());
            if (_per_page != 0) {
                parameter("per_page", _per_page);
            }

            var session = new OAuthSession(oath_context(), _uri, _uri, _uri);
            var request = session.Request().Get().ForUri(parameterize_uri());
            BaseResponse response = (BaseResponse)JsonConvert.DeserializeObject(request.ToString(), _response_type, json_settings());
            if (response.meta.status_code != 200) {
                throw new Exception("Error talking to StorEdge: " + response.meta.status_message);
            }
            last_meta = response.meta;
            return response;
        }
示例#13
0
        public static void Run()
        {
            // Create the consumer session
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey = "ZGIXM2M1Y2RIZJGYNGY1Y2EWZGYZMW",
                ConsumerSecret = "RZRCMBRPK57EAG6GRO4GPLYDH9REPX",
                SignatureMethod = SignatureMethod.HmacSha1,
                UseHeaderForOAuthParameters = true,
                UserAgent = string.Format("Xero.API.ScreenCast v1.0 (Public App Testing)")
            };

            OAuthSession consumerSession = new OAuthSession(
                consumerContext, 
                Settings.Default.RequestTokenURI, 
                Settings.Default.AuthoriseURI,
                Settings.Default.AccessTokenURI);

            // 1. Get a request token
            IToken requestToken = consumerSession.GetRequestToken();
            
            Console.WriteLine("Request Token Key: {0}", requestToken.Token);
            Console.WriteLine("Request Token Secret: {0}", requestToken.TokenSecret);


            // 2. Get the user to log into Xero using the request token in the querystring
            //string authorisationUrl = Settings.Default.AuthoriseURI.AbsoluteUri + "?oauth_token=" + HttpUtility.UrlEncode(requestTokenKey);
            string authorisationUrl = consumerSession.GetUserAuthorizationUrlForToken(requestToken);
            Process.Start(authorisationUrl);

            // 3. Get the use to enter the authorisation code from Xero (4-7 digit number)
            Console.WriteLine("Please input the code you were given in Xero:");
            var verificationCode = Console.ReadLine();

            if (string.IsNullOrEmpty(verificationCode))
            {
                Console.WriteLine("You didn't type a verification code!");
                return;
            }

            verificationCode = verificationCode.Trim();


            // 4. Use the request token and verification code to get an access token
            IToken accessToken;

            try
            {
                accessToken = consumerSession.ExchangeRequestTokenForAccessToken(requestToken, verificationCode);
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }

            Console.WriteLine("Access Token Key: {0}", accessToken.Token);
            Console.WriteLine("Access Token Secret: {0}", accessToken.TokenSecret);


            // 5. Make a call to api.xero.com to check that we can use the access token.
            IConsumerRequest getOrganisationRequest = consumerSession
                .Request()
                .ForMethod("GET")
                .ForUri(new Uri("https://api.xero.com/api.xro/2.0/Organisation"))
                .SignWithToken(accessToken);

            string getOrganisationResponse = getOrganisationRequest.ToString();

            if (getOrganisationResponse != string.Empty)
            {
                var organisationXml = XElement.Parse(getOrganisationResponse);
                string organisationName = organisationXml.XPathSelectElement("//Organisation/Name").Value;
                Console.WriteLine(string.Format("You have been authorised against organisation: {0}", organisationName));
            }


            // 6. Make a PUT call to the API - add a dummy contact
            Console.WriteLine("Please enter the name of a new contact to add to Xero");
            string contactName = Console.ReadLine();

            if (string.IsNullOrEmpty(contactName))
            {
                return;
            }

            string putContactRequestBody = string.Format("<Contacts><Contact><Name>{0}</Name></Contact></Contacts>", contactName);
            string putContactResponse;

            IConsumerRequest putContactRequest = consumerSession
                .Request()
                .ForMethod("PUT")
                .ForUri(new Uri("https://api.xero.com/api.xro/2.0/Contacts"))
                .WithFormParameters(new { xml = putContactRequestBody })
                .SignWithToken(accessToken);

            try
            {
                putContactResponse = putContactRequest.ToString();
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }
            catch (WebException ex)
            {
                putContactResponse = ex.Response.GetResponseStream().ReadToEnd();

                Console.WriteLine("A WebException was caught:");
                Console.WriteLine(putContactResponse);
                return;
            }

            if (putContactResponse != string.Empty)
            {
                var responseElement = XElement.Parse(putContactResponse);
                string statusCode = responseElement.XPathSelectElement("/Status").Value;

                if (statusCode == "OK")
                {
                    string contactId = responseElement.XPathSelectElement("/Contacts/Contact[1]/ContactID").Value;
                    Console.WriteLine(string.Format("The contact '{0}' was created with id: {1}", contactName, contactId));
                }
            }


            // 7. Try to update the contact that's just been created, but this time use a POST method
            string postContactRequestBody = string.Format("<Contacts><Contact><Name>{0}</Name><EmailAddress>{1}@nowhere.com</EmailAddress></Contact></Contacts>", contactName, contactName.ToLower().Replace(" ", "."));
            string postContactResponse;

            IConsumerRequest postContactRequest = consumerSession
                .Request()
                .ForMethod("POST")
                .ForUri(new Uri("https://api.xero.com/api.xro/2.0/Contacts"))
                .WithFormParameters(new {xml = postContactRequestBody})
                .SignWithToken(accessToken);

            try
            {
                postContactResponse = postContactRequest.ToString();
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }
            catch (WebException ex)
            {
                putContactResponse = ex.Response.GetResponseStream().ReadToEnd();

                Console.WriteLine("A WebException was caught:");
                Console.WriteLine(putContactResponse);
                return;
            }
            
            if (postContactResponse != string.Empty)
            {
                var responseElement = XElement.Parse(postContactResponse);
                string statusCode = responseElement.XPathSelectElement("/Status").Value;

                if (statusCode == "OK")
                {
                    string emailAddress = responseElement.XPathSelectElement("/Contacts/Contact[1]/EmailAddress").Value;
                    Console.WriteLine(string.Format("The contact '{0}' was updated with email address: {1}", contactName, emailAddress));
                }
            }
        }
        // unauthenticated connection method:
        /// <summary>
        /// Creates a connection with no authorization headers - used for requests that don't require authentication.
        /// This method does not actually perform the request - it returns the object to make the request with.
        /// </summary>
        /// <param name="query">The url to connect to.</param>
        /// <returns>IConsumerRequest.</returns>
        public IConsumerRequest UnauthenticatedConnection(string query)
        {
            var url = BaseUrl + query;
            if (AccessToken != null)
            {
                return AuthenticatedQuery(query);
            }

            var consumerContext = new OAuthConsumerContext
            {
                ConsumerKey = " ",
                ConsumerSecret = " ",
                SignatureMethod = DevDefined.OAuth.Framework.SignatureMethod.PlainText,
                UseHeaderForOAuthParameters = false
            };

            var consumerSession = new OAuthSession(consumerContext, RequestTokenUrl, AuthorizeUrl, AccessUrl);

            var getRequest = consumerSession
                .Request()
                .ForMethod(Constants.GET)
                .ForUri(new Uri(url));

            return getRequest;
        }
示例#15
0
        private static TwitchPassword auth ( )
        {
            try
            {
                /*
                    https://api.twitch.tv/kraken/oauth2/authorize?response_type=token&client_id=r8829yrhzewp4gwopt9gh90py0s8p3p&redirect_uri=http://integrationservices.blizzeta.net&scope=user_read%20user_blocks_edit%20user_blocks_read%20user_follows_edit%20channel_read%20channel_editor%20channel_commercial%20channel_stream%20channel_subscriptions%20user_subscriptions%20chat_login%20channel_check_subscription
                */

                //Process.Start ( Global.AuthorizationFullPermissions );
                string url = ParseAuthorization ( );

                X509Certificate2 cert = DevDefined.OAuth.Tests.TestCertificates.OAuthTestCertificate ( );

                OAuthConsumerContext context = new OAuthConsumerContext
                {
                    ConsumerKey = "api.twitch.tv",
                    SignatureMethod = SignatureMethod.RsaSha1,
                    Key = cert.PrivateKey
                };

                IOAuthSession session = new OAuthSession ( context, null, url, null ).WithQueryParameters ( new { scope = Global.Redirect } );
                IToken request = session.GetRequestToken ( );
                string authorize = session.GetUserAuthorizationUrlForToken ( request, Global.Redirect );
                IToken access = session.ExchangeRequestTokenForAccessToken ( request );
                string response = session.Request ( ).Get ( ).ForUrl ( Global.AuthorizationFullPermissions ).ToString ( );

                Console.WriteLine ( response );
                TwitchPassword pt = JsonConvert.DeserializeObject<TwitchPassword> ( response );
                return pt;
            }
            catch ( Exception ex )
            {
                Console.WriteLine ( "Error: {0}", ex.Message );
                if ( ex.InnerException != null )
                {
                    Console.WriteLine ( "Inner Error: {0}", ex.InnerException.Message );
                }
            }
            return null;
        }
        /// <summary>
        /// <para>It serializes the toSend object into xml and sends the post message specified in the "to" string using an authorized connection. 
        /// It returns the response from the server as an XDocument.
        /// </para>
        /// REQUIRES AUTHENTICATION.
        /// </summary>
        /// <param name="toSend">The object that will be serialized into xml and then sent in the post message.</param>
        /// <param name="to">The query string that will be added to the base url and used to connect to the API.</param>
        /// <param name="delete">True if you want the request to be of the method DELETE instead of POST.</param>
        /// <returns>XDocument.</returns>
        public XDocument Post(object toSend, string to, bool delete)
        {
            var url = BaseUrl + to;
            var xmlToSend = string.Empty;
            if (AccessToken == null)
            {
                throw new AccessTokenIsNullException();
            }

            var consumerContext = new OAuthConsumerContext
            {
                ConsumerKey = ConsumerKey,
                ConsumerSecret = ConsumerSecret,
                SignatureMethod = SignatureMethod.HmacSha1,
                UseHeaderForOAuthParameters = true
            };

            var consumerSession = new OAuthSession(consumerContext, RequestTokenUrl + ScopeOfRequest, AuthorizeUrl, AccessUrl) { AccessToken = AccessToken };

            // convert the object into xml
            if (toSend == null)
            {
                xmlToSend = string.Empty;
            }
            else
            {
                var serializer = new XmlSerializer(toSend.GetType());

                // Create a new file stream to write the serialized object to a file
                using (TextWriter writeFileStream = new StreamWriter(@"C:\test.xml"))
                {
                    serializer.Serialize(writeFileStream, toSend);

                    // Cleanup
                    writeFileStream.Close();
                }

                xmlToSend += Environment.NewLine + System.IO.File.ReadAllText(@"C:\test.xml");
                xmlToSend = xmlToSend.TrimStart();
            }

            // send the post request
            var testReq = consumerSession.Request();

            if (delete)
            {
                testReq.Delete();
            }
            else
            {
                testReq.Post();
            }

            testReq.ForUrl(url);
            testReq.SignWithToken();

            // Here's your Authorization Header
            var oAuthHeader =
                testReq.Context.GenerateOAuthParametersForHeader();

            var address = new Uri(url);

            var webRequest = WebRequest.Create(address) as HttpWebRequest;
            if (webRequest != null)
            {
                webRequest.Method = delete ? Constants.DELETE : Constants.POST;

                webRequest.ContentType = "text/xml";

                // Set the generated Header
                webRequest.Headers.Add("Authorization", oAuthHeader);

                if (string.IsNullOrEmpty(xmlToSend))
                {
                    webRequest.ContentLength = 0;
                }
                else
                {
                    var dataAsBytes = (new UTF8Encoding()).GetBytes(xmlToSend);
                    webRequest.ContentLength = dataAsBytes.Length;

                    using (var newStream = webRequest.GetRequestStream())
                    {
                        // Send the data.
                        newStream.Write(dataAsBytes, 0, dataAsBytes.Length);
                        newStream.Close();
                    }
                }
            }

            // make the call and return the results
            if (webRequest != null)
                using (var response = webRequest.GetResponse())
                {
                    using (var stream = new StreamReader(response.GetResponseStream()))
                    {
                        var doc = XDocument.Parse(stream.ReadToEnd(), LoadOptions.None);

                        return doc;
                    }
                }
            return null;
        }
        /// <summary>
        /// <para>Performs the query specified in the "query" string to perform a request that requires authorization.
        /// </para><para>This method requires that either an accessToken has been set manually or 
        /// that the GetVerificationCode() and AuthenticateWithVerificationCode(string code) methods have been called previously.
        /// </para><para>It returns the IConsumerRequest fully enabled to make the request specified in the "query" string.</para>
        /// </summary>
        /// <param name="query">The query string that will be added to the url and used to connect to the API with.</param>
        /// <returns>IConsumerRequest.</returns>
        public IConsumerRequest AuthenticatedQuery(string query)
        {
            var url = BaseUrl + query;

            if (AccessToken == null)
            {
                throw new AccessTokenIsNullException();
            }

            var consumerContext = new OAuthConsumerContext
            {
                ConsumerKey = ConsumerKey,
                ConsumerSecret = ConsumerSecret,
                SignatureMethod = SignatureMethod.HmacSha1,
                UseHeaderForOAuthParameters = true
            };

            var consumerSession = new OAuthSession(consumerContext, RequestTokenUrl + ScopeOfRequest, AuthorizeUrl, AccessUrl) { AccessToken = AccessToken };

            var getRequest = consumerSession
                .Request()
                .ForMethod(Constants.GET)
                .ForUri(new Uri(url))
                .SignWithToken(AccessToken);

            return getRequest;
        }
        /// <summary>
        /// Used to Check if the API key is valid or not.
        /// </summary>
        /// <param name="consumerkey"></param>
        /// <param name="consumersecret"></param>
        /// <returns></returns>
        public static Boolean vulndbCheckCredentials(String consumerkey, String consumersecret)
        {
            if (consumerkey == "" || consumersecret == "") { return false; }
            try
            {
                var requestEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/request_token");
                var authorizeEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/authorize");
                var accessEndPoint = new Uri("https://vulndb.cyberriskanalytics.com/oauth/access_token");
                var ctx = new OAuthConsumerContext
                {
                    ConsumerKey = consumerkey,
                    ConsumerSecret = consumersecret,
                    SignatureMethod = SignatureMethod.HmacSha1
                };
                var genericSession = new OAuthSession(ctx, requestEndPoint, authorizeEndPoint, accessEndPoint);
                var targetServiceUri = new Uri("https://vulndb.cyberriskanalytics.com/api/v1/vulnerabilities/");
                var respText = genericSession.Request().Get().ForUri(targetServiceUri).ToString();

                return true;

            }
            catch (WebException ex)
            {
                using (var stream = ex.Response.GetResponseStream())
                using (var reader = new StreamReader(stream))
                {
                    Console.WriteLine(reader.ReadToEnd());
                    return false;
                }
            }
        }
    public void TokenSecretNotIncludedInAuthorizationHeaderForPostRequestWithUseAuthorizationHeaders()
    {
      var session = new OAuthSession(new OAuthConsumerContext {ConsumerKey = "consumer", UseHeaderForOAuthParameters = true}, "http://localhost/request",
                                     "http://localhost/userauth", "http://localhost/access");

      var accessToken = new TokenBase {ConsumerKey = "consumer", Token = "token", TokenSecret = "secret"};

      RequestDescription description = session
        .Request(accessToken)
        .Post()
        .ForUrl("http://localhost/")
        .SignWithToken()
        .GetRequestDescription();

      Assert.False(description.Headers["Authorization"].Contains(Parameters.OAuth_Token_Secret));
    }
示例#20
0
        /// <summary>
        /// Core Logic to get HTML content for BLue Dot Menu
        /// Error Handling: If the OAuth access token has expired or is invalid for some other reason, 
        /// then the HTTP status code is 200, and the HTML returned shows the Connect to QuickBooks button within the Intuit "blue dot" menu.  
        /// If an internal error is detected, then the HTTP status code returned is not 2xx, and the HTML returned will display the following text in the menu: "We are sorry, but we cannot load the menu right now."
        /// </summary>
        protected void GetBlueDotMenu()
        {
            HttpContext.Current.Session["serviceEndPoint"] = Constants.IaEndPoints.BlueDotAppMenuUrl;
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(),
                SignatureMethod = SignatureMethod.HmacSha1,
                ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"].ToString()
            };

            OAuthSession oSession = new OAuthSession(consumerContext, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlRequestToken,
                                  Constants.OauthEndPoints.AuthorizeUrl,
                                  Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlAccessToken);

            oSession.ConsumerContext.UseHeaderForOAuthParameters = true;

            oSession.AccessToken = new TokenBase
            {
                Token = Session["accessToken"].ToString(),
                ConsumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(),
                TokenSecret = Session["accessTokenSecret"].ToString()
            };

            IConsumerRequest conReq = oSession.Request();
            conReq = conReq.Get();
            conReq = conReq.ForUrl(HttpContext.Current.Session["serviceEndPoint"].ToString());
            try
            {
                conReq = conReq.SignWithToken();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            string header = conReq.Context.GenerateOAuthParametersForHeader();
            try
            {
                txtServiceResponse = conReq.ReadBody();
                Response.Write(txtServiceResponse);
            }
            catch (WebException we)
            {
                HttpWebResponse rsp = (HttpWebResponse)we.Response;
                if (rsp != null)
                {
                    try
                    {
                        using (StreamReader reader = new StreamReader(rsp.GetResponseStream()))
                        {
                            txtServiceResponse = txtServiceResponse + rsp.StatusCode + " | " + reader.ReadToEnd();
                        }
                    }
                    catch (Exception)
                    {
                        txtServiceResponse = txtServiceResponse + "Status code: " + rsp.StatusCode;
                    }
                }
                else
                {
                    txtServiceResponse = txtServiceResponse + "Error Communicating with Intuit Anywhere" + we.Message;
                }
            }
        }
        public ActionResult GetBlueDotMenu()
        {
            SessionWrapper sessObj = new SessionWrapper();
            GlobalVariablesWrapper glblObj = new GlobalVariablesWrapper();
            ApplicationUserAppValues usrAppObj = new ApplicationUserAppValues();

            SessionWrapper.ServiceEndPoint = Constants.IaEndPoints.BlueDotAppMenuUrl;
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey = ApplicationUserAppValues.ConsumerKey,
                SignatureMethod = SignatureMethod.HmacSha1,
                ConsumerSecret = ApplicationUserAppValues.ConsumerSecret
            };

            OAuthSession oSession = new OAuthSession(consumerContext, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlRequestToken,
                                  Constants.OauthEndPoints.AuthorizeUrl,
                                  Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlAccessToken);

            oSession.ConsumerContext.UseHeaderForOAuthParameters = true;

            oSession.AccessToken = new TokenBase
            {
                Token = SessionWrapper.accessToken,
                ConsumerKey = ApplicationUserAppValues.ConsumerKey,
                TokenSecret = SessionWrapper.accessTokenSecret
            };

            IConsumerRequest conReq = oSession.Request();
            conReq = conReq.Get();
            conReq = conReq.ForUrl(SessionWrapper.ServiceEndPoint);
            try
            {
                conReq = conReq.SignWithToken();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            string header = conReq.Context.GenerateOAuthParametersForHeader();
            try
            {

                GlobalVariablesWrapper.TxtServiceResponseForMenu = conReq.ReadBody();
                //check alternative but this should work nimisha
                Response.Write(GlobalVariablesWrapper.TxtServiceResponseForMenu);
            }
            catch (WebException we)
            {
                HttpWebResponse rsp = (HttpWebResponse)we.Response;
                if (rsp != null)
                {
                    try
                    {
                        using (StreamReader reader = new StreamReader(rsp.GetResponseStream()))
                        {
                            GlobalVariablesWrapper.TxtServiceResponseForMenu = GlobalVariablesWrapper.TxtServiceResponseForMenu + rsp.StatusCode + " | " + reader.ReadToEnd();
                        }
                    }
                    catch (Exception)
                    {
                        GlobalVariablesWrapper.TxtServiceResponseForMenu = GlobalVariablesWrapper.TxtServiceResponseForMenu + "Status code: " + rsp.StatusCode;
                    }
                }
                else
                {
                    GlobalVariablesWrapper.TxtServiceResponseForMenu = GlobalVariablesWrapper.TxtServiceResponseForMenu + "Error Communicating with Intuit Anywhere" + we.Message;
                }
            }

            return View("GetBlueDotMenu");
        }
        /// <summary>
        /// Creates a HttpRequest with oAuthSession (OAuth Token) and gets the response with invalidating user
        /// from QuickBooks for this app
        /// For Authorization: The request header must include the OAuth parameters defined by OAuth Core 1.0 Revision A.
        /// If the disconnect is successful, then the HTTP status code is 200 and 
        /// the XML response includes the <ErrorCode> element with a 0 value.  
        /// If an HTTP error is detected, then the HTTP status code is not 200.  
        /// If an HTTP error is not detected but the disconnect is unsuccessful, 
        /// then the HTTP status code is 200 and the response XML includes the <ErrorCode> element with a non-zero value.   
        /// For example,  if the OAuth access token expires or is invalid for some other reason, then the value of <ErrorCode> is 270.
        /// </summary>
        /// <returns>Action Result</returns>
        public ActionResult Index()
        {
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(),
                SignatureMethod = SignatureMethod.HmacSha1,
                ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"].ToString()
            };

            OAuthSession oSession = new OAuthSession(consumerContext, Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlRequestToken,
                                  Constants.OauthEndPoints.AuthorizeUrl,
                                  Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlAccessToken);

            oSession.ConsumerContext.UseHeaderForOAuthParameters = true;
            if ((Session["accessToken"] + "").Length > 0)
            {
                oSession.AccessToken = new TokenBase
                {
                    Token = Session["accessToken"].ToString(),
                    ConsumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(),
                    TokenSecret = Session["accessTokenSecret"].ToString()
                };

                IConsumerRequest conReq = oSession.Request();
                conReq = conReq.Get();
                conReq = conReq.ForUrl(Constants.IaEndPoints.DisconnectUrl);
                try
                {
                    conReq = conReq.SignWithToken();
                }
                catch (Exception ex)
                {
                    throw ex;
                }

                //Used just see the what header contains
                string header = conReq.Context.GenerateOAuthParametersForHeader();

                //This method will clean up the OAuth Token
                txtServiceResponse = conReq.ReadBody();

                //Reset All the Session Variables
                Session.Remove("oauthToken");

                // Dont remove the access token since this is required for Reconnect btn in the Blue dot menu
                // Session.Remove("accessToken");

                // Add the invalid access token into session for the display of the Disconnect btn
                Session["InvalidAccessToken"] = Session["accessToken"];

                // Dont Remove flag since we need to display the blue dot menu for Reconnect btn in the Blue dot menu
                // Session.Remove("Flag");

                ViewBag.DisconnectFlg = "User is Disconnected from QuickBooks!";

                //Remove the Oauth access token from the OauthAccessTokenStorage.xml
                OauthAccessTokenStorageHelper.RemoveInvalidOauthAccessToken(Session["FriendlyEmail"].ToString(), this);
            }

            return View();
        }
    public void TokenSecretNotIncludedInQueryParametersForGetRequest()
    {
      var session = new OAuthSession(new OAuthConsumerContext {ConsumerKey = "consumer"}, "http://localhost/request",
                                     "http://localhost/userauth", "http://localhost/access");

      var accessToken = new TokenBase {ConsumerKey = "consumer", Token = "token", TokenSecret = "secret"};

      RequestDescription description = session
        .Request(accessToken)
        .Get()
        .ForUrl("http://localhost/")
        .SignWithToken()
        .GetRequestDescription();

      Assert.False(description.Url.ToString().Contains(Parameters.OAuth_Token_Secret));
    }
示例#24
0
        public static void Run()
        {
            // 0. Create the consumer session
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey = PartnerConsumerKey,
                ConsumerSecret = PartnerConsumerSecret,
                SignatureMethod = SignatureMethod.RsaSha1,
                UseHeaderForOAuthParameters = true,
                UserAgent = PartnerUserAgentString,
                Key = OAuthSigningCertificate.PrivateKey
            };

            OAuthSession consumerSession = new OAuthSession(
                consumerContext,
                Settings.Default.PartnerRequestTokenURI,
                Settings.Default.AuthoriseURI,
                Settings.Default.PartnerAccessTokenURI);

            // Replace the default ConsumerRequest factory with one that can create ConsumerRequest classes which use a client SSL certificate
            consumerSession.ConsumerRequestFactory = new DefaultConsumerRequestFactory(ClientSslCertificateFactory);


            // 1. Get a request token
            IToken requestToken;

            try
            {
                requestToken = consumerSession.GetRequestToken();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return;
            }

            Console.WriteLine("Request Token Key: {0}", requestToken.Token);
            Console.WriteLine("Request Token Secret: {0}", requestToken.TokenSecret);


            // 2. Get the user to log into Xero using the request token in the querystring
            //string authorisationUrl = Settings.Default.AuthoriseURI.AbsoluteUri + "?oauth_token=" + HttpUtility.UrlEncode(requestTokenKey);
            string authorisationUrl = consumerSession.GetUserAuthorizationUrlForToken(requestToken);
            Process.Start(authorisationUrl);

            // 3. Get the use to enter the authorisation code from Xero (4-7 digit number)
            Console.WriteLine("Please input the code you were given in Xero:");
            var verificationCode = Console.ReadLine();

            if (string.IsNullOrEmpty(verificationCode))
            {
                Console.WriteLine("You didn't type a verification code!");
                return;
            }

            verificationCode = verificationCode.Trim();


            // 4. Use the request token and verification code to get an access token
            AccessToken accessToken;

            try
            {
                accessToken = consumerSession.ExchangeRequestTokenForAccessToken(requestToken, verificationCode);
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }

            Console.WriteLine("Access Token Key: {0}", accessToken.Token);
            Console.WriteLine("Access Token Secret: {0}", accessToken.TokenSecret);


            // 5. Make a call to api-partner.network.xero.com to check that we can use the access token.
            IConsumerRequest getOrganisationRequest = consumerSession
                .Request()
                .ForMethod("GET")
                .ForUri(new Uri("https://api-partner.network.xero.com/api.xro/2.0/Organisation"))
                .SignWithToken(accessToken);

            string getOrganisationResponse = getOrganisationRequest.ToString();

            if (getOrganisationResponse != string.Empty)
            {
                XElement organisationXml = XElement.Parse(getOrganisationResponse);
                string organisationName = organisationXml.XPathSelectElement("//Organisation/Name").Value;
                Console.WriteLine(string.Format("You have been authorised against organisation: {0}", organisationName));
            }


            // 5.1 Refresh the access token using the session handle
            try
            {
                accessToken = consumerSession.RenewAccessToken(accessToken, accessToken.SessionHandle);

                Console.WriteLine("The access token has been refreshed");
                Console.WriteLine("New Access Token: " + accessToken.Token);
                Console.WriteLine("New Access Secret: " + accessToken.TokenSecret);
            }
            catch (Exception ex)
            {
                Console.WriteLine("The access token could not be refreshed:\r\n" + ex);
                return;
            }


            // 6. Make a PUT call to the API - add a dummy contact
            Console.WriteLine("Please enter the name of a new contact to add to Xero");
            string contactName = Console.ReadLine();

            if (string.IsNullOrEmpty(contactName))
            {
                return;
            }

            string putContactRequestBody = string.Format("<Contacts><Contact><Name>{0}</Name></Contact></Contacts>", contactName);
            string putContactResponse;

            IConsumerRequest putContactRequest = consumerSession
                .Request()
                .ForMethod("PUT")
                .ForUri(new Uri("https://api-partner.network.xero.com/api.xro/2.0/Contacts"))
                .WithFormParameters(new { xml = putContactRequestBody })
                .SignWithToken(accessToken);

            try
            {
                putContactResponse = putContactRequest.ToString();
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }
            catch (WebException ex)
            {
                putContactResponse = ex.Response.GetResponseStream().ReadToEnd();

                Console.WriteLine("A WebException was caught:");
                Console.WriteLine(putContactResponse);
                return;
            }

            if (putContactResponse != string.Empty)
            {
                var responseElement = XElement.Parse(putContactResponse);
                string statusCode = responseElement.XPathSelectElement("/Status").Value;

                if (statusCode == "OK")
                {
                    string contactId = responseElement.XPathSelectElement("/Contacts/Contact[1]/ContactID").Value;
                    Console.WriteLine(string.Format("The contact '{0}' was created with id: {1}", contactName, contactId));
                }
            }


            // 7. Try to update the contact that's just been created, but this time use a POST method
            string postContactRequestBody = string.Format("<Contacts><Contact><Name>{0}</Name><EmailAddress>{1}@nowhere.com</EmailAddress></Contact></Contacts>", contactName, contactName.ToLower().Replace(" ", "."));
            string postContactResponse;

            IConsumerRequest postContactRequest = consumerSession
                .Request()
                .ForMethod("POST")
                .ForUri(new Uri("https://api-partner.network.xero.com/api.xro/2.0/Contacts"))
                .WithFormParameters(new { xml = postContactRequestBody })
                .SignWithToken(accessToken);

            try
            {
                postContactResponse = postContactRequest.ToString();
            }
            catch (OAuthException ex)
            {
                Console.WriteLine("An OAuthException was caught:");
                Console.WriteLine(ex.Report);
                return;
            }
            catch (WebException ex)
            {
                putContactResponse = ex.Response.GetResponseStream().ReadToEnd();

                Console.WriteLine("A WebException was caught:");
                Console.WriteLine(putContactResponse);
                return;
            }

            if (postContactResponse != string.Empty)
            {
                var responseElement = XElement.Parse(postContactResponse);
                string statusCode = responseElement.XPathSelectElement("/Status").Value;

                if (statusCode == "OK")
                {
                    string emailAddress = responseElement.XPathSelectElement("/Contacts/Contact[1]/EmailAddress").Value;
                    Console.WriteLine(string.Format("The contact '{0}' was updated with email address: {1}", contactName, emailAddress));
                }
            }
        }
        static void Main(string[] args)
        {
            var consumerContext = new OAuthConsumerContext
                {
                    SignatureMethod = SignatureMethod.HmacSha1,
                    ConsumerKey = "dai4siwkt27bo3r", // this is just a sample app setup for demo purposes called "DevDefinedOAuthTest", it's a sandbox app in "Development" mode.
                    ConsumerSecret = "emsponeqnebimbm", 
                    UseHeaderForOAuthParameters = true // this is required for the PUT request with raw body to succeed.
                };

            var session = new OAuthSession(consumerContext, "https://api.dropbox.com/1/oauth/request_token",
                                           "https://www.dropbox.com/1/oauth/authorize",
                                           "https://api.dropbox.com/1/oauth/access_token");

            IToken requestToken = session.GetRequestToken();

            string authorisationUrl = session.GetUserAuthorizationUrlForToken(requestToken);

            Console.WriteLine("Authorization Url: {0}", authorisationUrl);

            Process.Start(authorisationUrl);

            Console.WriteLine();

            Console.WriteLine("Press enter once authorization complete");

            Console.ReadLine();

            session.ExchangeRequestTokenForAccessToken(requestToken);

            string accountInfo = session.Request().Get().ForUrl("https://api.dropbox.com/1/account/info").ReadBody();

            Console.WriteLine("Account info: {0}", accountInfo);

            Console.WriteLine();

            Console.WriteLine("Press enter to continue (will put file into sandbox)");

            Console.ReadLine();

            Console.WriteLine("Uploading...");

            const string root = "sandbox"; // can also be "dropbox" (if app has all folders access)

            string fileName = "img_" + Guid.NewGuid() + ".png";

            string putUrl = string.Format("https://api-content.dropbox.com/1/files_put/{0}/{1}", root, fileName);

            byte[] contents = File.ReadAllBytes("DevDefinedOAuthTitle.png");

            IConsumerRequest putRequest = session.Request().Put().ForUrl(putUrl).WithRawContent(contents);

            string putInfo = putRequest.ReadBody();

            Console.WriteLine("Put response: {0}", putInfo);

            Console.WriteLine();

            Console.WriteLine("Press enter to exit");

            Console.ReadLine();
            
        }
示例#26
0
        private void WhoScoredConsumer()
        {
            X509Certificate2 certificate = TestCertificates.OAuthTestCertificate();

            string requestUrl = ConfigurationManager.AppSettings["requestUrl"];
            string userAuthorizeUrl = ConfigurationManager.AppSettings["userAuthorizeUrl"];
            string accessUrl = ConfigurationManager.AppSettings["accessUrl"];
            string callBackUrl = ConfigurationManager.AppSettings["callBackUrl"];

            var consumerContext = new OAuthConsumerContext
            {
                ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
                ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"],
                SignatureMethod = SignatureMethod.HmacSha1,
                Key = certificate.PrivateKey
            };

            var session = new OAuthSession(consumerContext, requestUrl, userAuthorizeUrl, accessUrl);

            // get a request token from the provider
            //IToken requestToken = session.GetRequestToken();

            // generate a user authorize url for this token (which you can use in a redirect from the current site)
            //string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callBackUrl);

            const string Verifier = "8yeydIESPsinquIQ";
            // exchange a request token for an access token
            //IToken accessToken = session.ExchangeRequestTokenForAccessToken(requestToken, Verifier);
            session.AccessToken = new TokenBase();
            session.AccessToken.Token = ConfigurationManager.AppSettings["accessTokenKey"];
            session.AccessToken.TokenSecret = ConfigurationManager.AppSettings["accessTokenSecret"];

            // make a request for a protected resource
            string matchesArchive = "?file=matchesarchive&version=1.1";

            string responseText = session.Request().Get().ForUrl(string.Format("http://chpp.hattrick.org/chppxml.ashx{0}", matchesArchive)).ToString();
        }