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 = "コンピュータの時計が大幅にずれている場合も認証が行えないことがあります。" }))); }
// 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; }
// 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; }
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(); } }
// 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 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の調子が悪いときやコンピュータの時計が大幅にずれている場合も認証が行えないことがあります。" }))); }
// 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; }
// 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); }
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 }))); }
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, }))); }
public IObservable <string> Request() { return(authorizer.GetRequestToken(requestTokenUrl) .ToObservable() .Do(x => requestToken = x.Token) .Select(x => authorizer.BuildAuthorizeUrl(authorizeUrl, x.Token))); }
// 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 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 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); }
/// <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)); }
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); }
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 }); }
// 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); }
// 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))); }
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); }
/// <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); }
// 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))); }
// sample flow for Twitter authroize public async static Task <string> GetAuthorizeUrl(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"); requestToken = tokenResponse.Token; var pinRequestUrl = authorizer.BuildAuthorizeUrl("https://api.twitter.com/oauth/authorize", requestToken); // open browser and get PIN Code return(pinRequestUrl); }
/// <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 }; }
/// <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 }); }
// 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 => requestToken = res.Token) .ObserveOnDispatcher() .Subscribe(token => { var url = authorizer.BuildAuthorizeUrl("http://twitter.com/oauth/authorize", token); new MyHyperlink() { NavigateUri = new Uri(url), TargetName = "_blank" }.Browse(); MessageBox.Show("check browser, allow oauth and enter pincode"); }, ex => MessageBox.Show(ReadWebException(ex))); }
//public static WithingsClient Create(string consumerKey, string consumerSecret) //{ // var client = OAuthUtility.CreateOAuthClient("consumerKey", "consumerSecret", new AccessToken("accessToken", "accessTokenSecret")); //} public async Task <ActionResult> RequestTokenFlow() { //setting authorizer value to the keyvaluepair and IEnumberable key and secret var authorizer = new OAuthAuthorizer(consumerKey, consumerSecret); //Createing a KeyvaluePair for the callBack URL used in step one List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >(); parameters.Add(new KeyValuePair <string, string>("oauth_callback", Uri.EscapeUriString("http://localhost:49932/CallBack/AccessTokenFlow"))); // get request token - once url reads http://localhost:49932/Withings/RequestTokenFlow Controller begins with action result HERE var tokenResponse = await authorizer.GetRequestToken("https://oauth.withings.com/account/request_token", parameters); //Summary - Sends consumerKey and consumerSecret to withings oauth site with parameters of oauth callback valued above //setting value of the Token to the requestToken var requestToken = tokenResponse.Token; //Oauth is hashed and decoded via AsynchOauth and stored as tokenReponse.Token in requestToken variable //adding data to session //Store the products to a session Session["requestToken"] = requestToken; //requestUrl buildAuthroizeUrl is putting together a callback url var requestUrl = authorizer.BuildAuthorizeUrl("https://oauth.withings.com/account/authorize", requestToken); //creating a request url with consumerKey/Secret + withings oauth + tokenResponse.Token //Binding View to go to callback URL defined in first step ViewBag.RequestUrl = requestUrl; return(View()); }
// sample flow for Hatena authroize public static async Task <AccessToken> Authorize() { m_verifier = ""; var authorizer = new OAuthAuthorizer(HatenaConfig.CONSUMER_KEY, HatenaConfig.CONSUMER_SECRET); // 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 requestUrl = authorizer.BuildAuthorizeUrl("https://www.hatena.ne.jp/touch/oauth/authorize", requestToken); Device.OpenUri(new Uri(requestUrl)); // 認証が成功すると、 // http://dev.clock-up.jp/redirect_to_app.php?oauth_token=xxxxxx%3D%3D&oauth_verifier=xxxxxxxx%2FphLI%2Fp // のようなページが表示される。結果、アプリに呼び戻される // verifier が来るまで待つ while (true) { if (m_verifier == "CANCEL") { return(null); } if (m_verifier != "") { break; } await Task.Delay(500); } var accessTokenResponse = await authorizer.GetAccessToken("https://www.hatena.com/oauth/token", requestToken, m_verifier); // save access token. var accessToken = accessTokenResponse.Token; Debug.WriteLine("Key:" + accessToken.Key); Debug.WriteLine("Secret:" + accessToken.Secret); return(accessToken); }
public async Task <TumblrCredentials> Login() { var authorizer = new OAuthAuthorizer(Consumer); // get request token var tokenResponse = await authorizer.GetRequestToken(RequestUrl); var requestToken = tokenResponse.Token; var startUri = new Uri(authorizer.BuildAuthorizeUrl(AuthorizeUrl, requestToken)); var tokenString = await ContactWebAuthenticationBroker(startUri, CallbackUri); if (string.IsNullOrWhiteSpace(tokenString)) { return(null); } return(await GetAccessToken(Consumer, tokenString, requestToken.Secret)); }
public async Task <string> GetRequestTokenAsync(string callbackUri, CancellationToken cancellationToken = default(CancellationToken)) { // // Acquiring a request token // string authUrl = AuthUrl + "/request_token/"; var parameters = new Dictionary <string, string> { { "oauth_callback", callbackUri } }; var authorizer = new OAuthAuthorizer(_consumerKey, _consumerSecret); TokenResponse <RequestToken> tokenResponse = await authorizer.GetRequestToken(authUrl, parameters).ConfigureAwait(false); AccessToken = new AccessToken(tokenResponse.Token.Key, tokenResponse.Token.Secret); return(tokenResponse.Token.Key); }
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)), }); }
public async Task <RequestToken> GetRequestTokenAsync() { // create authorizer var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret); List <KeyValuePair <string, string> > parameters = new List <KeyValuePair <string, string> >(); parameters.Add(new KeyValuePair <string, string>("oauth_callback", Uri.EscapeUriString("http://localhost:49932/Withings/AccessTokenFlow"))); // get request token - once url reads http://localhost:49932/Withings/CallBack Controller begins with action result HERE // get request token //Summary - Sends consumerKey and consumerSecret to withings oauth site with parameters of oauth callback valued above var tokenResponse = await authorizer.GetRequestToken(Constants.BaseApiUrl + Constants.TemporaryCredentialsRequestTokenUri, parameters); var requestToken = tokenResponse.Token; // return the request token return(requestToken); }
/// <summary> /// This method makes the original call to Evernote to get a token so /// that the user can validate that they want to access this site. /// </summary> /// <param name="reauth"></param> /// <returns></returns> public ActionResult Authorize(bool reauth = false) { // Allow for reauth if (reauth) SessionHelper.Clear(); // First of all, check to see if the user is already registered, in which case tell them that if (SessionHelper.EvernoteCredentials != null) return Redirect(Url.Action("AlreadyAuthorized")); // Evernote will redirect the user to this URL once they have authorized your application var callBackUrl = Request.Url.GetLeftPart(UriPartial.Authority) + Url.Action("ObtainTokenCredentials"); // Generate a request token - this needs to be persisted till the callback var requestToken = OAuthAuthorizer.GetRequestToken(ConfigurationManager.AppSettings["Evernote.Url"] + "/oauth", new Dictionary<string, string> { { "oauth_callback", callBackUrl } }, null).Result.Token; // Persist the token SessionHelper.RequestToken = requestToken; // Redirect the user to Evernote so they can authorize the app var callForwardUrl = OAuthAuthorizer.BuildAuthorizeUrl(ConfigurationManager.AppSettings["Evernote.Url"] + "/OAuth.action", requestToken); return Redirect(callForwardUrl); }
public async Task <string> RequestPIN() { var retMessage = String.Empty; try { oAuthAuthorizer = new OAuthAuthorizer(this.oAuthConsumerKey, this.oAuthConsumerSecret); var tokenResponse = await oAuthAuthorizer.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") })); oAuthRequestToken = tokenResponse.Token; } catch (Exception ex) { retMessage = $"RequestPINでエラーが発生しました。【内容】{ex.Message}"; } if (String.IsNullOrEmpty(retMessage)) { var pinRequestUrl = oAuthAuthorizer.BuildAuthorizeUrl("https://www.hatena.ne.jp/oauth/authorize", oAuthRequestToken); try { Process.Start(pinRequestUrl); } catch (Exception ex) { retMessage = $"Webページ「{pinRequestUrl}」を開くのに失敗しました。手動で開いてください。【内容】{ex.Message}"; } } return(retMessage); }
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 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); }
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の調子が悪いときやコンピュータの時計が大幅にずれている場合も認証が行えないことがあります。" }))); }
static void Main(string[] args) { ServicePointManager.Expect100Continue = false; // set your consumerkey/secret const string ConsumerKey = ""; const string ConsumerSecret = ""; AccessToken accessToken = null; string userId, screenName; // get accesstoken flow // create authorizer and call "GetRequestToken" ,"BuildAuthorizeUrl", "GetAccessToken" // TokenResponse's ExtraData is ILookup. // if twitter, you can take "user_id" and "screen_name". // Run is sync. Subscribe is async. var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret); authorizer.GetRequestToken("http://twitter.com/oauth/request_token") .Do(r => { Console.WriteLine("Check Browser and input PinCode"); Process.Start(authorizer.BuildAuthorizeUrl("http://twitter.com/oauth/authorize", r.Token)); // open browser }) .Select(r => new { RequestToken = r.Token, PinCode = Console.ReadLine() }) .SelectMany(a => authorizer.GetAccessToken("http://twitter.com/oauth/access_token", a.RequestToken, a.PinCode)) .ForEach(r => { userId = r.ExtraData["user_id"].First(); screenName = r.ExtraData["screen_name"].First(); accessToken = r.Token; }); // get accesstoken flow by xAuth //new OAuthAuthorizer(ConsumerKey, ConsumerSecret) // .GetAccessToken("https://api.twitter.com/oauth/access_token", "username", "password") // .Run(r => accessToken = r.Token); // get timeline flow // set parameters can use Collection Initializer // if you want to set webrequest parameters then use ApplyBeforeRequest var client = new OAuthClient(ConsumerKey, ConsumerSecret, accessToken) { Url = "http://api.twitter.com/1/statuses/home_timeline.xml", Parameters = { { "count", 20 }, { "page", 1 } }, ApplyBeforeRequest = req => { req.Timeout = 1000; req.UserAgent = "ReactiveOAuth"; } }; client.GetResponseText() .Select(s => XElement.Parse(s)) .ForEach(x => Console.WriteLine(x.ToString())); // post flow // if post then set MethodType = MethodType.Post //new OAuthClient(ConsumerKey, ConsumerSecret, accessToken) //{ // MethodType = MethodType.Post, // Url = "http://api.twitter.com/1/statuses/update.xml", // Parameters = { { "status", "PostTest from ReactiveOAuth" } } //}.GetResponseText() // .Select(s => XElement.Parse(s)) // .Run(x => Console.WriteLine("Post Success:" + x.Element("text"))); // StreamingAPI sample // if you use streaming api, recommend call GetResponseLines. // see details -> WPF Sample. //new OAuthClient(ConsumerKey, ConsumerSecret, accessToken) //{ // Url = "https://userstream.twitter.com/2/user.json" //}.GetResponseLines() //.Run(s => Console.WriteLine(s)); }
/// <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)); }); }
/**********************************************************************************/ public async Task <bool> Authorize() { Logger.Trace("Authorizing"); if (string.IsNullOrEmpty(Login) || string.IsNullOrEmpty(Password)) { StatusMessage = "Nothing"; LastErrorMessage = "Password or login are no set."; return(false); } IsAuthorized = false; var client = new HttpClient(); try { var authorizer = new OAuthAuthorizer(ConsumerKey, ConsumerSecret); var tokenResponse = await authorizer.GetRequestToken("http://api.zenmoney.ru/oauth/request_token"); var requestToken = tokenResponse.Token; var pinRequestUrl = authorizer.BuildAuthorizeUrl("http://api.zenmoney.ru/access/", requestToken) + "&mobile"; var authPage = await client.GetStringAsync(pinRequestUrl); var query = new FormUrlEncodedContent(new Collection <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("oauth_callback", "http://grtisenko.biz/zenmoney"), new KeyValuePair <string, string>("login", Login), new KeyValuePair <string, string>("password", Password) }); var request = await client.PostAsync(pinRequestUrl, query); if (request.StatusCode == HttpStatusCode.OK) { var responseStr = await request.Content.ReadAsStringAsync(); //LastErrorMessage = responseStr; throw new UnauthorizedAccessException("Json content: " + responseStr); } var args = HttpUtil.ParseQueryString(request.RequestMessage.RequestUri.ToString()); var verificationCode = Uri.UnescapeDataString(args["oauth_verifier"]); var accessTokenResponse = await authorizer.GetAccessToken("http://api.zenmoney.ru/oauth/access_token", requestToken, verificationCode); _accessToken = accessTokenResponse.Token; IsAuthorized = true; } catch (HttpRequestException httpEx) { LastErrorMessage = "Ошибка подключения к серверу: " + httpEx.Message; Logger.LogException <ZenmoneyClient>(httpEx, "Authorization faild, due http request exception"); } catch (Exception ex) { LastErrorMessage = "Неправильное имя пользователя или пароль"; Logger.LogException <ZenmoneyClient>(ex, "Authorization faild"); } finally { client.Dispose(); } return(IsAuthorized); }
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, }))); }
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, }))); }