public ActionResult AuthorizeCallback(string oauth_token, string oauth_verifier) { TwitterService service = new TwitterService(_consumerKey, _consumerSecret); var requestToken = new OAuthRequestToken {Token = oauth_token}; OAuthAccessToken accessToken = service.GetAccessToken(requestToken, oauth_verifier); service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret); TwitterUser user = service.VerifyCredentials(); ViewModel.Message = string.Format("Your username is {0}", user.ScreenName); return View("Index"); }
public void AuthorizeTwitter_TestAuthorizeReturnsCorretTwitterRedirectResult() { var db = new TestTweetHarborDbContext(); var ts = new Mock <ITweetHarborTwitterService>(); var token = new OAuthRequestToken() { Token = Guid.NewGuid().ToString(), TokenSecret = Guid.NewGuid().ToString() }; ts.Setup(m => m.GetRequestToken("http://localhost:9090/Account/OAuthComplete/?Client=twitter")).Returns(token); ts.Setup(m => m.GetAuthorizationUri(token)).Returns(new Uri("http://twitter.com/OAuth")); var auth = new Mock <IFormsAuthenticationWrapper>(); var c = new AccountController(db, ts.Object, auth.Object); c.SetFakeControllerContext(); var authResponse = c.Authorize("twitter"); Assert.IsInstanceOfType(authResponse, typeof(RedirectResult)); RedirectResult redirRes = (authResponse as RedirectResult); //var data = HttpUtility.ParseQueryString(redirRes.Url.ToString().Substring(redirRes.Url.ToString() .IndexOf('?'))); //Assert.AreNotEqual(0, data.Count, "No query string parameters found"); //Assert.AreNotEqual(0, data["redirect_uri"].Length, "redirect_uri not found in url"); //var data2 = HttpUtility.ParseQueryString(new Uri(data["redirect_uri"]).Query); //Assert.IsTrue(data2.Keys[0].ToLower() == "client"); //Assert.IsTrue(data2["client"].ToLower() == "appharbor"); }
public IHttpActionResult TwitterCallback(string oauth_token, string oauth_verifier) { var requestToken = new OAuthRequestToken { Token = oauth_token }; string Key = "jvy2ZXkqWH6KAPzycTtoMnzgA"; string Secret = "ApD4fROU3DM8tzdfytZFJOkrQfq0H1Ga6i6yOFH0hXpCgbtntR"; try { TwitterService service = new TwitterService(Key, Secret); //get Access tocken OAuthAccessToken accessToken = service.GetAccessToken(requestToken, oauth_verifier); service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret); //for getting user Profile var profile = service.GetUserProfile(new GetUserProfileOptions { IncludeEntities = true }); VerifyCredentialsOptions option = new VerifyCredentialsOptions(); TwitterUser user = service.VerifyCredentials(option); //TempData["Name"] = user.Name; //TempData["Userpic"] = user.ProfileImageUrl; //string u= user.Name; //return Ok(); //return Redirect("http://localhost:4200"+u); return(Redirect("http://localhost:4200")); } catch { throw; } }
public ActionResult TwitterAuth() { OAuthRequestToken requestToken = service.GetRequestToken("http://localhost:14623/Twitter/TwitterCallback"); Uri uri = service.GetAuthenticationUrl(requestToken); return(Redirect(uri.ToString())); }
public IHttpActionResult TwitterCallbackFunc(OAuthData oAuth_Data) { var requestToken = new OAuthRequestToken { Token = oAuth_Data.oauth_token }; string Key = "I4ObconJp84KE97TpZLxmtfOz"; string Secret = "fuYsBswujZu438WDWVNFvGoj45oszq7YfnKjclX7spqxmNdZB9"; try { TwitterService service = new TwitterService(Key, Secret); //Get Access Tokens OAuthAccessToken accessToken = service.GetAccessToken(requestToken, oAuth_Data.oauth_verifier); service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret); VerifyCredentialsOptions option = new VerifyCredentialsOptions(); //According to Access Tokens get user profile details TwitterUser user = service.VerifyCredentials(option); //return View(); //return RedirectToAction("Index", "Home"); //Redirect("~/Index.html"); return(Ok(user)); } catch { throw; } }
public bool FlickrAuthenticate() { Logger.Debug("Authenticating..."); if (OAuthToken?.Token == null) { ConsoleHelper.WriteInfoLine("Requesting access token..."); var flickr = GetInstance(); OAuthRequestToken requestToken = flickr.OAuthGetRequestToken("oob"); var url = flickr.OAuthCalculateAuthorizationUrl(requestToken.Token, AuthLevel.Write); Process.Start(url); ConsoleHelper.WriteInfo("Verifier: "); var verifier = Console.ReadLine(); OAuthToken = flickr.OAuthGetAccessToken(requestToken, verifier); } if (OAuthToken == null) { Logger.Error("Could not authenticate."); return(true); } Logger.Info("Authenticated as " + OAuthToken.FullName + "."); Uploader.UserId = OAuthToken.UserId; Uploader.Flickr = GetAuthInstance(); return(false); }
public Uri GetRequestURI() { OAuthRequestToken requestToken = twitter.GetRequestToken(callbackURL); Uri uri = twitter.GetAuthorizationUri(requestToken); return(uri); }
// This URL is registered as the application's callback under Twitter's DEV API public ActionResult TwitterSignInCallback(string oauth_token, string oauth_verifier) { var requestToken = new OAuthRequestToken { Token = oauth_token }; // Exchange the Request Token for an Access Token TwitterService twitterService = new TwitterService(OAuthAPIKey, OAuthAPISecret); OAuthAccessToken accessToken = twitterService.GetAccessToken(requestToken, oauth_verifier); // User authenticates using the Access Token twitterService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret); TwitterUser user = twitterService.VerifyCredentials(new VerifyCredentialsOptions() { }); bool successfulLogin = user != null; FormsAuthentication.SetAuthCookie(user.ScreenName, false); if (successfulLogin) { return(RedirectToAction("Index", "Home", new { userName = user.ScreenName })); } return(RedirectToAction("Index", "Home")); }
/// <summary> /// Authenticate with twitter to get a token /// </summary> public static void Authenticate() { // STEP 1 of authentication Flickr f = FlickrManager.GetInstance(); OAuthRequestToken requestToken = f.OAuthGetRequestToken("oob"); string url = f.OAuthCalculateAuthorizationUrl(requestToken.Token, AuthLevel.Write); System.Diagnostics.Process.Start(url); // STEP 2 of authentication Console.WriteLine("Enter the verifier code"); string verifierCode = Console.ReadLine(); Flickr f1 = FlickrManager.GetInstance(); try { var accessToken = f1.OAuthGetAccessToken(requestToken, verifierCode); FlickrManager.OAuthToken = accessToken; } catch (FlickrApiException ex) { throw; } Trace.WriteLine("Authentication with twitter is complete"); }
public void PreAuthorization() { requestToken = service.GetRequestToken(); Uri uri = service.GetAuthorizationUri(requestToken); Process.Start(uri.ToString()); }
public void AskToken() { requestToken = flickr.OAuthGetRequestToken("oob"); string url = flickr.OAuthCalculateAuthorizationUrl(requestToken.Token, AuthLevel.Write); System.Diagnostics.Process.Start(url); }
public LoginProfile ProcessAuthoriztion(HttpContext context, IDictionary <string, string> @params) { var twitterService = new TwitterService(KeyStorage.Get("twitterKey"), KeyStorage.Get("twitterSecret")); if (String.IsNullOrEmpty(context.Request["oauth_token"]) || String.IsNullOrEmpty(context.Request["oauth_verifier"])) { var requestToken = twitterService.GetRequestToken(context.Request.Url.AbsoluteUri); var uri = twitterService.GetAuthorizationUri(requestToken); context.Response.Redirect(uri.ToString(), true); } else { var requestToken = new OAuthRequestToken { Token = context.Request["oauth_token"] }; var accessToken = twitterService.GetAccessToken(requestToken, context.Request["oauth_verifier"]); twitterService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret); var user = twitterService.VerifyCredentials(new VerifyCredentialsOptions()); return(ProfileFromTwitter(user)); } return(new LoginProfile()); }
public string GetAuthorizationUrl() { OAuthRequestToken requestToken = twitterService.GetRequestToken(TwitterRedirect_uri); var uri = twitterService.GetAuthenticationUrl(requestToken); return(uri.AbsoluteUri); }
public void TryLogin() { if (LoggedIn) { RaiseLoginCompleted(true); return; } OAuthRequestToken token = Service.GetRequestToken(); Uri uri = Service.GetAuthorizationUri(token); _pinObtainer.GetPin(uri.AbsoluteUri); _pinObtainer.PinCodeObtained += (sender, e) => { var loginResult = TryLoginImpl(e.PinCode, token); if (loginResult) { LoggedIn = true; TrySerialize(_serializationFilePath); RaiseLoginCompleted(new OperationResultEventArgs(true, null)); } else { RaiseLoginCompleted(new OperationResultEventArgs(false, new Exception(message: "Login Failed"))); } }; }
public FlickrService() { FlickrNet = new Flickr("5cc521a6a8599edbd471fa9c59c30260", "13fdeeb5eb5539d8"); var localSettings = ApplicationData.Current.LocalSettings; var accessToken = localSettings.Values["accessToken"]; if (accessToken != null) { FlickrNet.OAuthAccessToken = accessToken.ToString(); } var tokenSecret = localSettings.Values["tokenSecret"]; if (tokenSecret != null) { FlickrNet.OAuthAccessTokenSecret = tokenSecret.ToString(); } var requestTokens = localSettings.Values["requestToken"]; if (requestTokens != null) { var oAuthRequestToken = requestTokens.ToString().Split('|'); requestToken = new OAuthRequestToken { Token = oAuthRequestToken[0], TokenSecret = oAuthRequestToken[1] }; } }
public ActionResult Authorize() { // Step 1 - Retrieve an OAuth Request Token TwitterService service = new TwitterService(_consumerKey, _consumerSecret); // This is the registered callback URL OAuthRequestToken requestToken = service.GetRequestToken("http://localhost:37276/Manage/AuthorizeCallback"); // Step 2 - Redirect to the OAuth Authorization URL Uri uri = service.GetAuthenticationUrl(requestToken); var db = HttpContext.GetOwinContext().Get <ApplicationDbContext>(); // find the user. I am skipping validations and other checks. var userid = User.Identity.GetUserId(); var user = db.Users.Where(x => x.Id == userid).FirstOrDefault(); user.twitter_connect = true; // save changes to database db.SaveChanges(); return(Redirect(uri.ToString())); }
public ActionResult TwitterCallback(string oauth_token, string oauth_verifier) { var requestToken = new OAuthRequestToken { Token = oauth_token }; string key = "W7nisP4ZK14FeeTu5sn5Q9z3c"; string secret = "F2kQSgBgFceir7B3UD0RODZSOvi7QDUdyU1quHh664cbxXhB9T"; try { TwitterService service = new TwitterService(key, secret); OAuthAccessToken accessToken = service.GetAccessToken(requestToken, oauth_verifier); service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret); VerifyCredentialsOptions option = new VerifyCredentialsOptions(); TwitterUser user = service.VerifyCredentials(option); TempData["Name"] = user.Name; TempData["userpic"] = user.ProfileImageUrl; return(View()); } catch (System.Exception) { throw; } }
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { Flickr f = FlickrManager.GetInstance(); // obtain the request token from Flickr f.OAuthGetRequestTokenAsync(callbackUrl, r => { // Check if an error was returned if (r.Error != null) { Dispatcher.BeginInvoke(() => { MessageBox.Show("An error occurred getting the request token: " + r.Error.Message); }); return; } // Get the request token requestToken = r.Result; // get Authorization url string url = f.OAuthCalculateAuthorizationUrl(requestToken.Token, AuthLevel.Write); // Replace www.flickr.com with m.flickr.com for mobile version // url = url.Replace("https://www.flickr.com", "http://www.flickr.com"); // Navigate to url Dispatcher.BeginInvoke(() => { WebBrowser1.Navigate(new Uri(url)); }); }); }
/// <summary> /// Load page with query string of Flickr and get logged user /// </summary> protected void Page_Load(object sender, EventArgs e) { try { // Verify if query string contains authentication values if (Request.QueryString["oauth_verifier"] != null && Session["RequestToken"] != null) { Flickr flickr = FlickrManager.GetInstance(); OAuthRequestToken requestToken = Session["RequestToken"] as OAuthRequestToken; try { OAuthAccessToken accessToken = flickr.OAuthGetAccessToken(requestToken, Request.QueryString["oauth_verifier"]); FlickrManager.OAuthToken = accessToken; } catch (OAuthException) { Debug.Write("[ERROR] - Error to get Flickr access token."); } } // Verify if not post back if (!Page.IsPostBack) { SetLogged(); } } catch (System.Exception) { ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "alert", "alert('Ocorreu um erro ao carregar as fotos.');", true); } }
public ActionResult Authorize() { refresh2 = UserToken.flag2; refresh2++; UserToken.flag2 = refresh2; // Step 1 - Retrieve an OAuth Request Token //var temp= FacebookProfileViewModel.iflogedTwitter; // temp++; // FacebookProfileViewModel.iflogedTwitter = temp; TwitterService service = new TwitterService(_consumerKey, _consumerSecret); // This is the registered callback URL OAuthRequestToken requestToken = service.GetRequestToken("http://localhost:37276/Facebook/Index"); // Step 2 - Redirect to the OAuth Authorization URL Uri uri = service.GetAuthenticationUrl(requestToken); var db = HttpContext.GetOwinContext().Get <ApplicationDbContext>(); // find the user. I am skipping validations and other checks. var userid = User.Identity.GetUserId(); var user = db.Users.Where(x => x.Id == userid).FirstOrDefault(); user.twitter_connect = true; // save changes to database db.SaveChanges(); return(JavaScript("window.location = '" + uri.ToString() + "'")); //return Redirect(uri.ToString()); }
public void ProcessRequest(HttpContext context) { //get parameters string oauth_token = context.Request.Params["oauth_token"]; string oauth_verifier = context.Request.Params["oauth_verifier"]; var requestToken = new OAuthRequestToken { Token = oauth_token }; // Step 3 - Exchange the Request Token for an Access Token Global.TwitterService = new TwitterService(Global.TwitterConsumerKey, Global.TwitterConsumerSecret); OAuthAccessToken accessToken = Global.TwitterService.GetAccessToken(requestToken, oauth_verifier); // Step 4 - User authenticates using the Access Token Global.TwitterService.AuthenticateWith(accessToken.Token, accessToken.TokenSecret); TwitterUser user = Global.TwitterService.VerifyCredentials(new VerifyCredentialsOptions()); //var sessionProps = (SessionProperties) context.Session["sessionProps"]; //sessionProps.TwitterAccessToken = accessToken.Token; //sessionProps.TwitterAccessTokenSecret = accessToken.TokenSecret; Parameters.Instance.TwitterAccessToken = accessToken.Token; Parameters.Instance.TwitterAccessTokenSecret = accessToken.TokenSecret; //service.SendTweet(new SendTweetOptions(){Status = "Testing twitter function. Carrry on"}); context.Response.Redirect("../AdminMain.aspx"); }
private async Task ListenForToken(OAuthRequestToken requestToken) { HttpListener listener = new HttpListener(); listener.Prefixes.Add(Constants.LOCAL_HOST_ADDRESS); listener.Start(); string oauthToken = ""; string oauthVerifier = ""; while (true) { var context = listener.GetContext(); oauthToken = context.Request.QueryString.Get("oauth_token"); oauthVerifier = context.Request.QueryString.Get("oauth_verifier"); Debug.WriteLine(oauthToken, oauthVerifier); if (!string.IsNullOrEmpty(oauthToken) && !string.IsNullOrEmpty(oauthVerifier)) { //form response var outputStream = context.Response.OutputStream; string responseString = "<html><body><h2>Access granted</h2></body></html>"; var bytes = Encoding.UTF8.GetBytes(responseString); context.Response.ContentLength64 = bytes.Length; outputStream.Write(bytes, 0, bytes.Length); outputStream.Close(); break; } } var access = FlickrInstance.OAuthGetAccessToken(requestToken, oauthVerifier); Settings.Default.Username = access.Username; SaveLoginToken(access.Token, access.TokenSecret); return; }
public string GetAuthorizationUrl() { requestToken = Flickr.OAuthGetRequestToken("oob"); string url = Flickr.OAuthCalculateAuthorizationUrl(requestToken.Token, AuthLevel.Delete); return(url); }
protected void Page_Load(object sender, EventArgs e) { // The request token is stored in session - if it isn't present then we do nothing if (Request.QueryString["oauth_verifier"] != null && Session["RequestToken"] != null) { Flickr f = FlickrManager.GetInstance(); OAuthRequestToken requestToken = Session["RequestToken"] as OAuthRequestToken; try { OAuthAccessToken accessToken = f.OAuthGetAccessToken(requestToken, Request.QueryString["oauth_verifier"]); FlickrManager.OAuthToken = accessToken; ResultsLabel.Text = "You successfully authenticated as " + accessToken.FullName; ResultPanel.CssClass = "alert alert-success"; ResultPanel.Visible = true; } catch (OAuthException ex) { ResultsLabel.Text = "An error occurred retrieving the token : " + ex.Message; ResultPanel.CssClass = "alert alert-danger"; ResultPanel.Visible = true; } } }
/// <summary> /// Logs into Twitter, using OAuth. The user will need to copy/paste the Twitter auth code back into the console program. /// </summary> /// <returns>TwitterService</returns> private static TwitterService LoginTwitter() { // Pass your credentials to the service TwitterService service = new TwitterService(_consumerKey, _consumerSecret); // Step 1 - Retrieve an OAuth Request Token OAuthRequestToken requestToken = service.GetRequestToken(); // Step 2 - Redirect to the OAuth Authorization URL Uri uri = service.GetAuthorizationUri(requestToken); Process.Start(uri.ToString()); Console.Write("Enter Twitter auth key: "); string key = Console.ReadLine(); // Step 3 - Exchange the Request Token for an Access Token string verifier = key; // <-- This is input into your application by your user OAuthAccessToken access = service.GetAccessToken(requestToken, verifier); // Step 4 - User authenticates using the Access Token service.AuthenticateWith(access.Token, access.TokenSecret); return(service); }
private void CreateNewRequestToken() { var service = new TwitterService(ClientInfo); UnauthorizedToken = service.GetRequestToken(); AuthenticationUrl = service.GetAuthorizationUri(UnauthorizedToken); }
/// <summary> /// Begin login process. /// </summary> private void btnLogin_Click(object sender, RoutedEventArgs e) { // Try to see if the user has already logged in try { // Look for the file containing previous tokens XmlDocument doc = new XmlDocument(); doc.Load(ConfigurationManager.AppSettings["LoginDataFile"]); XmlNode root = doc.LastChild; string token = root.FirstChild.InnerText; string tokenSecret = root.LastChild.InnerText; service.AuthenticateWith(token, tokenSecret); MoveToMain(); } // Login file not found so begin online authorization via browser. // Login process continues by inputing the pin recived later. catch (FileNotFoundException ex) { // Step 1 - Retrieve an OAuth Request Token requestToken = service.GetRequestToken(); // Step 2 - Redirect to the OAuth Authorization URL Uri uri = service.GetAuthorizationUri(requestToken); Process.Start(uri.ToString()); spPin.Visibility = Visibility.Visible; btnLogin.IsEnabled = false; } // Something went wrong catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// 4. Twitter redirects back to this action where we finish creating the user /// </summary> public ActionResult AuthorizeCallback(string oauth_token, string oauth_verifier) { var requestToken = new OAuthRequestToken { Token = oauth_token }; var service = twitterFactory.Create(); var accessToken = service.GetAccessToken(requestToken, oauth_verifier); service.AuthenticateWith(accessToken.Token, accessToken.TokenSecret); var twitterUser = service.VerifyCredentials(); if (twitterUser == null) { return(HttpNotFound("Dude, Twitter has no idea who you are.")); } var user = userRepository.GetByTwitterId(twitterUser.Id) ?? context.User; if (user == null) { return(HttpNotFound("I'm sorry, I don't remember seeing you before. Have we met?")); } user.AuthData = new TwitterAuthData { Secret = accessToken.TokenSecret, Token = accessToken.Token, TwitterId = twitterUser.Id }; user.TwitterHandles.Add(twitterUser.ScreenName); userRepository.Save(user); return(RedirectToAction("Index")); }
public void InteractiveAuthorize() { var f = Surrogate; var requestToken = _reqToken = f.OAuthGetRequestToken("oob"); var url = f.OAuthCalculateAuthorizationUrl(requestToken.Token, AuthLevel.Write); Process.Start(url); }
/// <summary> /// constuctor that authorizes /// should go in the order of constuctor, authorize /// </summary> public Twit() { twitter = new TwitterService(info.ConsumerKey, info.ConsumerSecret); req = twitter.GetRequestToken(); string u = twitter.GetAuthenticationUrl(req).ToString(); Process.Start(u); }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); _twitterService = new TwitterService(Constants.ConsumerKey, Constants.ConsumerSecret); _requestToken = _twitterService.GetRequestToken(); _url = _twitterService.GetAuthorizationUri(_requestToken).ToString(); }
protected virtual void HandleAuthenticationRequestToken(OAuthRequestToken token, TwitterResponse response) { _requestToken = token; // Save the token while(!_browserLoaded) { Thread.Sleep(200); } Dispatcher.BeginInvoke( () => _browser.Navigate(_service.GetAuthorizationUri(_requestToken)) ); }
private void AuthorizeDesktopBtn_Click(object sender, RoutedEventArgs e) { // Step 1 - Retrieve an OAuth Request Token _requestToken = _service.GetRequestToken(); // Step 2 - Redirect to the OAuth Authorization URL Uri uri = _service.GetAuthorizationUri(_requestToken); Process.Start(uri.ToString()); AuthorizeDesktopBtn.IsEnabled = false; pinTextBox.Visibility = Visibility.Visible; pinLbl.Visibility = Visibility.Visible; pinInstruction.Visibility = Visibility.Visible; }
public string GetAuthUrl(OAuthRequestToken token) { return _flickr.OAuthCalculateAuthorizationUrl(token.Token, AuthLevel.Read); }
public void SetAuthCode(OAuthRequestToken token, string code) { var accessToken = _flickr.OAuthGetAccessToken(token.Token, token.TokenSecret, code); _flickr.OAuthAccessToken = accessToken.Token; _flickr.OAuthAccessTokenSecret = accessToken.TokenSecret; }