Пример #1
0
        private IConsumerRequest CreateSignedOauthRequest(RestRequest request)
        {
            var oAuthContext         = MapRequestToOauthContext(request);
            var oAuthConsumerContext = new OAuthConsumerContext()
            {
                ConsumerKey                 = _credentials.ClientKey,
                ConsumerSecret              = _credentials.ClientSecret,
                SignatureMethod             = SignatureMethod.HmacSha1,
                UseHeaderForOAuthParameters = true
            };
            var accessToken = new AccessToken
            {
                ConsumerKey = _credentials.ClientKey,
                Token       = _credentials.TokenKey,
                TokenSecret = _credentials.TokenSecret
            };

            var consumerRequest = new ConsumerRequest(oAuthContext, oAuthConsumerContext, accessToken)
                                  .WithAcceptHeader(request.Accept)
                                  .WithRawContentType(request.ContentType);

            Dictionary <String, String> queryParams = request.QueryParameters ?? new Dictionary <String, String>();

            if (!request.IncludeHateoasLinks)
            {
                queryParams.Add("ShowLinks", "none");
            }

            consumerRequest = consumerRequest.WithQueryParameters(queryParams);

            return(consumerRequest.SignWithToken(accessToken));
        }
Пример #2
0
        //From DevDefined library
        //Builds session, stores client information in memory
        //Replace session variables with those associated with your own 3rd party app
        OAuthSession BuildSession()
        {
            Session["clientId"]    = "insert your app's clientID";
            Session["appSecret"]   = "insert your app's Secret";
            Session["redirectUri"] = "insert your redirect Uri";
            Session["scope"]       = "READ_SHEETS,WRITE_SHEETS";
            //State is an optional variable
            Session["state"] = "MY_STATE";

            var consumerContext = new OAuthConsumerContext
            {
                SignatureMethod             = SignatureMethod.HmacSha1,
                ConsumerKey                 = Session["clientId"].ToString(),
                ConsumerSecret              = Session["appSecret"].ToString(),
                UseHeaderForOAuthParameters = false
            };

            var session = new OAuthSession(consumerContext,
                                           requestTokenUrl: "https://www.smartsheet.com/b/authorize?response_type=code&client_id=" + Session["clientId"] + "&redirect_uri=" + Session["redirectUri"] + "&scope=" + Session["scope"] + "&state=" + Session["state"],
                                           userAuthorizeUrl: "https://www.smartsheet.com/b/authorize", /* not used in this flow */
                                           accessTokenUrl: "https://api.smartsheet.com/1.1/token")
            {
                CallbackUri = new Uri(GetCallbackUrl())
            };

            return(session);
        }
        // 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);
        }
Пример #4
0
        // this performs our main OAuth authentication, performing
        // the request token retrieval, authorization, and exchange
        // for an access token
        public IToken GetAccessToken()
        {
            var consumerContext = new OAuthConsumerContext()
            {
                ConsumerKey = "anyone"
            };

            var rest_client = new JsonServiceClient(BaseUri);
            var url         = new Rainy.WebService.ApiRequest().ToUrl("GET");
            var api_ref     = rest_client.Get <ApiResponse> (url);

            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);
        }
Пример #5
0
        /// <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());
                    }
            }
        }
 public DropBoxStorageProviderSession(DropBoxToken token, DropBoxConfiguration config, OAuthConsumerContext consumerContext, IStorageProviderService service)
 {
     SessionToken         = token;
     ServiceConfiguration = config;
     Service = service;
     Context = consumerContext;
 }
        static string GetDevDefinedOAuthHeader(HttpWebRequest webRequest, string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret)
        {
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey                 = consumerKey,
                ConsumerSecret              = consumerSecret,
                SignatureMethod             = SignatureMethod.HmacSha1,
                UseHeaderForOAuthParameters = true
            };

            consumerContext.UseHeaderForOAuthParameters = true;

            //URIs not used - we already have Oauth tokens
            OAuthSession oSession = new OAuthSession(consumerContext, "https://www.example.com",
                                                     "https://www.example.com",
                                                     "https://www.example.com");


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

            IConsumerRequest consumerRequest = oSession.Request();

            consumerRequest = ConsumerRequestExtensions.ForMethod(consumerRequest, webRequest.Method);
            consumerRequest = ConsumerRequestExtensions.ForUri(consumerRequest, webRequest.RequestUri);
            consumerRequest = consumerRequest.SignWithToken();
            return(consumerRequest.Context.GenerateOAuthParametersForHeader());
        }
        /// <summary>
        /// This method is able to exchange the request token into an access token which can be used in
        /// sharpbox. It is necessary that the user validated the request via authorization url otherwise
        /// this call wil results in an unauthorized exception!
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="ConsumerKey"></param>
        /// <param name="ConsumerSecret"></param>
        /// <param name="DropBoxRequestToken"></param>
        /// <returns></returns>
        static public ICloudStorageAccessToken ExchangeDropBoxRequestTokenIntoAccessToken(DropBoxConfiguration configuration, String ConsumerKey, String ConsumerSecret, DropBoxRequestToken DropBoxRequestToken)
        {
            // build the consumer context
            var consumerContext = new OAuthConsumerContext(ConsumerKey, ConsumerSecret);

            // build up the oauth session
            var serviceContext = new OAuthServiceContext(configuration.RequestTokenUrl.ToString(),
                                                         configuration.AuthorizationTokenUrl.ToString(), configuration.AuthorizationCallBack.ToString(),
                                                         configuration.AccessTokenUrl.ToString());

            // build the access token
            OAuthService svc         = new OAuthService();
            OAuthToken   accessToken = svc.GetAccessToken(serviceContext, consumerContext, DropBoxRequestToken.RealToken);

            if (accessToken == null)
            {
                throw new UnauthorizedAccessException();
            }

            // create the access token
            return(new DropBoxToken(accessToken,
                                    new DropBoxBaseTokenInformation()
            {
                ConsumerKey = ConsumerKey,
                ConsumerSecret = ConsumerSecret
            }));
        }
Пример #9
0
        /// <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 ETradeClient(Stocks.OAuthToken consumerToken, bool productionMode = false, Stocks.OAuthToken accessToken = null)
        {
            _consumerToken = new ConsumerToken {
                Token = consumerToken.Token, TokenSecret = consumerToken.Secret
            };

            _consumerContext = new OAuthConsumerContext
            {
                ConsumerKey                 = _consumerToken.Token,
                ConsumerSecret              = _consumerToken.TokenSecret,
                SignatureMethod             = SignatureMethod.HmacSha1,
                UseHeaderForOAuthParameters = true,
                CallBack = "oob"
            };

            _session = new OAuthSession(_consumerContext, RequestUrl, AuthorizeUrl, AccessTokenUrl, RenewAccessTokenUrl);

            _productionMode = productionMode;

            if (accessToken != null)
            {
                _accessToken = new AccessToken {
                    Token = accessToken.Token, TokenSecret = accessToken.Secret
                };
            }
        }
Пример #11
0
        /// <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();
        }
Пример #13
0
        private static string GetDevDefinedOAuthHeader(string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret, HttpWebRequest webRequest, string requestBody)
        {
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey                 = consumerKey,
                SignatureMethod             = SignatureMethod.HmacSha1,
                ConsumerSecret              = consumerSecret,
                UseHeaderForOAuthParameters = true
            };

            //We already have OAuth tokens, so OAuth URIs below are not used - set to example.com
            OAuthSession oSession = new OAuthSession(consumerContext, "https://www.example.com",
                                                     "https://www.example.com",
                                                     "https://www.example.com");

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

            IConsumerRequest consumerRequest = oSession.Request();

            consumerRequest = ConsumerRequestExtensions.ForMethod(consumerRequest, webRequest.Method);
            if (requestBody != null)
            {
                consumerRequest = consumerRequest.Post().WithRawContentType(webRequest.ContentType).WithRawContent(System.Text.Encoding.ASCII.GetBytes(requestBody));
            }
            consumerRequest = ConsumerRequestExtensions.ForUri(consumerRequest, webRequest.RequestUri);
            consumerRequest = consumerRequest.SignWithToken();
            return(consumerRequest.Context.GenerateOAuthParametersForHeader());
        }
        /// <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);
        }
Пример #15
0
 public GoogleDocsStorageProviderSession(IStorageProviderService service, ICloudStorageConfiguration configuration, OAuthConsumerContext context, ICloudStorageAccessToken token)
 {
     Service = service;
     ServiceConfiguration = configuration;
     Context      = context;
     SessionToken = token;
 }
        /// <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);
        }
Пример #17
0
        static string GetDevDefinedOAuthHeader(HttpWebRequest webRequest, string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret)
        {
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey                 = consumerKey,
                ConsumerSecret              = consumerSecret,
                SignatureMethod             = SignatureMethod.HmacSha1,
                UseHeaderForOAuthParameters = true
            };

            consumerContext.UseHeaderForOAuthParameters = true;
            OAuthSession oSession = new OAuthSession(consumerContext, GET_REQUEST_TOKEN, AuthorizeUrl, GET_ACCESS_TOKEN);

            oSession.AccessToken = new TokenBase
            {
                Token       = accessToken,
                ConsumerKey = consumerKey,
                TokenSecret = accessTokenSecret
            };
            IConsumerRequest consumerRequest = oSession.Request();

            consumerRequest = ConsumerRequestExtensions.ForMethod(consumerRequest, webRequest.Method);
            consumerRequest = ConsumerRequestExtensions.ForUri(consumerRequest, webRequest.RequestUri);
            consumerRequest = consumerRequest.SignWithToken();
            return(consumerRequest.Context.GenerateOAuthParametersForHeader());
        }
Пример #18
0
        //returns a consumer reference
        public static IOAuthSession EtsyConsumer()
        {
            //API EndPoints
            string requestUrl       = "https://openapi.etsy.com/v2/oauth/request_token?scope=transactions_r%20listings_r";
            string userAuthorizeUrl = "https://www.etsy.com/oauth/signin";
            string accessUrl        = "https://openapi.etsy.com/v2/oauth/access_token";

            //Dev Information
            var consumerContext = new OAuthConsumerContext
            {
                ConsumerKey     = key,
                ConsumerSecret  = secret,
                SignatureMethod = SignatureMethod.HmacSha1
            };

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

            IToken requestToken = session.GetRequestToken();

            string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, "https://bit.ly/2KQfh6x");

            //Redirect to the Authorization site
            System.Diagnostics.Process.Start(authorizationLink);

            Console.Write("Enter Verification String: ");
            string verification = Console.ReadLine();

            session.ExchangeRequestTokenForAccessToken(requestToken, verification);
            WriteToBinaryFile(@"saveData.txt", session.AccessToken);

            return(session);
        }
Пример #19
0
        public string GetOAuthAuthorizationHeader(string resourceUrl, OAuthConsumerContext conContext, OAuthToken accessToken, Dictionary <string, string> parameter, string method)
        {
            var oAuth = new OAuthBase();

            string normalizedUrl;
            string normalizedRequestParameters;

            var timestamp = oAuth.GenerateTimeStamp();
            var nonce     = oAuth.GenerateNonce();
            var signature = oAuth.GenerateSignature(new Uri(resourceUrl),
                                                    conContext.ConsumerKey, conContext.ConsumerSecret,
                                                    accessToken == null ? string.Empty : accessToken.TokenKey, accessToken == null ? string.Empty : accessToken.TokenSecret,
                                                    method, timestamp, nonce,
                                                    conContext.SignatureMethod,
                                                    out normalizedUrl, out normalizedRequestParameters);

            signature = System.Web.HttpUtility.UrlEncode(signature);

            var sb = new StringBuilder("OAuth");

            sb.Append(", oauth_version=1.0");
            sb.AppendFormat(", oauth_nonce={0}", nonce);
            sb.AppendFormat(", oauth_timestamp={0}", timestamp);
            sb.AppendFormat(", oauth_consumer_key={0}", conContext.ConsumerKey);
            if (accessToken != null)
            {
                sb.AppendFormat(", , oauth_token={0}", accessToken.TokenKey);
            }
            sb.Append(", oauth_signature_method=\"HMAC-SHA1\"");
            sb.AppendFormat(", oauth_signature={0}", signature);

            return(sb.ToString());
        }
Пример #20
0
        public OAuthToken GetRequestToken(OAuthServiceContext svcContext, OAuthConsumerContext conContext)
        {
            // generate the url
            String requestTokenUrl = OAuthUrlGenerator.GenerateRequestTokenUrl(svcContext.RequestTokenUrl, conContext);

            // get the token
            return(GetToken(requestTokenUrl));
        }
Пример #21
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();
        }
Пример #22
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();
        }
Пример #23
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     = "{발급 받은 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();
        }
Пример #24
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();

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

                // 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!";
                //Remove the Oauth access token from the OauthAccessTokenStorage.xml
                OauthAccessTokenStorageHelper.RemoveInvalidOauthAccessToken(Session["FriendlyEmail"].ToString(), Page);
            }
        }
Пример #25
0
 public ConsumerRequestTests()
 {
     context = new OAuthContext {
         RequestMethod = "POST", RawUri = new Uri("http://localhost/svc")
     };
     consumerContext = new OAuthConsumerContext {
         ConsumerKey = "key", ConsumerSecret = "secret", SignatureMethod = SignatureMethod.PlainText
     };
     accessToken = new AccessToken();
 }
Пример #26
0
		public void GetRequestTokenForConsumerWithoutCallbackUrl()
		{
			var consumerContext = new OAuthConsumerContext {ConsumerKey = "key"};

			var session = new OAuthSession(consumerContext, "http://localhost/request", "http://localhost/userauth", "http://localhost/access");

			RequestDescription description = session.BuildRequestTokenContext("POST").GetRequestDescription();

			Assert.True(description.Body.Contains("oauth_callback=oob"));
		}
Пример #27
0
        private OAuthSession GetOAuthSession(String key, String secret)
        {
            OAuthConsumerContext consumerContext = new OAuthConsumerContext();

            consumerContext.ConsumerKey     = key;
            consumerContext.ConsumerSecret  = secret;
            consumerContext.SignatureMethod = SignatureMethod.HmacSha1;

            return(new OAuthSession(consumerContext, Chpp.RequestTokenURL, Chpp.AuthorizeURL, Chpp.AccessTokenURL));
        }
Пример #28
0
        public static void Main(string[] args)
        {
            string requestTokenUrl  = "https://api.projectplace.com/initiate";
            string authorizationUrl = "https://api.projectplace.com/authorize";
            string tokenUrl         = "https://api.projectplace.com/token";
            string apiEndpoint      = "https://api.projectplace.com";
            string consumerKey      = "APPLICATION_KEY_GOES_HERE";
            string consumerSecret   = "APPLICATION_SECRET_GOES_HERE";
            IToken accessToken      = null;

            // 1. If you already have an access token - uncomment this section and enter it here.
            //IToken accessToken = new TokenBase();
            //accessToken.Token = "ACCESS_TOKEN_KEY_GOES_HERE";
            //accessToken.TokenSecret = "ACCESS_TOKEN_SECRET_GOES_HERE";

            // 2. Create the consumer context
            OAuthConsumerContext consumerContext = new OAuthConsumerContext
            {
                ConsumerKey                 = consumerKey,
                ConsumerSecret              = consumerSecret,
                SignatureMethod             = SignatureMethod.HmacSha1,
                UseHeaderForOAuthParameters = true,
            };

            // 3. Start session
            OAuthSession session = new OAuthSession(consumerContext, requestTokenUrl, authorizationUrl, tokenUrl);

            // 4. If you do not have an access token, you will first have to authorize
            // access. In this part we formulate a URI which you must open in a web-broser.
            // Once you have completed the log-in and accepted access for the application
            // You will be redirected to whatever page is in the applications callback
            // Simply check the URL and look for the oauth_verifer parameter, and copy that
            if (accessToken == null)
            {
                IToken requestToken = session.GetRequestToken();

                string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken);

                Console.WriteLine("Authorize this application by going to {0}", authorizationLink);
                Console.WriteLine("Then enter the oauth_verifier here:");
                string verificationCode = Console.ReadLine();

                accessToken = session.ExchangeRequestTokenForAccessToken(requestToken, verificationCode);
                Console.WriteLine("Here is your new access token: {0} with secret: {1}\n", accessToken.Token, accessToken.TokenSecret);
            }

            // 5. We have an access token - assign it to the session
            session.AccessToken = accessToken;

            // 6. Lets ask for a protected resource, such as your own profile
            string  responseText = session.Request().Get().ForUrl(apiEndpoint + "/1/user/me/profile").ToString();
            Profile profile      = JsonConvert.DeserializeObject <Profile>(responseText);

            Console.WriteLine("Successfully fetched profile for {0} {1}", profile.first_name, profile.last_name);
        }
        public DropBoxStorageProviderSession BuildSessionFromAccessToken(DropBoxToken token, DropBoxConfiguration configuration)
        {
            // build the consumer context
            var consumerContext = new OAuthConsumerContext(token.BaseTokenInformation.ConsumerKey, token.BaseTokenInformation.ConsumerSecret);

            // build the session
            var session = new DropBoxStorageProviderSession(token, configuration, consumerContext, this);

            // go aahead
            return(session);
        }
Пример #30
0
        private static IOAuthSession CreateSession()
        {
            var consumerContext = new OAuthConsumerContext
            {
                ConsumerKey     = ConsumerKey,
                ConsumerSecret  = ConsumerSecret,
                SignatureMethod = SignatureMethod.HmacSha1
            };

            return(new OAuthSession(consumerContext, RequestTokenUrl, OauthUrl, AccessTokenUrl));
        }