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();
		}
        public TradeMeToken AuthenticateWithVerifier(PreliminaryToken preliminaryToken, string oAuthVerifierOrPin)
        {
            if (string.IsNullOrEmpty(oAuthVerifierOrPin))
            {
                throw new Exception();
            }

            oAuthVerifierOrPin = oAuthVerifierOrPin.Trim();

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

            var session = new OAuthSession(
                consumerContext,
                Profile.Current.RequestTokenUrl + "?scope=" + _appKeys.ScopeOfRequest,
                Profile.Current.AuthorizeUrl,
                Profile.Current.AccessUrl);

            return new TradeMeToken(session.ExchangeRequestTokenForAccessToken(preliminaryToken.Token, oAuthVerifierOrPin));
        }
예제 #3
0
        // this performs our main OAuth authentication, performing
        // the request token retrieval, authorization, and exchange
        // for an access token
        public static IToken GetAccessToken()
        {
            var consumerContext = new OAuthConsumerContext () {
                ConsumerKey = "anyone"
            };

            var restClient = new JsonServiceClient (BaseUri);
            var api_ref = restClient.Get<ApiResponse> ("/api/1.0");

            var session = new OAuthSession (consumerContext, api_ref.OAuthRequestTokenUrl,
                                            api_ref.OAuthAuthorizeUrl, api_ref.OAuthAccessTokenUrl);

            IToken request_token = session.GetRequestToken ();

            // we dont need a callback url
            string link = session.GetUserAuthorizationUrlForToken (request_token, "http://example.com/");

            // visit the link to perform the authorization (no interaction needed)
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create (link);
            // disallow auto redirection, since we are interested in the location header only
            req.AllowAutoRedirect = false;

            // the oauth_verifier we need, is part of the querystring in the (redirection)
            // 'Location:' header
            string location = ((HttpWebResponse)req.GetResponse ()).Headers ["Location"];
            var query = string.Join ("", location.Split ('?').Skip (1));
            var oauth_data = System.Web.HttpUtility.ParseQueryString (query);

            IToken access_token = session.ExchangeRequestTokenForAccessToken (request_token, oauth_data ["oauth_verifier"]);

            return access_token;
        }
예제 #4
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();
        }
예제 #5
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();
        }
예제 #6
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();
        }
예제 #7
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();
        }
예제 #8
0
        public void GetAccessToken()
        {
            string requestUrl = "https://www.yammer.com/oauth/request_token";
            string userAuthorizeUrl = "https://www.yammer.com/oauth/authorize";
            string accessUrl = "https://www.yammer.com/oauth/access_token";

            var context = new OAuthConsumerContext
            {
                ConsumerKey = @"YourConsumerKey",
                ConsumerSecret = @"YourConsumerSecret",
                SignatureMethod = SignatureMethod.PlainText,
                UseHeaderForOAuthParameters = true
            };
            var session = new OAuthSession(context, requestUrl, userAuthorizeUrl, accessUrl);
            var authCode = "";
            var requestToken = session.GetRequestToken("POST");
            var authLink = session.GetUserAuthorizationUrlForToken(requestToken);
            var accessToken = session.ExchangeRequestTokenForAccessToken(requestToken, authCode);
        }
예제 #9
0
        public void GetAccessToken()
        {
            string requestUrl = "https://www.yammer.com/oauth/request_token";
            string userAuthorizeUrl = "https://www.yammer.com/oauth/authorize";
            string accessUrl = "https://www.yammer.com/oauth/access_token";

            var context = new OAuthConsumerContext
            {
                ConsumerKey = @"ZWZ4FiczbUeQbuDyp1JhDg",
                ConsumerSecret = @"14HZ8T9YgIuWQtlaFdhtLLBncWx0ZHbuoioNzdSzrA",
                SignatureMethod = SignatureMethod.PlainText,
                UseHeaderForOAuthParameters = true
            };
            var session = new OAuthSession(context, requestUrl, userAuthorizeUrl, accessUrl);
            var authCode = "";
            var requestToken = session.GetRequestToken("POST");
            var authLink = session.GetUserAuthorizationUrlForToken(requestToken);
            var accessToken = session.ExchangeRequestTokenForAccessToken(requestToken, authCode);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString.HasKeys())
            {
                var oauthVerifyer = Request.QueryString["oauth_verifier"].ToString();

                RestProfile profile = RestProfile.GetRestProfile();

                profile.RealmId = Request.QueryString["realmId"].ToString();

                switch (Request.QueryString["dataSource"].ToString().ToLower())
                {
                    case "qbo": profile.DataSource = (int)IntuitServicesType.QBO; break;
                    case "qbd": profile.DataSource = (int)IntuitServicesType.QBD; break;
                }

                OAuthConsumerContext consumerContext = new OAuthConsumerContext
                {
                    ConsumerKey = ConfigurationManager.AppSettings["consumerKey"].ToString(),
                    ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"].ToString(),
                    SignatureMethod = SignatureMethod.HmacSha1
                };

                IOAuthSession clientSession = new OAuthSession(consumerContext,
                                                Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlRequestToken,
                                                Constants.OauthEndPoints.IdFedOAuthBaseUrl,
                                                 Constants.OauthEndPoints.IdFedOAuthBaseUrl + Constants.OauthEndPoints.UrlAccessToken);

                try
                {
                    IToken accessToken = clientSession.ExchangeRequestTokenForAccessToken((IToken)Session["requestToken"], oauthVerifyer);
                    profile.OAuthAccessToken = accessToken.Token;
                    profile.OAuthAccessTokenSecret = accessToken.TokenSecret;
                    profile.Save();
                }
                catch
                {

                }
            }
        }
        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();
            
        }
예제 #12
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));
                }
            }
        }
        /// <summary>
        /// <para>This is the second and final step in the authorisation process. It uses the verification code (retrieved in public string GetVerificationCode()).
        /// </para><para>It exchanges the verification code for an access token.</para>
        /// <para>Once this step has been performed the user will be enabled to perform authenticated requests.</para>
        /// </summary>
        /// <param name="code">The verification code.</param>
        public void AuthenticateWithVerificationCode(string code)
        {
            if (string.IsNullOrEmpty(code))
            {
                throw new NoVerificationCodeException();
            }

            code = code.Trim();

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

            var session = new OAuthSession(
                consumerContext,
                RequestTokenUrl + ScopeOfRequest,
                AuthorizeUrl,
                AccessUrl);

            AccessToken = session.ExchangeRequestTokenForAccessToken(RequestToken, code);
        }
예제 #14
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));
                }
            }
        }
        public Response DoRequest()
        {
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey = Constants.OAuth.ConsumerKey,
                ConsumerSecret = Constants.OAuth.ConsumerSecret,
                SignatureMethod = Constants.OAuth.SignatureMethod,
            };

            OAuthSession session = new OAuthSession(
                consumerContext,
                Constants.OAuth.RequestTokenURL,
                Constants.OAuth.AuthorizeURL,
                Constants.OAuth.AccessTokenURL);

            string tokenCookie = null;
            ctx.Request.Cookies.TryGetValue(Constants.Cookies.OAuthTokenCookie, out tokenCookie);
            string secretCookie = null;
            ctx.Request.Cookies.TryGetValue(Constants.Cookies.OAuthSecretCookie, out secretCookie);

            if (!forceReauth && !string.IsNullOrWhiteSpace(tokenCookie) && !string.IsNullOrWhiteSpace(secretCookie))
            {
                AccessToken accessToken = new AccessToken();
                accessToken.Token = tokenCookie;
                accessToken.TokenSecret = secretCookie;

                session.AccessToken = accessToken;
            }
            else
            {
                NameValueCollection queryStringParameters = Utilities.GetQueryStringParameters(ctx, new string[] { "oauth_token", "oauth_verifier" });

                if (queryStringParameters.Count == 2)
                {
                    // Re-create the request token from the callback request from Ravelry post-user-authentication.
                    RequestToken requestToken = new RequestToken();
                    requestToken.Token = queryStringParameters["oauth_token"];

                    try
                    {
                        // TODO: Ravelry fails to accept the token here.  Debugging with them.
                        // Exchange the temporary request token for an access token which can be used to access user data.  Uses "GET".
                        IToken accessToken = session.ExchangeRequestTokenForAccessToken(requestToken, queryStringParameters["oauth_verifier"]);

                        // Save token data to cookies.
                        ctx.Response.AddCookie(new NancyCookie(Constants.Cookies.OAuthTokenCookie, accessToken.Token, true, true));
                        ctx.Response.AddCookie(new NancyCookie(Constants.Cookies.OAuthSecretCookie, accessToken.TokenSecret, true, true));
                    }
                    catch (Exception e)
                    {
                        Utilities.SetException(ctx, e);
                        return null;
                    }
                }
                else
                {
                    // Retrieve a request token from Ravelry.
                    session.CallbackUri = new System.Uri(Constants.OAuth.CallbackURL);
                    IToken requestToken = session.GetRequestToken();

                    // Generate a user authorization URL for the request token.
                    string authorizationLink = session.GetUserAuthorizationUrlForToken(
                        requestToken,
                        Constants.OAuth.CallbackURL);

                    // Redirect to Ravelry.
                    return new RedirectResponse(authorizationLink);
                }
            }

            // Save the session to the context
            Utilities.SetAuthenticatedSession(ctx, session);

            return null;
        }
예제 #16
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;
        }