Esempio n. 1
0
        /// <summary>
        /// GET USER ACCESS TOKEN
        /// </summary>
        /// <returns>OAuth1Credentials</returns>
        public async Task <AccessToken> ExchangeRequestTokenForAccessToken(RequestToken requestToken, string oAuthVerifier)
        {
            var authorizer = new OAuthAuthorizer(_consumerKey, _consumerSecret);
            TokenResponse <AccessToken> accessTokenResponse = await authorizer.GetAccessToken("https://oauth.withings.com/account/access_token", requestToken, oAuthVerifier);

            return(accessTokenResponse.Token);
        }
Esempio n. 2
0
        protected async Task <TumblrCredentials> GetAccessToken(TumblrClientCredentials clientCredentials, string webAuthResultResponseData, string tokenSecret)
        {
            string responseData = webAuthResultResponseData.Substring(webAuthResultResponseData.IndexOf("oauth_token", StringComparison.Ordinal));

            if (responseData.EndsWith("#_=_"))
            {
                responseData = responseData.Substring(0, responseData.Length - 4);
            }
            string requestToken = null, oauthVerifier = null;

            String[] keyValPairs = responseData.Split('&');

            foreach (string t in keyValPairs)
            {
                String[] splits = t.Split('=');
                switch (splits[0])
                {
                case "oauth_token":
                    requestToken = splits[1];
                    break;

                case "oauth_verifier":
                    oauthVerifier = splits[1];
                    break;
                }
            }

            var authorizer = new OAuthAuthorizer(clientCredentials);

            var accessToken = await authorizer.GetAccessToken(AccessTokenUrl, new RequestToken(requestToken, tokenSecret), oauthVerifier).ConfigureAwait(false);

            return(new TumblrCredentials(accessToken.Token.Key, accessToken.Token.Secret));
        }
Esempio n. 3
0
        public async Task AuthorizeAsync()
        {
            if (IsAuthorized)
            {
                return;
            }

            await authorizationLock.WaitAsync();

            if (IsAuthorized)
            {
                return;
            }

            try
            {
                var authorizer           = new OAuthAuthorizer(consumerKey, consumerSecret);
                var requestTokenResponse = await authorizer.GetRequestToken(requestTokenUri, requestTokenParameters);

                var requestToekn  = requestTokenResponse.Token;
                var pinRequestUri = authorizer.BuildAuthorizeUrl(authorizeUri, requestToekn);
                var pinCode       = await retrievePin(pinRequestUri);

                var accessTokenResponse = await authorizer.GetAccessToken(accessTokenUri, requestToekn, pinCode);

                accessToken = accessTokenResponse.Token;
            }
            finally
            {
                authorizationLock.Release();
            }
        }
Esempio n. 4
0
        // sample flow for Hatena authroize
        public async static Task<AccessToken> AuthorizeSample(string consumerKey, string consumerSecret)
        {
            // create authorizer
            var authorizer = new OAuthAuthorizer(consumerKey, consumerSecret);

            // get request token
            var tokenResponse = await authorizer.GetRequestToken(
                "https://www.hatena.com/oauth/initiate",
                new[] { new KeyValuePair<string, string>("oauth_callback", "oob") },
                new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("scope", "read_public,write_public,read_private,write_private") }));
            var requestToken = tokenResponse.Token;

            var pinRequestUrl = authorizer.BuildAuthorizeUrl("https://www.hatena.ne.jp/oauth/authorize", requestToken);

            // open browser and get PIN Code
            Process.Start(pinRequestUrl);

            // enter pin
            Console.WriteLine("ENTER PIN");
            var pinCode = Console.ReadLine();

            // get access token
            var accessTokenResponse = await authorizer.GetAccessToken("https://www.hatena.com/oauth/token", requestToken, pinCode);

            // save access token.
            var accessToken = accessTokenResponse.Token;
            Console.WriteLine("Key:" + accessToken.Key);
            Console.WriteLine("Secret:" + accessToken.Secret);

            return accessToken;
        }
Esempio n. 5
0
        /// <summary>
        /// アクセストークン取得
        /// </summary>
        /// <param name="authorizer"></param>
        /// <param name="requestToken"></param>
        /// <returns></returns>
        private static async Task <AccessToken> GetAccessTokenAsync(OAuthAuthorizer authorizer, RequestToken requestToken, string username, string password)
        {
            var requestUri = new Uri(authorizer.BuildAuthorizeUrl(AuthorizeBaseUrl, requestToken));

            // rkmの取得にrkが必要
            var rk = await GetRkAsync(username, password);

            var handler = new HttpClientHandler()
            {
                AllowAutoRedirect = false
            };

            var client = new HttpClient(handler);

            client.DefaultRequestHeaders.Add("User-Agent", UserAgent);
            client.DefaultRequestHeaders.Add("Cookie", $"rk={rk}");

            // 認証の自動化にrkmが必要
            string rks = string.Empty;
            string rkm = string.Empty;

            using (var response = await client.GetAsync("http://b.hatena.ne.jp/my.name"))
            {
                var json = await response.Content.ReadAsStringAsync();

                rks = JObject.Parse(json).Value <string>("rks");
                rkm = JObject.Parse(json).Value <string>("rkm");
            }

            if (string.IsNullOrEmpty(rkm))
            {
                throw new HttpRequestException("rkm");
            }

            var param = new FormUrlEncodedContent(new Dictionary <string, string>
            {
                { "rkm", rkm },
                { "oauth_token", requestToken.Key },
                { "name", "%E8%A8%B1%E5%8F%AF%E3%81%99%E3%82%8B" }
            });

            // OAuth認証
            using (var response = await client.PostAsync(AuthorizeBaseUrl, param))
            {
                var responseData = response.Headers.Location;
                var regex        = new Regex(@"oauth_verifier=(.+)&?");
                var match        = regex.Match(responseData.Query);
                if (match.Success)
                {
                    var verifier            = Uri.UnescapeDataString(match.Groups[1].Value);
                    var accessTokenResponse = await authorizer.GetAccessToken(AccessTokenUrl, requestToken, verifier);

                    return(accessTokenResponse.Token);
                }
                else
                {
                    throw new HttpRequestException("failed to get the access token");
                }
            }
        }
Esempio n. 6
0
        public async Task <AuthCredential> ProcessApprovedAuthCallbackAsync(RequestToken token)
        {
            if (token == null)
            {
                throw new ArgumentNullException("token", "RequestToken cannot be null");
            }

            if (string.IsNullOrWhiteSpace(token.Token))
            {
                throw new ArgumentNullException("token", "RequestToken.Token must not be null");
            }

            var oauthRequestToken = new AsyncOAuth.RequestToken(token.Token, token.Secret);
            var authorizer        = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);
            var accessToken       = await authorizer.GetAccessToken(Constants.BaseApiUrl + Constants.TemporaryCredentialsAccessTokenUri, oauthRequestToken, token.Verifier);

            var result = new AuthCredential
            {
                AuthToken       = accessToken.Token.Key,
                AuthTokenSecret = accessToken.Token.Secret,
                UserId          = accessToken.ExtraData["encoded_user_id"].FirstOrDefault()
            };

            return(result);
        }
Esempio n. 7
0
    public void getAttributes(string audience_email)
    {
        try{
            System.Net.ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;

            /*------------------------------- Edit the information below ------------------------*/

            string CONDUCTTR_PROJECT_ID                   = "";
            string CONDUCTTR_CONSUMER_KEY                 = "";
            string CONDUCTTR_CONSUMER_SECRET              = "";
            string CONDUCTTR_CONSUMER_ACCESS_TOKEN        = "";
            string CONDUCTTR_CONSUMER_ACCESS_TOKEN_SECRET = "";
            string CONDUCTTR_API_GET_METHOD               = "";

            /*------------------------------- Edit the information above ------------------------*/


            Uri URL = new Uri("https://api.conducttr.com/v1/project/" + CONDUCTTR_PROJECT_ID + "/" + CONDUCTTR_API_GET_METHOD + "?audience_email=" + audience_email);

            var config = new OAuthConfig()
            {
                ConsumerKey = CONDUCTTR_CONSUMER_KEY, ConsumerSecret = CONDUCTTR_CONSUMER_SECRET
            };
            OAuthAuthorizer auth = new OAuthAuthorizer(config);
            auth.AccessToken       = CONDUCTTR_CONSUMER_ACCESS_TOKEN;
            auth.AccessTokenSecret = CONDUCTTR_CONSUMER_ACCESS_TOKEN_SECRET;

            //string json = "";
            WWW www = GET(URL.ToString() + "&" + OAuthAuthorizer.AuthorizeRequest2(config, CONDUCTTR_CONSUMER_ACCESS_TOKEN, CONDUCTTR_CONSUMER_ACCESS_TOKEN_SECRET, "GET", URL, null));
        }
        catch (Exception e) {
            Debug.Log(e.Message + " : " + e.StackTrace);
            //status.text = e.Message;
        }
    }
 public void Initialize()
 {
     _authorizer = new OAuthAuthorizer(Setting.GlobalConsumerKey.Value ?? App.ConsumerKey,
      Setting.GlobalConsumerSecret.Value ?? App.ConsumerSecret);
     CurrentAuthenticationStep = AuthenticationStep.RequestingToken;
     Observable.Defer(() => _authorizer.GetRequestToken(RequestTokenEndpoint).ToObservable())
         .Retry(3, TimeSpan.FromSeconds(3)) // twitter sometimes returns an error without any troubles.
         .Subscribe(t =>
         {
             _currentRequestToken = t.Token;
             CurrentAuthenticationStep = AuthenticationStep.WaitingPinInput;
             BrowserHelper.Open(_authorizer.BuildAuthorizeUrl(AuthorizationEndpoint, t.Token));
         },
         ex => this.Messenger.Raise(new TaskDialogMessage(
                                        new TaskDialogOptions
                                        {
                                            Title = "OAuth認証エラー",
                                            MainIcon = VistaTaskDialogIcon.Error,
                                            MainInstruction = "Twitterと正しく通信できませんでした。",
                                            Content = "何度も繰り返し発生する場合は、しばらく時間を置いて試してみてください。",
                                            CommonButtons = TaskDialogCommonButtons.Close,
                                            FooterIcon = VistaTaskDialogIcon.Information,
                                            FooterText = "コンピュータの時計が大幅にずれている場合も認証が行えないことがあります。"
                                        })));
 }
 public void Initialize()
 {
     _authorizer = new OAuthAuthorizer(Setting.GlobalConsumerKey.Value ?? App.ConsumerKey,
      Setting.GlobalConsumerSecret.Value ?? App.ConsumerSecret);
     CurrentAuthenticationStep = AuthenticationStep.RequestingToken;
     Observable.Defer(() => _authorizer.GetRequestToken(RequestTokenEndpoint).ToObservable())
               .Retry(3, TimeSpan.FromSeconds(3)) // twitter sometimes returns an error without any troubles.
               .Subscribe(
                   t =>
                   {
                       _currentRequestToken = t.Token;
                       CurrentAuthenticationStep = AuthenticationStep.WaitingPinInput;
                       BrowserHelper.Open(_authorizer.BuildAuthorizeUrl(AuthorizationEndpoint, t.Token));
                   },
                   ex => this.Messenger.RaiseSafe(() => new TaskDialogMessage(new TaskDialogOptions
                   {
                       Title = AuthorizationWindowResources.OAuthErrorTitle,
                       MainIcon = VistaTaskDialogIcon.Error,
                       MainInstruction = AuthorizationWindowResources.OAuthErrorInst,
                       Content = AuthorizationWindowResources.OAuthErrorContent,
                       CommonButtons = TaskDialogCommonButtons.Close,
                       FooterIcon = VistaTaskDialogIcon.Information,
                       FooterText = AuthorizationWindowResources.OAuthErrorFooter,
                   })));
 }
Esempio n. 10
0
 public void CheckAuthorize()
 {
     if (IsKeyChecking) return;
     IsKeyChecking = true;
     var authorizer = new OAuthAuthorizer(OverrideConsumerKey, OverrideConsumerSecret);
     Observable.Defer(() => authorizer.GetRequestToken(AuthorizationViewModel.RequestTokenEndpoint))
         .Retry(3, TimeSpan.FromSeconds(3))
         .Finally(() => IsKeyChecking = false)
         .Subscribe(_ =>
         {
             Setting.GlobalConsumerKey.Value = this.OverrideConsumerKey;
             Setting.GlobalConsumerSecret.Value = this.OverrideConsumerSecret;
             UpdateEndpointKey();
             this.Messenger.Raise(new WindowActionMessage(WindowAction.Close));
         },
         ex => this.Messenger.Raise(new TaskDialogMessage(
                                        new TaskDialogOptions
                                        {
                                            Title = "認証失敗",
                                            MainIcon = VistaTaskDialogIcon.Error,
                                            MainInstruction = "API Keyの正当性を確認できませんでした。",
                                            Content = "キーの入力を確認し、再度お試しください。",
                                            CommonButtons = TaskDialogCommonButtons.Close,
                                            FooterIcon = VistaTaskDialogIcon.Information,
                                            FooterText = "Twitterの調子が悪いときやコンピュータの時計が大幅にずれている場合も認証が行えないことがあります。"
                                        })));
 }
Esempio n. 11
0
        // sample flow for Hatena authroize
        public async static Task <AccessToken> AuthorizeSample(string consumerKey, string consumerSecret)
        {
            // create authorizer
            var authorizer = new OAuthAuthorizer(consumerKey, consumerSecret);

            // get request token
            var tokenResponse = await authorizer.GetRequestToken(
                "https://www.hatena.com/oauth/initiate",
                new[] { new KeyValuePair <string, string>("oauth_callback", "oob") },
                new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("scope", "read_public,write_public,read_private,write_private") }));

            var requestToken = tokenResponse.Token;

            var pinRequestUrl = authorizer.BuildAuthorizeUrl("https://www.hatena.ne.jp/oauth/authorize", requestToken);

            // open browser and get PIN Code
            Process.Start(pinRequestUrl);

            // enter pin
            Console.WriteLine("ENTER PIN");
            var pinCode = Console.ReadLine();

            // get access token
            var accessTokenResponse = await authorizer.GetAccessToken("https://www.hatena.com/oauth/token", requestToken, pinCode);

            // save access token.
            var accessToken = accessTokenResponse.Token;

            Console.WriteLine("Key:" + accessToken.Key);
            Console.WriteLine("Secret:" + accessToken.Secret);

            return(accessToken);
        }
Esempio n. 12
0
 public void Initialize()
 {
     _authorizer = new OAuthAuthorizer(Setting.GlobalConsumerKey.Value ?? App.ConsumerKey,
                                       Setting.GlobalConsumerSecret.Value ?? App.ConsumerSecret);
     CurrentAuthenticationStep = AuthenticationStep.RequestingToken;
     Observable.Defer(() => _authorizer.GetRequestToken(RequestTokenEndpoint).ToObservable())
     .Retry(3, TimeSpan.FromSeconds(3))           // twitter sometimes returns an error without any troubles.
     .Subscribe(
         t =>
     {
         _currentRequestToken      = t.Token;
         CurrentAuthenticationStep = AuthenticationStep.WaitingPinInput;
         BrowserHelper.Open(_authorizer.BuildAuthorizeUrl(AuthorizationEndpoint, t.Token));
     },
         ex => Messenger.RaiseSafe(() => new TaskDialogMessage(new TaskDialogOptions
     {
         Title           = AuthorizationWindowResources.OAuthErrorTitle,
         MainIcon        = VistaTaskDialogIcon.Error,
         MainInstruction = AuthorizationWindowResources.OAuthErrorInst,
         Content         = AuthorizationWindowResources.OAuthErrorContent,
         CommonButtons   = TaskDialogCommonButtons.Close,
         FooterIcon      = VistaTaskDialogIcon.Information,
         FooterText      = AuthorizationWindowResources.OAuthErrorFooter
     })));
 }
        private void SignRequest(WebRequest request)
        {
            var requestUri = request.RequestUri;

            if (request.RequestUri.Host.Contains("runscope"))
            {
                var url = request.RequestUri.ToString().Replace("payment-cmtapi-com-hqy5tesyhuwv.runscope.net", "payment.cmtapi.com");
                requestUri = new Uri(url);
            }

            var oauthHeader = OAuthAuthorizer.AuthorizeRequest(ConsumerKey,
                                                               ConsumerSecretKey,
                                                               "",
                                                               "",
                                                               request.Method,
                                                               requestUri,
                                                               null);

            request.Headers.Add(HttpRequestHeader.Authorization, oauthHeader);
            request.ContentType = ContentType.Json;


            _logger.Maybe(() => _logger.LogMessage("CMT request header info : " + request.Headers));
            _logger.Maybe(() => _logger.LogMessage("CMT request info : " + request.ToJson()));
        }
Esempio n. 14
0
        // sample flow for Twitter authroize
        public static async Task <AccessToken> Authorize(string consumerKey, string consumerSecret)
        {
            // create authorizer
            var authorizer = new OAuthAuthorizer(consumerKey, consumerSecret);

            // get request token
            TokenResponse <RequestToken> tokenResponse = await authorizer.GetRequestToken(
                RequestTokenUrl,
                new[] { new KeyValuePair <string, string>("oauth_callback", "oob") });

            RequestToken requestToken = tokenResponse.Token;

            string pinRequestUrl = authorizer.BuildAuthorizeUrl(AuthorizeTokenUrl, requestToken);

            // open browser and get PIN Code
            Process.Start(pinRequestUrl);

            // enter pin
            System.Console.WriteLine("ENTER PIN");
            string pinCode = System.Console.ReadLine();

            // get access token
            TokenResponse <AccessToken> accessTokenResponse = await authorizer.GetAccessToken(AccessTokenUrl, requestToken, pinCode);

            // save access token.
            AccessToken accessToken = accessTokenResponse.Token;

            return(accessToken);
        }
        public void Share(string message, Action onRequestDone)
        {
            var content = string.Format("status={0}&trim_user=true&include_entities=true", OAuthEncoder.PercentEncode(message));
            var taskUri = new Uri("https://api.twitter.com/1/statuses/update.json");
            var client  = GetClient();

            client.Headers [HttpRequestHeader.Authorization] = OAuthAuthorizer.AuthorizeRequest(_oauthConfig, _oAuthToken, _oAuthTokenSecret, "POST", taskUri, content);

            try
            {
                client.UploadData(taskUri, "POST", Encoding.UTF8.GetBytes(content));
                if (onRequestDone != null)
                {
                    onRequestDone();
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine("Error while posting on Twitter. Message: " + ex.Message);
            }
            finally
            {
                client.Dispose();
            }
        }
Esempio n. 16
0
        // sample flow for Twitter authroize
        public async static Task <AccessToken> AuthorizeSample(string consumerKey, string consumerSecret)
        {
            // create authorizer
            var authorizer = new OAuthAuthorizer(consumerKey, consumerSecret);

            // get request token
            var tokenResponse = await authorizer.GetRequestToken("https://api.twitter.com/oauth/request_token");

            var requestToken = tokenResponse.Token;

            var pinRequestUrl = authorizer.BuildAuthorizeUrl("https://api.twitter.com/oauth/authorize", requestToken);

            // open browser and get PIN Code
            Process.Start(pinRequestUrl);

            // enter pin
            Console.WriteLine("ENTER PIN");
            var pinCode = Console.ReadLine();

            // get access token
            var accessTokenResponse = await authorizer.GetAccessToken("https://api.twitter.com/oauth/access_token", requestToken, pinCode);

            // save access token.
            var accessToken = accessTokenResponse.Token;

            Console.WriteLine("Key:" + accessToken.Key);
            Console.WriteLine("Secret:" + accessToken.Secret);

            return(accessToken);
        }
Esempio n. 17
0
        // sample flow for Twitter authroize
        public static async Task<AccessToken> Authorize(string consumerKey, string consumerSecret)
        {
            // create authorizer
            var authorizer = new OAuthAuthorizer(consumerKey, consumerSecret);

            // get request token
            TokenResponse<RequestToken> tokenResponse = await authorizer.GetRequestToken(
                RequestTokenUrl,
                new[] {new KeyValuePair<string, string>("oauth_callback", "oob")});
            RequestToken requestToken = tokenResponse.Token;

            string pinRequestUrl = authorizer.BuildAuthorizeUrl(AuthorizeTokenUrl, requestToken);

            // open browser and get PIN Code
            Process.Start(pinRequestUrl);

            // enter pin
            System.Console.WriteLine("ENTER PIN");
            string pinCode = System.Console.ReadLine();

            // get access token
            TokenResponse<AccessToken> accessTokenResponse = await authorizer.GetAccessToken(AccessTokenUrl, requestToken, pinCode);

            // save access token.
            AccessToken accessToken = accessTokenResponse.Token;

            return accessToken;
        }
Esempio n. 18
0
        public OAuthClient(string consumerKey, string consumerSecret)
        {
            _consumerKey = consumerKey;
            _consumerSecret = consumerSecret;

            _authorizer = new OAuthAuthorizer(_consumerKey, _consumerSecret);
        }
Esempio n. 19
0
        // sample flow for Twitter authroize
        public async static Task<AccessToken> AuthorizeSample(string consumerKey, string consumerSecret)
        {
            // create authorizer
            var authorizer = new OAuthAuthorizer(consumerKey, consumerSecret);

            // get request token
            var tokenResponse = await authorizer.GetRequestToken("https://api.twitter.com/oauth/request_token");
            var requestToken = tokenResponse.Token;

            var pinRequestUrl = authorizer.BuildAuthorizeUrl("https://api.twitter.com/oauth/authorize", requestToken);

            // open browser and get PIN Code
            Process.Start(pinRequestUrl);

            // enter pin
            Console.WriteLine("ENTER PIN");
            var pinCode = Console.ReadLine();

            // get access token
            var accessTokenResponse = await authorizer.GetAccessToken("https://api.twitter.com/oauth/access_token", requestToken, pinCode);

            // save access token.
            var accessToken = accessTokenResponse.Token;
            Console.WriteLine("Key:" + accessToken.Key);
            Console.WriteLine("Secret:" + accessToken.Secret);

            return accessToken;
        }
        public string GenerateAuthUrlFromRequestToken(RequestToken requestToken)
        {
            // create authorizer
            var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);
            //requestUrl buildAuthroizeUrl is putting together a callback url
            var requestUrl = authorizer.BuildAuthorizeUrl("https://oauth.withings.com/account/authorize", requestToken);

            return(requestUrl);
        }
        protected override void SaveCredentials(OAuthAuthorizer oauth)
        {
            var editor = _parent.GetSharedPreferences(KEY, FileCreationMode.Private).Edit();

            editor.PutString(TWOAuthToken, oauth.AccessToken);
            editor.PutString(TWOAuthTokenSecret, oauth.AccessTokenSecret);
            editor.PutString(TWOAccessId, oauth.AccessId.ToString());
            editor.PutString(TWOAccessScreenName, oauth.AccessScreenname);
            editor.Commit();
        }
        protected override void SaveCredentials(OAuthAuthorizer oauth)
        {
            var defaults = NSUserDefaults.StandardUserDefaults;

            defaults [TWOAuthToken]        = new NSString(oauth.AccessToken);
            defaults [TWOAuthTokenSecret]  = new NSString(oauth.AccessTokenSecret);
            defaults [TWOAccessId]         = new NSString(oauth.AccessId.ToString());
            defaults [TWOAccessScreenName] = new NSString(oauth.AccessScreenname);
            defaults.Synchronize();
        }
Esempio n. 23
0
        public async Task<string> BeginAuthorizedAsync(ConsumerData data)
        {
            authorizer = new OAuthAuthorizer(data.ConsumerKey,data.ConsumerSecret);

             var tokenResponse = await authorizer.GetRequestToken(TwitterUrl.GetRequestTokenUrl);
             requestToken = tokenResponse.Token;
            
            var pinRequestUrl = authorizer.BuildAuthorizeUrl(TwitterUrl.AuthorizeUrl, requestToken);
            return pinRequestUrl;
        }
        public void GetUserInfos(Action <TwitterUserInfo> onRequestDone)
        {
            var content = string.Format("user_id={0}&screen_name={1}", OAuthEncoder.PercentEncode(_userId), OAuthEncoder.PercentEncode(_screenName));
            var taskUri = new Uri("https://api.twitter.com/1.1/users/show.json?" + content);
            var request = (HttpWebRequest)WebRequest.Create(taskUri);

            request.AutomaticDecompression = DecompressionMethods.GZip;
            request.Headers [HttpRequestHeader.Authorization] = OAuthAuthorizer.AuthorizeRequest(_oauthConfig, _oAuthToken, _oAuthTokenSecret, "GET", taskUri, null);

            TwitterUserInfo userInfos = null;

            request.BeginGetResponse(ar => {
                try {
                    var response = (HttpWebResponse)request.EndGetResponse(ar);
                    using (var stream = response.GetResponseStream())
                    {
                                                #if !WINDOWS
                        var jentry   = (JsonObject)JsonValue.Load(stream);
                        userInfos    = new TwitterUserInfo();
                        userInfos.Id = jentry["id_str"];
                        string name  = jentry["name"];
                        if (name.Contains(" "))
                        {
                            userInfos.Firstname = name.Substring(0, name.IndexOf(" "));
                            userInfos.Lastname  = name.Substring(name.IndexOf(" ") + 1);
                        }
                        else
                        {
                            userInfos.Firstname = name;
                        }
                        userInfos.City = jentry["location"];
                                                #endif
                    }
                } catch (WebException we) {
                    var response = we.Response as HttpWebResponse;
                    if (response != null)
                    {
                        switch (response.StatusCode)
                        {
                        case HttpStatusCode.Unauthorized:
                            // This is the case of sharing two keys
                            break;
                        }
                    }
                    Console.WriteLine(we);
                }
                finally{
                    if (onRequestDone != null)
                    {
                        onRequestDone(userInfos);
                    }
                }
            }, null);
        }
Esempio n. 25
0
        public async Task <RequestToken> GetRequestToken()
        {
            var authorizer = new OAuthAuthorizer(_consumerKey, _consumerSecret);
            var parameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("oauth_callback", Uri.EscapeUriString(_callbackUrl))
            };
            TokenResponse <RequestToken> tokenResponse = await authorizer.GetRequestToken("https://oauth.withings.com/account/request_token", parameters);

            return(tokenResponse.Token);
        }
        public async Task <AccessToken> VerifyUserAsync(string verifier)
        {
            ValidateAccessToken();

            const string accessUrl = AuthUrl + "/access_token/";

            OAuthAuthorizer             authorizer = new OAuthAuthorizer(_consumerKey, _consumerSecret);
            TokenResponse <AccessToken> response   = await authorizer.GetAccessToken(accessUrl, new RequestToken(AccessToken.Key, AccessToken.Secret), verifier).ConfigureAwait(false);

            AccessToken = response.Token;
            return(AccessToken);
        }
Esempio n. 27
0
        private void SignRequest(WebRequest request)
        {
            var oauthHeader = OAuthAuthorizer.AuthorizeRequest(ConsumerKey,
                                                               ConsumerSecretKey,
                                                               "",
                                                               "",
                                                               request.Method,
                                                               request.RequestUri,
                                                               null);

            request.Headers.Add(HttpRequestHeader.Authorization, oauthHeader);
        }
Esempio n. 28
0
        /// <summary>
        /// アプリケーション認証用の URI を取得します。
        /// </summary>
        /// <param name="consumerKey">アプリケーションの Consumer Key。</param>
        /// <param name="consumerSecret">アプリケーションの Consumer Secret。</param>
        /// <returns>アプリケーション認証用の URI を返す非同期操作を表す <see cref="Task{TResult}"/> オブジェクト。</returns>
        /// <exception cref="ArgumentException"><paramref name="consumerKey"/> または <paramref name="consumerSecret"/> が空文字列です。</exception>
        /// <exception cref="ArgumentNullException"><paramref name="consumerKey"/> または <paramref name="consumerSecret"/> が <see langword="null"/> です。</exception>
        /// <exception cref="HttpRequestException">HTTP リクエストに失敗しました。</exception>
        public async static Task <Session> AuthorizeAsync(string consumerKey, string consumerSecret)
        {
            Validation.NotNullOrEmpty(consumerKey, nameof(consumerKey));
            Validation.NotNullOrEmpty(consumerSecret, nameof(consumerSecret));

            var authorizer    = new OAuthAuthorizer(consumerKey, consumerSecret);
            var tokenResponse = await authorizer.GetRequestToken(_requestTokenUri, _parameters, new FormUrlEncodedContent(_postContents));

            var requestToken = tokenResponse.Token;

            return(new Session(authorizer, requestToken, consumerKey, consumerSecret));
        }
Esempio n. 29
0
        public async Task <string> BeginAuthorizedAsync(ConsumerData data)
        {
            authorizer = new OAuthAuthorizer(data.ConsumerKey, data.ConsumerSecret);

            var tokenResponse = await authorizer.GetRequestToken(TwitterUrl.GetRequestTokenUrl);

            requestToken = tokenResponse.Token;

            var pinRequestUrl = authorizer.BuildAuthorizeUrl(TwitterUrl.AuthorizeUrl, requestToken);

            return(pinRequestUrl);
        }
Esempio n. 30
0
        public static List <Task <string> > DownloadAllJsonAsync(this IEnumerable <string> urls, TwitterAuth twitterAuth)
        {
            if (twitterAuth == null)
            {
                return(urls.DownloadAllAsync(ContentType.Json));
            }

            return(urls.DownloadAllAsync(ContentType.Json, (webReq, uri) => {
                webReq.Headers[HttpRequestHeader.Authorization] = OAuthAuthorizer.AuthorizeRequest(
                    twitterAuth.OAuthProvider, twitterAuth.AccessToken, twitterAuth.AccessTokenSecret, HttpMethod.Get, uri, null);
            }));
        }
Esempio n. 31
0
        // sample flow for Twitter authroize
        public async static Task <AccessToken> GetAccessToken(string consumerKey, string consumerSecret, string pinCode)
        {
            // create authorizer
            var authorizer = new OAuthAuthorizer(consumerKey, consumerSecret);

            // get access token
            var accessTokenResponse = await authorizer.GetAccessToken("https://api.twitter.com/oauth/access_token", requestToken, pinCode);

            // save access token.
            var accessToken = accessTokenResponse.Token;

            return(accessToken);
        }
Esempio n. 32
0
 /// <summary>
 /// For Desktop authentication. Your code should direct the user to the FitBit website to get
 /// Their pin, they can then enter it here.
 /// </summary>
 /// <param name="pin"></param>
 /// <param name="token"></param>
 /// <returns></returns>
 public async Task<AuthCredential> GetAuthCredentialFromPinAsync(string pin, RequestToken token)
 {
     var oauthRequestToken = new AsyncOAuth.RequestToken(token.Token, token.Secret);
     var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);
     var accessTokenResponse = await authorizer.GetAccessToken(Constants.BaseApiUrl + Constants.TemporaryCredentialsAccessTokenUri, oauthRequestToken, pin);
     // save access token.
     var accessToken = accessTokenResponse.Token;
     return new AuthCredential
     {
         AuthToken = accessToken.Key,
         AuthTokenSecret = accessToken.Secret
     };
 }
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     LoginText = "Please wait...";
     var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);
     authorizer.GetRequestToken(BaseUrl + "/oauth", new Codeplex.OAuth.Parameter("oauth_callback", "http://localhost/myapp"))
     .Select(res => res.Token)
     .ObserveOnDispatcher()
     .Subscribe(token => {
         requestToken = token;
         var url = authorizer.BuildAuthorizeUrl(BaseUrl + "/OAuth.action", token);
         wbLogin.Navigate(new Uri(url)); // navigate browser
     });
 }
Esempio n. 34
0
            internal Session(OAuthAuthorizer authorizer, RequestToken requestToken, string consumerKey, string consumerSecret)
            {
                Debug.Assert(authorizer != null);
                Debug.Assert(requestToken != null);
                Debug.Assert(!string.IsNullOrEmpty(consumerKey));
                Debug.Assert(!string.IsNullOrEmpty(consumerSecret));

                _authorizer           = authorizer;
                _requestToken         = requestToken;
                this.AuthorizationUri = authorizer.BuildAuthorizeUrl(_authorizationUri, requestToken);
                this.ConsumerKey      = consumerKey;
                this.ConsumerSecret   = consumerSecret;
            }
Esempio n. 35
0
        // sample flow for Hatena authroize
        public async static Task <AccessToken> AuthorizeSampleRedirect(string consumerKey, string consumerSecret)
        {
            // create authorizer
            var authorizer = new OAuthAuthorizer(consumerKey, consumerSecret);

            // get request token
            var tokenResponse = await authorizer.GetRequestToken(
                "https://www.hatena.com/oauth/initiate",
                new[] { new KeyValuePair <string, string>("oauth_callback", "http://dev.clock-up.jp/redirect_to_app.php") },
                new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("scope", "read_public") }));

            var requestToken = tokenResponse.Token;

            //

            // ブラウザ起動
            var pinRequestUrl = authorizer.BuildAuthorizeUrl("https://www.hatena.ne.jp/oauth/authorize", requestToken);

            Process.Start(pinRequestUrl);

            // 認証が成功すると、
            // http://dev.clock-up.jp/redirect_to_app.php?oauth_token=LjjaOIMY8fXTAA%3D%3D&oauth_verifier=77EbWdvM9KWG1Tjct%2FphLI%2Fp
            // のような形式でモノが来る

            // query to verifier -> verifier
            Console.WriteLine("ENTER QUERY PARAMETERS");
            var query = Console.ReadLine();

            string[] parameters = query.Split('&');
            string   verifier   = "";

            foreach (var p in parameters)
            {
                if (p.StartsWith("oauth_verifier="))
                {
                    verifier = p.Substring("oauth_verifier=".Length);
                }
            }
            var accessTokenResponse = await authorizer.GetAccessToken("https://www.hatena.com/oauth/token", requestToken, verifier);

            // get access token
            // var accessTokenResponse = await authorizer.GetAccessToken("https://www.hatena.com/oauth/token", requestToken, pinCode);

            // save access token.
            var accessToken = accessTokenResponse.Token;

            Console.WriteLine("Key:" + accessToken.Key);
            Console.WriteLine("Secret:" + accessToken.Secret);

            return(accessToken);
        }
Esempio n. 36
0
 public void LoadWebBrowser(WebBrowser browser)
 {
     var authorizer = new OAuthAuthorizer(AppBootstrapper.ConsumerKey, AppBootstrapper.ConsumerSecret);
     authorizer.GetRequestToken("https://api.twitter.com/oauth/request_token")
         .Select(x => x.Token)
         .DispatcherSubscribe(
             token =>
             {
                 _token = token;
                 string url = authorizer.BuildAuthorizeUrl("https://api.twitter.com/oauth/authorize", token);
                 browser.Navigate(new Uri(url));
             },
             OnError);
 }
Esempio n. 37
0
        // Get RequestToken flow sample
        // create authorizer and call "GetRequestToken" and "BuildAuthorizeUrl"
        private void GetRequestTokenButton_Click(object sender, RoutedEventArgs e)
        {
            var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);

            authorizer.GetRequestToken("http://twitter.com/oauth/request_token")
            .Select(res => res.Token)
            .Subscribe(token =>
            {
                requestToken = token;
                var url      = authorizer.BuildAuthorizeUrl("http://twitter.com/oauth/authorize", token);
                Process.Start(url);     // open browser
                MessageBox.Show("check browser, allow oauth and enter pincode");
            }, ex => MessageBox.Show(ReadWebException(ex)));
        }
Esempio n. 38
0
        /// <summary>
        /// For Desktop authentication. Your code should direct the user to the FitBit website to get
        /// Their pin, they can then enter it here.
        /// </summary>
        /// <param name="pin"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task <AuthCredential> GetAuthCredentialFromPinAsync(string pin, RequestToken token)
        {
            var oauthRequestToken   = new AsyncOAuth.RequestToken(token.Token, token.Secret);
            var authorizer          = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);
            var accessTokenResponse = await authorizer.GetAccessToken(Constants.BaseApiUrl + Constants.TemporaryCredentialsAccessTokenUri, oauthRequestToken, pin);

            // save access token.
            var accessToken = accessTokenResponse.Token;

            return(new AuthCredential
            {
                AuthToken = accessToken.Key,
                AuthTokenSecret = accessToken.Secret
            });
        }
Esempio n. 39
0
        /// <summary>
        /// リクエストトークン取得
        /// </summary>
        /// <param name="authorizer"></param>
        /// <returns></returns>
        private static async Task <RequestToken> GetRequestTokenAsync(OAuthAuthorizer authorizer)
        {
            var requestTokenResponse = await authorizer.GetRequestToken(
                RequestTokenUrl,
                new[]
            {
                new KeyValuePair <string, string>("oauth_callback", CallbackUrl)
            },
                new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("scope", "read_private,read_public,write_public")
            }));

            return(requestTokenResponse.Token);
        }
Esempio n. 40
0
        public void LoadWebBrowser(WebBrowser browser)
        {
            var authorizer = new OAuthAuthorizer(AppBootstrapper.ConsumerKey, AppBootstrapper.ConsumerSecret);

            authorizer.GetRequestToken("https://api.twitter.com/oauth/request_token")
            .Select(x => x.Token)
            .DispatcherSubscribe(
                token =>
            {
                _token     = token;
                string url = authorizer.BuildAuthorizeUrl("https://api.twitter.com/oauth/authorize", token);
                browser.Navigate(new Uri(url));
            },
                OnError);
        }
Esempio n. 41
0
        // Get RequestToken flow sample
        // create authorizer and call "GetRequestToken" and "BuildAuthorizeUrl"
        private void GetRequestTokenButton_Click(object sender, RoutedEventArgs e)
        {
            var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);

            authorizer.GetRequestToken("http://twitter.com/oauth/request_token")
            .Select(res => res.Token)
            .ObserveOnDispatcher()
            .Subscribe(token =>
            {
                requestToken = token;
                var url      = authorizer.BuildAuthorizeUrl("http://twitter.com/oauth/authorize", token);
                webBrowser1.Navigate(new Uri(url));
                BrowserAuthorize.Visibility = System.Windows.Visibility.Visible;
            }, ex => MessageBox.Show(ReadWebException(ex)));
        }
Esempio n. 42
0
        /// <summary>
        /// First step in the OAuth process is to ask Fitbit for a temporary request token. 
        /// From this you should store the RequestToken returned for later processing the auth token.
        /// </summary>
        /// <returns></returns>
        public async Task<RequestToken> GetRequestTokenAsync()
        {
            // create authorizer
            var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);

            // get request token
            var tokenResponse = await authorizer.GetRequestToken(Constants.BaseApiUrl + Constants.TemporaryCredentialsRequestTokenUri);
            var requestToken = tokenResponse.Token;

            // return the request token
            return new RequestToken
            {
                Token = requestToken.Key,
                Secret = requestToken.Secret
            };
        }
Esempio n. 43
0
        public void AuthenticatePin()
        {
            Enforce.NotNull(_token);

            int pin;
            if (!int.TryParse(Pin, out pin))
                throw new InvalidOperationException("The PIN must be a number.");

            var authorizer = new OAuthAuthorizer(AppBootstrapper.ConsumerKey, AppBootstrapper.ConsumerSecret);
            authorizer.GetAccessToken("https://twitter.com/oauth/access_token", _token, Pin)
                .DispatcherSubscribe(
                    response =>
                    {
                        AppSettings.UserOAuthToken = response.Token.Key;
                        AppSettings.UserOAuthTokenSecret = response.Token.Secret;
                        _eventAggregator.Publish(new AuthenticatedMessage());
                    },
                    OnError);
        }
Esempio n. 44
0
        public async Task<AuthCredential> ProcessApprovedAuthCallbackAsync(RequestToken token)
        {
            if (token == null)
                throw new ArgumentNullException("token", "RequestToken cannot be null");

            if (string.IsNullOrWhiteSpace(token.Token))
                throw new ArgumentNullException("token", "RequestToken.Token must not be null");

            var oauthRequestToken = new AsyncOAuth.RequestToken(token.Token, token.Secret);
            var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);
            var accessToken = await authorizer.GetAccessToken(Constants.BaseApiUrl + Constants.TemporaryCredentialsAccessTokenUri, oauthRequestToken, token.Verifier);

            var result = new AuthCredential
            {
                AuthToken = accessToken.Token.Key,
                AuthTokenSecret = accessToken.Token.Secret,
                UserId = accessToken.ExtraData["encoded_user_id"].FirstOrDefault()
            };
            return result;
        }
Esempio n. 45
0
		public static IObservable<RequestTokenData> GetRequestToken(this TwitterClient client, string consumerKey, string consumerSecret)
		{
			var authorizer = new OAuthAuthorizer(consumerKey, consumerSecret);
			if (client.CurrentNetworkProfile != null)
			{
				if (client.CurrentNetworkProfile.Proxy != null)
				{
					authorizer.ApplyBeforeRequest += req => req.Proxy = client.CurrentNetworkProfile.Proxy.GetProxy();
				}
			}

			return Observable
				.Defer(() => authorizer.GetRequestToken(RestApi.OAuthEndpoints["oauth/request_token"].Url))
				.OnErrorRetry(3)
				.Select(res => new RequestTokenData
				{
					Token = res.Token,
					AuthorizeUrl = new Uri(authorizer.BuildAuthorizeUrl(RestApi.OAuthEndpoints["oauth/authorize"].Url, res.Token)),
				});
		}
Esempio n. 46
0
		public static IObservable<AccessTokenData> GetAccessToken(this TwitterClient client, string consumerKey, string consumerSecret, RequestToken token, string pincode)
		{
			var authorizer = new OAuthAuthorizer(consumerKey, consumerSecret);
			if (client.CurrentNetworkProfile != null)
			{
				if (client.CurrentNetworkProfile.Proxy != null)
				{
					authorizer.ApplyBeforeRequest += req => req.Proxy = client.CurrentNetworkProfile.Proxy.GetProxy();
				}
			}

			return Observable
				.Defer(() => authorizer.GetAccessToken(RestApi.OAuthEndpoints["oauth/access_token"].Url, token, pincode))
				.OnErrorRetry(3)
				.Select(res => new AccessTokenData
				{
					Token = res.Token,
					ScreenName = res.ExtraData["screen_name"].FirstOrDefault(),
					UserId = Convert.ToInt64(res.ExtraData["user_id"].FirstOrDefault()),
				});
		}
Esempio n. 47
0
        public ViewModel()
        {
            _getRequestToken = new Lazy<Command>(() =>
                new Command(_ =>
                {
                    var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);
                    authorizer.GetRequestToken("http://twitter.com/oauth/request_token")
                    .Select(res => res.Token)
                    .ObserveOnDispatcher()
                    .Subscribe(token =>
                    {
                        requestToken = token;
                        AuthorizeUrl = authorizer.BuildAuthorizeUrl("http://twitter.com/oauth/authorize", token);
                    }, e => MessageBox.Show(e.ToString()));
                    _getAccessToken.Value.IsCanExecute = true;
                })
            );
            _getAccessToken = new Lazy<Command>(() =>
                new Command(_ =>
                {
                    new OAuthAuthorizer(ConsumerKey, ConsumerSecret).GetAccessToken("http://twitter.com/oauth/access_token", requestToken, PinCode)
                        .ObserveOnDispatcher()
                        .Subscribe(res =>
                        {
                            UserId = res.ExtraData["user_id"].First();
                            ScreenName = res.ExtraData["screen_name"].First();
                            accessToken = res.Token;
                            _startGetTimeline.Value.IsCanExecute = true;
                        }, e => MessageBox.Show(e.ToString()));
                    CanGetTimeline(this, new EventArgs());
                    _getAccessToken.Value.IsCanExecute = false;
                    AuthorizeUrl = "";
                }, false)
             );

            _startGetTimeline = new Lazy<Command>(() =>
            {
                return new Command(_ =>
                {
                    StreamingApi = new OAuthClient(ConsumerKey, ConsumerSecret, accessToken) { Url = "https://userstream.twitter.com/2/user.json" }
                        .GetResponseLines()
                        .Where(s => !string.IsNullOrWhiteSpace(s)) // filter invalid data
                        .Select(s => DynamicJson.Parse(s)).Publish();
                    StreamingApi.Take(1).Subscribe(x => friendList = new HashSet<int>(((double[])x.friends).Select(id => (int)id)), e => MessageBox.Show(e.ToString(), "FriendList"));
                    StreamingApi.Subscribe(x => this.PropertyChanged(x, new PropertyChangedEventArgs("StreamingApi")), e => MessageBox.Show(e.ToString(), "プロパティ変更"));
                    StreamingApi
                        .Where(x => x.text())
                        .ObserveOnDispatcher()
                        .Subscribe(x =>
                        {
                            _tweet.Add(new TimelineItemViewModel(x));
                            this.PropertyChanged(this, new PropertyChangedEventArgs("Tweet"));
                        });
                    ((IConnectableObservable<dynamic>)StreamingApi).Connect();
                    _startGetTimeline.Value.IsCanExecute = false;
                }, false);
            });

            //PropertyChanged += new PropertyChangedEventHandler((sender, target) => { if (target.PropertyName == "StreamingApi") MessageBox.Show(); });
            CanGetTimeline += new EventHandler((sender, e) => _startGetTimeline.Value.IsCanExecute = true);
        }
Esempio n. 48
0
 public void CheckAuthorize()
 {
     if (OverrideConsumerKey == App.ConsumerKey)
     {
         this.Messenger.Raise(new TaskDialogMessage(
             new TaskDialogOptions
             {
                 Title = "キー設定エラー",
                 MainIcon = VistaTaskDialogIcon.Error,
                 MainInstruction = "このキーは設定できません。",
                 Content = "APIキーくらい横着しないで自分で取得しろ",
                 CommonButtons = TaskDialogCommonButtons.Close
             }));
         return;
     }
     if (!(System.Text.RegularExpressions.Regex.Match(OverrideConsumerKey, "^[a-zA-Z0-9]+$")).Success)
     {
         this.Messenger.Raise(new TaskDialogMessage(
             new TaskDialogOptions
             {
                 Title = "キー設定エラー",
                 MainIcon = VistaTaskDialogIcon.Error,
                 MainInstruction = "Consumer Keyが間違っています。",
                 Content = "入力されたConsumer Keyに使用できない文字が含まれています。入力したキーを確認してください。",
                 CommonButtons = TaskDialogCommonButtons.Close
             }));
         return;
     }
     if (!(System.Text.RegularExpressions.Regex.Match(OverrideConsumerSecret, "^[a-zA-Z0-9]+$")).Success)
     {
         this.Messenger.Raise(new TaskDialogMessage(
             new TaskDialogOptions
             {
                 Title = "キー設定エラー",
                 MainIcon = VistaTaskDialogIcon.Error,
                 MainInstruction = "Consumer Secretが間違っています。",
                 Content = "入力されたConsumer Secretに使用できない文字が含まれています。入力したキーを確認してください。",
                 CommonButtons = TaskDialogCommonButtons.Close
             }));
         return;
     }
     if (IsKeyChecking) return;
     IsKeyChecking = true;
     var authorizer = new OAuthAuthorizer(OverrideConsumerKey, OverrideConsumerSecret);
     Observable.Defer(
         () => authorizer.GetRequestToken(AuthorizationViewModel.RequestTokenEndpoint).ToObservable())
               .Retry(3, TimeSpan.FromSeconds(3))
               .Finally(() => IsKeyChecking = false)
               .Subscribe(
                   _ =>
                   {
                       Setting.GlobalConsumerKey.Value = this.OverrideConsumerKey;
                       Setting.GlobalConsumerSecret.Value = this.OverrideConsumerSecret;
                       UpdateEndpointKey();
                       this.Messenger.Raise(new WindowActionMessage(WindowAction.Close));
                   },
                   ex => this.Messenger.Raise(
                       new TaskDialogMessage(
                           new TaskDialogOptions
                           {
                               Title = "OAuth認証エラー",
                               MainIcon = VistaTaskDialogIcon.Error,
                               MainInstruction = "API Keyの正当性を確認できませんでした。",
                               Content = "キーの入力を確認し、再度お試しください。",
                               CommonButtons = TaskDialogCommonButtons.Close,
                               FooterIcon = VistaTaskDialogIcon.Information,
                               FooterText = "Twitterの調子が悪いときやコンピュータの時計が大幅にずれている場合も認証が行えないことがあります。"
                           })));
 }
        private void WbLoginOnNavigating(object sender, NavigatingEventArgs e)
        {
            if (e.Uri.ToString().StartsWith("http://localhost/myapp")) {
                var splitted = e.Uri.ToString().Split('&').Select(s => s.Split('=')).ToDictionary(s => s.First(), s => s.Last());
                if (!splitted.ContainsKey("oauth_verifier")) {
                    ((Storyboard)Resources["HidePopupAnimation"]).Begin();
                    return;
                }
                string verifier = splitted["oauth_verifier"];
                var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret);
                authorizer.GetAccessToken(BaseUrl + "/oauth", requestToken, verifier)
                    .ObserveOnDispatcher()
                    .Subscribe(res => {
                        try {
                            AuthenticationResult result = new AuthenticationResult();
                            result.AuthenticationToken = Uri.UnescapeDataString(res.Token.Key);
                            result.NoteStoreUrl = Uri.UnescapeDataString(res.ExtraData["edam_noteStoreUrl"].First());
                            result.Expiration = long.Parse(res.ExtraData["edam_expires"].First());
                            result.WebApiUrlPrefix = Uri.UnescapeDataString(res.ExtraData["edam_webApiUrlPrefix"].First());
                            result.User = new User();
                            result.User.Id = int.Parse(res.ExtraData["edam_userId"].First());
                            MessageBox.Show("Login Success. Token is " + result.AuthenticationToken);
                        }
                        catch (KeyNotFoundException) {

                        }
                        finally {
                            ((Storyboard)Resources["HidePopupAnimation"]).Begin();
                        }
                    });

                e.Cancel = true;
                wbLogin.Visibility = Visibility.Collapsed;
            }
        }
Esempio n. 50
0
        /// <summary>
        /// Open linkedin auth page
        /// </summary>
        private void li_connection()
        {
            // Get linkedin authorization url for app
              var authorizer = new OAuthAuthorizer(SWLinkedInSettings.ConsumerKey, SWLinkedInSettings.ConsumerSecret);
              authorizer.GetRequestToken(SWLinkedInSettings.RequestTokenUri)
              .Select(res => res.Token)
              .ObserveOnDispatcher()
              .Subscribe(token =>
              {
            // Save request token
            this.li_requestToken = token;

            //linkedInRequestToken = token;
            string uri = authorizer.BuildAuthorizeUrl(SWLinkedInSettings.AuthorizeUri, token);
            authBrowser.Navigate(new Uri(uri));
              });
        }
Esempio n. 51
0
        /// <summary>
        /// Get linkedin access token from uri
        /// </summary>
        private void handleLinkedInAuthorization(Uri uri)
        {
            var results = GeneralUtils.GetQueryParameters(uri);

              // If no verifier or query, we return to page
              if (results == null || !results.ContainsKey("oauth_verifier"))
              {
            liFailedAndGoBack();
            return;
              }

              // Handle no linkedin request token
              if (li_requestToken == null)
              {
            liFailedAndGoBack();
            return;
              }

              // clean up
              StorageUtils.RemoveData(Constants.LI_TOKEN);

              // Get access token
              string verifyPin = results["oauth_verifier"];
              var authorizer = new OAuthAuthorizer(SWLinkedInSettings.ConsumerKey, SWLinkedInSettings.ConsumerSecret);
              authorizer.GetAccessToken(SWLinkedInSettings.AccessTokenUri, this.li_requestToken, verifyPin)
            .ObserveOnDispatcher()
            .Subscribe(res =>
            {
              if (res == null)
              {
            liFailedAndGoBack();
            return;
              }
              SWLinkedInSettings.SetAccessToken(res.Token);
              // Notify UI that linkedin is now connected
              PhoneApplicationService.Current.State[Constants.AUTH_NOTIFICATION] = "LinkedIn is now enabled!";
              goBack();
            });
        }
Esempio n. 52
0
		public Authorizer(string consumerKey, string consumerSecret)
		{
			this.consumerKey = consumerKey;
			this.consumerSecret = consumerSecret;
			authorizer = new OAuthAuthorizer(consumerKey, consumerSecret);
		}
Esempio n. 53
0
 public void CheckAuthorize()
 {
     if (OverrideConsumerKey == App.ConsumerKey)
     {
         this.Messenger.Raise(new TaskDialogMessage(
             new TaskDialogOptions
             {
                 Title = KeyOverrideWindowResources.MsgKeySettingError,
                 MainIcon = VistaTaskDialogIcon.Error,
                 MainInstruction = KeyOverrideWindowResources.MsgBlockingKeyInst,
                 Content = KeyOverrideWindowResources.MsgBlockingKeyContent,
                 CommonButtons = TaskDialogCommonButtons.Close
             }));
         return;
     }
     if (!(System.Text.RegularExpressions.Regex.Match(OverrideConsumerKey, "^[a-zA-Z0-9]+$")).Success)
     {
         this.Messenger.Raise(new TaskDialogMessage(
             new TaskDialogOptions
             {
                 Title = KeyOverrideWindowResources.MsgKeySettingError,
                 MainIcon = VistaTaskDialogIcon.Error,
                 MainInstruction = KeyOverrideWindowResources.MsgInvalidKeyInst,
                 Content = KeyOverrideWindowResources.MsgInvalidKeyContent,
                 CommonButtons = TaskDialogCommonButtons.Close
             }));
         return;
     }
     if (!(System.Text.RegularExpressions.Regex.Match(OverrideConsumerSecret, "^[a-zA-Z0-9]+$")).Success)
     {
         this.Messenger.Raise(new TaskDialogMessage(
             new TaskDialogOptions
             {
                 Title = KeyOverrideWindowResources.MsgKeySettingError,
                 MainIcon = VistaTaskDialogIcon.Error,
                 MainInstruction = KeyOverrideWindowResources.MsgInvalidSecretInst,
                 Content = KeyOverrideWindowResources.MsgInvalidSecretContent,
                 CommonButtons = TaskDialogCommonButtons.Close
             }));
         return;
     }
     if (IsKeyChecking) return;
     IsKeyChecking = true;
     var authorizer = new OAuthAuthorizer(OverrideConsumerKey, OverrideConsumerSecret);
     Observable.Defer(
         () => authorizer.GetRequestToken(AuthorizationViewModel.RequestTokenEndpoint).ToObservable())
               .Retry(3, TimeSpan.FromSeconds(3))
               .Finally(() => IsKeyChecking = false)
               .Subscribe(
                   _ =>
                   {
                       Setting.GlobalConsumerKey.Value = this.OverrideConsumerKey;
                       Setting.GlobalConsumerSecret.Value = this.OverrideConsumerSecret;
                       UpdateEndpointKey();
                       this.Messenger.Raise(new WindowActionMessage(WindowAction.Close));
                   },
                   ex => this.Messenger.Raise(
                       new TaskDialogMessage(
                           new TaskDialogOptions
                           {
                               Title = KeyOverrideWindowResources.MsgAuthErrorTitle,
                               MainIcon = VistaTaskDialogIcon.Error,
                               MainInstruction = KeyOverrideWindowResources.MsgAuthErrorInst,
                               Content = KeyOverrideWindowResources.MsgAuthErrorContent,
                               CommonButtons = TaskDialogCommonButtons.Close,
                               FooterIcon = VistaTaskDialogIcon.Information,
                               FooterText = KeyOverrideWindowResources.MsgAuthErrorFooter,
                           })));
 }