// 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; }
/// <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"); } } }
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(); } }
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 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 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 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 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, }))); }
// 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 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 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); }
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 <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); }
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; }
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); }
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); }
// 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))); }
// 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); }
// 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 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)), }); }
/// <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 = "コンピュータの時計が大幅にずれている場合も認証が行えないことがあります。" }))); }
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 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); }
/// <summary> /// GET USER REQUEST URL /// </summary> /// <returns>string</returns> public string UserRequestUrl(RequestToken token) { var authorizer = new OAuthAuthorizer(_consumerKey, _consumerSecret); return(authorizer.BuildAuthorizeUrl("https://oauth.withings.com/account/authorize", token)); }
/**********************************************************************************/ 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); }