twitter4j.auth.RequestToken Java Examples
The following examples show how to use
twitter4j.auth.RequestToken.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GetAccessTokenTask.java From Tweetin with Apache License 2.0 | 6 votes |
@Override protected Boolean doInBackground(Void... params) { String consumerKey = mainActivity.getString(R.string.app_consumer_key); String consumerSecret = mainActivity.getString(R.string.app_consumer_secret); Twitter twitter = TwitterUnit.getTwitterFromInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); try { String token = sharedPreferences.getString(mainActivity.getString(R.string.sp_request_token), null); String tokenSecret = sharedPreferences.getString(mainActivity.getString(R.string.sp_request_token_secret), null); RequestToken requestToken = new RequestToken(token, tokenSecret); accessToken = twitter.getOAuthAccessToken(requestToken, oAuthVerifier); useScreenName = twitter.verifyCredentials().getScreenName(); } catch (Exception e) { return false; } if (isCancelled()) { return false; } return true; }
Example #2
Source File: TwitterAuth.java From liberty-bikes with Eclipse Public License 1.0 | 6 votes |
@GET public Response getTwitterAuthURL(@Context HttpServletRequest request) { ConfigurationBuilder c = new ConfigurationBuilder() .setOAuthConsumerKey(config.twitter_key) .setOAuthConsumerSecret(config.twitter_secret); Twitter twitter = new TwitterFactory(c.build()).getInstance(); request.getSession().setAttribute("twitter", twitter); try { String callbackURL = config.authUrl + "/TwitterCallback"; RequestToken token = twitter.getOAuthRequestToken(callbackURL); request.getSession().setAttribute("twitter_token", token); // send the user to Twitter to be authenticated String authorizationUrl = token.getAuthenticationURL(); return Response.temporaryRedirect(new URI(authorizationUrl)).build(); } catch (Exception e) { e.printStackTrace(); return Response.status(500).build(); } }
Example #3
Source File: GetAuthorizationURLTask.java From Tweetin with Apache License 2.0 | 6 votes |
@Override protected Boolean doInBackground(Void... params) { String consumerKey = splashActivity.getString(R.string.app_consumer_key); String consumerSecret = splashActivity.getString(R.string.app_consumer_secret); Twitter twitter = TwitterUnit.getTwitterFromInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); try { RequestToken requestToken = twitter.getOAuthRequestToken(splashActivity.getString(R.string.app_callback_url)); token = requestToken.getToken(); tokenSecret = requestToken.getTokenSecret(); authorizationURL = requestToken.getAuthorizationURL(); } catch (Exception e) { return false; } if (isCancelled()) { return false; } return true; }
Example #4
Source File: AccessTokenGenerator.java From api-mining with GNU General Public License v3.0 | 6 votes |
/** * Interactive {@link AccessToken} generation. * * @param args No args are required. * @throws Exception If the token cannot be generated. */ public static void main(final String... args) throws Exception { Twitter twitter = new TwitterFactory().getInstance(); RequestToken requestToken = twitter.getOAuthRequestToken(); // Ask for the PIN BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); AccessToken accessToken = null; System.out.print("Open the following URL and grant access to your account: "); System.out.println(requestToken.getAuthorizationURL()); System.out.print("Enter the PIN: "); accessToken = twitter.getOAuthAccessToken(requestToken, br.readLine()); System.out.println("AccessToken Key: " + accessToken.getToken()); System.out.println("AccessToken Secret: " + accessToken.getTokenSecret()); twitter.shutdown(); }
Example #5
Source File: TwitterIdentityProvider.java From keycloak with Apache License 2.0 | 6 votes |
@Override public Response performLogin(AuthenticationRequest request) { try (VaultStringSecret vaultStringSecret = session.vault().getStringSecret(getConfig().getClientSecret())) { Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(getConfig().getClientId(), vaultStringSecret.get().orElse(getConfig().getClientSecret())); URI uri = new URI(request.getRedirectUri() + "?state=" + request.getState().getEncoded()); RequestToken requestToken = twitter.getOAuthRequestToken(uri.toString()); AuthenticationSessionModel authSession = request.getAuthenticationSession(); authSession.setAuthNote(TWITTER_TOKEN, requestToken.getToken()); authSession.setAuthNote(TWITTER_TOKENSECRET, requestToken.getTokenSecret()); URI authenticationUrl = URI.create(requestToken.getAuthenticationURL()); return Response.seeOther(authenticationUrl).build(); } catch (Exception e) { throw new IdentityBrokerException("Could send authentication request to twitter.", e); } }
Example #6
Source File: MainController.java From WTFDYUM with Apache License 2.0 | 6 votes |
@RequestMapping(value = "/signin", method = RequestMethod.GET) public RedirectView signin(final HttpServletRequest request) throws WTFDYUMException { if (authenticationService.isAuthenticated()) { return new RedirectView("/user", true); } if (maxMembers > 0 && principalService.countMembers() >= maxMembers) { throw new WTFDYUMException(WTFDYUMExceptionType.MEMBER_LIMIT_EXCEEDED); } final RequestToken requestToken = twitterService.signin("/signin/callback"); request.getSession().setAttribute(SESSION_REQUEST_TOKEN, requestToken); return new RedirectView(requestToken.getAuthenticationURL()); }
Example #7
Source File: MainController.java From WTFDYUM with Apache License 2.0 | 6 votes |
@RequestMapping(value = "/signin/callback", method = RequestMethod.GET) public RedirectView signinCallback(@RequestParam("oauth_verifier") final String verifier, final HttpServletRequest request) throws WTFDYUMException { final RequestToken requestToken = (RequestToken) request.getSession().getAttribute(SESSION_REQUEST_TOKEN); request.getSession().removeAttribute(SESSION_REQUEST_TOKEN); final AccessToken accessToken = twitterService.completeSignin(requestToken, verifier); if (principalService.get(accessToken.getUserId()) == null) { userService.addEvent(accessToken.getUserId(), new Event(EventType.REGISTRATION, null)); } final Principal user = new Principal(accessToken.getUserId(), accessToken.getToken(), accessToken.getTokenSecret()); principalService.saveUpdate(user); authenticationService.authenticate(user); return new RedirectView("/user", true); }
Example #8
Source File: TwitterSession.java From vocefiscal-android with Apache License 2.0 | 6 votes |
/** * Stores the session data on disk. * * @param context * @return */ public boolean saveRequest(Context context, RequestToken requestToken, Twitter t) { twitter = t; Editor editor = context.getSharedPreferences(KEY, Context.MODE_PRIVATE).edit(); rtoken = requestToken.getToken(); rtokensecret =requestToken.getTokenSecret(); editor.putString(R_TOKEN,rtoken); editor.putString(R_TOKENSECRET, rtokensecret); if (editor.commit()) { singleton = this; return true; } return false; }
Example #9
Source File: TwitterOAuthActivity.java From firebase-login-demo-android with MIT License | 6 votes |
private void getTwitterOAuthTokenAndLogin(final RequestToken requestToken, final String oauthVerifier) { // once a user authorizes the application, get the auth token and return to the MainActivity new AsyncTask<Void, Void, AccessToken>() { @Override protected AccessToken doInBackground(Void... params) { AccessToken accessToken = null; try { accessToken = mTwitter.getOAuthAccessToken(requestToken, oauthVerifier); } catch (TwitterException te) { Log.e(TAG, te.toString()); } return accessToken; } @Override protected void onPostExecute(AccessToken token) { Intent resultIntent = new Intent(); resultIntent.putExtra("oauth_token", token.getToken()); resultIntent.putExtra("oauth_token_secret", token.getTokenSecret()); resultIntent.putExtra("user_id", token.getUserId() + ""); setResult(MainActivity.RC_TWITTER_LOGIN, resultIntent); finish(); } }.execute(); }
Example #10
Source File: SigninServlet.java From TwitterBoost-Tools with MIT License | 5 votes |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // configure twitter api with consumer key and secret key ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true) .setOAuthConsumerKey(Setup.CONSUMER_KEY) .setOAuthConsumerSecret(Setup.CONSUMER_SECRET); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); request.getSession().setAttribute("twitter", twitter); try { // setup callback URL StringBuffer callbackURL = request.getRequestURL(); int index = callbackURL.lastIndexOf("/"); callbackURL.replace(index, callbackURL.length(), "").append("/callback"); // get request object and save to session RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString()); request.getSession().setAttribute("requestToken", requestToken); // redirect to twitter authentication URL response.sendRedirect(requestToken.getAuthenticationURL()); } catch (TwitterException e) { throw new ServletException(e); } }
Example #11
Source File: TwitterServiceTest.java From WTFDYUM with Apache License 2.0 | 5 votes |
@Test(expected = WTFDYUMException.class) public void completeSigninTestTwitterException() throws Exception { final RequestToken paramToken = new RequestToken("TOK", "SECRET_tok"); final String verifier = "VERiFy"; when(twitter.getOAuthAccessToken(paramToken, verifier)).thenThrow(new TwitterException("dummy")); sut.completeSignin(paramToken, verifier); Assertions.fail("Exception not throwned"); }
Example #12
Source File: RequestTokenTask.java From SmileEssence with MIT License | 5 votes |
@Override protected RequestToken doInBackground(Void... params) { try { return twitter.getOAuthRequestToken(); } catch (TwitterException e) { e.printStackTrace(); Logger.error(e.toString()); return null; } }
Example #13
Source File: Twitter4jSampleActivity.java From android-opensource-library-56 with Apache License 2.0 | 5 votes |
private void startOAuth() { new Thread() { public void run() { ConfigurationBuilder cbuilder = new ConfigurationBuilder(); cbuilder.setOAuthConsumerKey(Settings.CONSUMER_KEY); cbuilder.setOAuthConsumerSecret(Settings.CONSUMER_SECRET); Configuration conf = cbuilder.build(); mOauth = new OAuthAuthorization(conf); String authUrl = null; try { RequestToken requestToken = mOauth .getOAuthRequestToken(null); authUrl = requestToken.getAuthorizationURL(); } catch (Exception e) { e.printStackTrace(); return; } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); }; }.start(); setContentView(R.layout.login); findViewById(R.id.login).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // ピンコード処理を書く EditText editText = (EditText) findViewById(R.id.pincode); getOAuthAccessToken(editText.getText().toString()); } }); }
Example #14
Source File: TwitterOauthWizard.java From Onosendai with Apache License 2.0 | 5 votes |
@Override protected Result<RequestToken> doInBackground (final Void... params) { try { return new Result<RequestToken>(this.host.getTwitter(this.requestCode).getOAuthRequestToken(TwitterOauth.CALLBACK_URL)); } catch (final Exception e) { // NOSONAR report all errors to user. return new Result<RequestToken>(e); } }
Example #15
Source File: TwitterOauthWizard.java From Onosendai with Apache License 2.0 | 5 votes |
@Override protected void onPostExecute (final Result<RequestToken> result) { this.dialog.dismiss(); if (result.isSuccess()) { final Intent intent = new Intent(this.host.getContext(), TwitterLoginActivity.class); final RequestToken requtestToken = result.getData(); this.host.stashRequestToken(requtestToken); intent.putExtra(TwitterOauth.IEXTRA_AUTH_URL, requtestToken.getAuthorizationURL()); this.host.getHelperCallback().deligateStartActivityForResult(intent, this.requestCode); } else { getLog().e("Failed to init OAuth.", result.getE()); DialogHelper.alert(this.host.getContext(), result.getE()); } }
Example #16
Source File: TwitterOauthWizard.java From Onosendai with Apache License 2.0 | 5 votes |
@Override protected Result<AccessToken> doInBackground (final Void... params) { try { final RequestToken token = this.host.unstashRequestToken(); return new Result<AccessToken>(this.host.getTwitter(this.requestCode).getOAuthAccessToken(token, this.oauthVerifier)); } catch (final Exception e) { // NOSONAR report all errors to user. return new Result<AccessToken>(e); } }
Example #17
Source File: TwitterLogin.java From timbuctoo with GNU General Public License v3.0 | 5 votes |
@GET public Response login() throws TwitterException { RequestToken requestToken = twitter.getOAuthRequestToken(); tokenSecrets.put(requestToken.getToken(), requestToken); return Response.temporaryRedirect(URI.create(requestToken.getAuthorizationURL())).build(); }
Example #18
Source File: MainControllerTest.java From WTFDYUM with Apache License 2.0 | 5 votes |
@Test public void signinTest() throws Exception { final RequestToken returnedRequestToken = new RequestToken("my_super_token", ""); when(twitterService.signin(anyString())).thenReturn(returnedRequestToken); mockMvc .perform(get("/signin")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrlPattern("http*://**/**my_super_token")); }
Example #19
Source File: MainControllerTest.java From WTFDYUM with Apache License 2.0 | 5 votes |
@Test public void signinCallbackTest() throws Exception { final RequestToken returnedRequestToken = new RequestToken("my_super_token", ""); when(twitterService.signin(anyString())).thenReturn(returnedRequestToken); when(principalService.get(1203L)).thenReturn(null); final HttpSession session = mockMvc .perform(get("/signin")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrlPattern("http*://**/**my_super_token")) .andReturn() .getRequest() .getSession(); assertThat(session).isNotNull(); assertThat(session.getAttribute(MainController.SESSION_REQUEST_TOKEN)).isNotNull(); assertThat(session.getAttribute(MainController.SESSION_REQUEST_TOKEN)).isEqualTo(returnedRequestToken); final AccessToken returnedAccessToken = new AccessToken("TOken", "secret"); ReflectionTestUtils.setField(returnedAccessToken, "userId", 1203L); when(twitterService.completeSignin(returnedRequestToken, "42")).thenReturn(returnedAccessToken); mockMvc .perform(get("/signin/callback?oauth_verifier=42").session((MockHttpSession) session)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/user")); final Principal builtUser = new Principal(1203L, "TOken", "secret"); verify(userService, times(1)).addEvent(1203L, new Event(EventType.REGISTRATION, null)); verify(principalService, times(1)).saveUpdate(builtUser); verify(authenticationService, times(1)).authenticate(builtUser); }
Example #20
Source File: TwitterServiceImpl.java From WTFDYUM with Apache License 2.0 | 5 votes |
@Override public RequestToken signin(final String path) throws WTFDYUMException { RequestToken token = null; try { token = twitter().getOAuthRequestToken(new StringBuilder(baseUrl).append(path).toString()); } catch (final TwitterException e) { log.debug("Error while signin", e); throw new WTFDYUMException(e, WTFDYUMExceptionType.TWITTER_ERROR); } return token; }
Example #21
Source File: TwitterServiceImpl.java From WTFDYUM with Apache License 2.0 | 5 votes |
@Override public AccessToken completeSignin(final RequestToken requestToken, final String verifier) throws WTFDYUMException { AccessToken token = null; try { token = twitter().getOAuthAccessToken(requestToken, verifier); } catch (final TwitterException e) { log.debug("Error while completeSignin", e); throw new WTFDYUMException(e, WTFDYUMExceptionType.TWITTER_ERROR); } return token; }
Example #22
Source File: CallbackServlet.java From TwitterBoost-Tools with MIT License | 5 votes |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get twitter object from session Twitter twitter = (Twitter) request.getSession().getAttribute("twitter"); //Get twitter request token object from session RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken"); String verifier = request.getParameter("oauth_verifier"); try { // Get twitter access token object by verifying request token AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); request.getSession().removeAttribute("requestToken"); // Get user object from database with twitter user id UserPojo user = TwitterDAO.selectTwitterUser(accessToken.getUserId()); if(user == null) { // if user is null, create new user with given twitter details user = new UserPojo(); user.setTwitter_user_id(accessToken.getUserId()); user.setTwitter_screen_name(accessToken.getScreenName()); user.setAccess_token(accessToken.getToken()); user.setAccess_token_secret(accessToken.getTokenSecret()); TwitterDAO.insertRow(user); user = TwitterDAO.selectTwitterUser(accessToken.getUserId()); } else { // if user already there in database, update access token user.setAccess_token(accessToken.getToken()); user.setAccess_token_secret(accessToken.getTokenSecret()); TwitterDAO.updateAccessToken(user); } request.setAttribute("user", user); } catch (TwitterException | DBException e) { throw new ServletException(e); } request.getRequestDispatcher("/index2.html").forward(request, response); }
Example #23
Source File: Twitter.java From BotLibre with Eclipse Public License 1.0 | 5 votes |
/** * Authorise a new account to be accessible by Bot. * Return the request token that contains the URL that the user must use to authorise twitter. */ public RequestToken authorizeAccount() throws TwitterException { twitter4j.Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(getOauthKey(), getOauthSecret()); RequestToken requestToken = twitter.getOAuthRequestToken(); setConnection(twitter); return requestToken; }
Example #24
Source File: TwitterNotifier.java From yfiton with Apache License 2.0 | 5 votes |
public RequestToken getRequestToken() throws NotificationException { if (requestToken == null) { try { requestToken = twitter.getOAuthRequestToken(); } catch (TwitterException e) { throw new NotificationException(e); } } return requestToken; }
Example #25
Source File: TwitterNotifier.java From yfiton with Apache License 2.0 | 5 votes |
public RequestToken getRequestToken() throws NotificationException { if (requestToken == null) { try { requestToken = twitter.getOAuthRequestToken(); } catch (TwitterException e) { throw new NotificationException(e); } } return requestToken; }
Example #26
Source File: TwitterServiceTest.java From WTFDYUM with Apache License 2.0 | 4 votes |
@Test public void completeSigninTestNominal() throws Exception { final AccessToken returnedToken = new AccessToken("TOKTOK", "TOK_secret"); final RequestToken paramToken = new RequestToken("TOK", "SECRET_tok"); final String verifier = "VERiFy"; when(twitter.getOAuthAccessToken(paramToken, verifier)).thenReturn(returnedToken); final AccessToken accessToken = sut.completeSignin(paramToken, verifier); verify(twitter, times(1)).getOAuthAccessToken(paramToken, verifier); assertThat(accessToken).isNotNull(); assertThat(accessToken).isEqualTo(returnedToken); }
Example #27
Source File: AccessTokenTask.java From SmileEssence with MIT License | 4 votes |
public AccessTokenTask(Twitter twitter, RequestToken requestToken, String pinCode) { super(twitter); this.requestToken = requestToken; this.pinCode = pinCode; }
Example #28
Source File: FiscalizacaoConcluidaActivity.java From vocefiscal-android with Apache License 2.0 | 4 votes |
public boolean startTwitterLogin(final String callbackURL) { Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer (CommunicationConstants.TWITTER_API_KEY, CommunicationConstants.TWITTER_API_SECRET); boolean ok = true; try { RequestToken rToken = twitter.getOAuthRequestToken(callbackURL); TwitterSession twitterSession = new TwitterSession(); twitterSession.saveRequest(FiscalizacaoConcluidaActivity.this, rToken,twitter); Intent twitterIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(rToken.getAuthenticationURL()+"&force_login=true")); startActivity(twitterIntent); handler.postDelayed(new Runnable() { @Override public void run() { FiscalizacaoConcluidaActivity.this.finish(); } }, 2000); } catch (TwitterException e) { ok = false; if(e!=null&&e.getStatusCode()!=403) { handler.post(new Runnable() { @Override public void run() { Toast.makeText(FiscalizacaoConcluidaActivity.this,"Não foi possível twittar!",Toast.LENGTH_SHORT).show(); } }); } } return ok; }
Example #29
Source File: Twitter.java From appinventor-extensions with Apache License 2.0 | 4 votes |
/** * Authenticate to Twitter using OAuth * @suppressdoc */ @SimpleFunction(description = "Redirects user to login to Twitter via the Web browser using " + "the OAuth protocol if we don't already have authorization.") public void Authorize() { if (consumerKey.length() == 0 || consumerSecret.length() == 0) { form.dispatchErrorOccurredEvent(this, "Authorize", ErrorMessages.ERROR_TWITTER_BLANK_CONSUMER_KEY_OR_SECRET); return; } if (twitter == null) { twitter = new TwitterFactory().getInstance(); } final String myConsumerKey = consumerKey; final String myConsumerSecret = consumerSecret; AsynchUtil.runAsynchronously(new Runnable() { public void run() { if (checkAccessToken(myConsumerKey, myConsumerSecret)) { handler.post(new Runnable() { @Override public void run() { IsAuthorized(); } }); return; } try { // potentially time-consuming calls RequestToken newRequestToken; twitter.setOAuthConsumer(myConsumerKey, myConsumerSecret); newRequestToken = twitter.getOAuthRequestToken(CALLBACK_URL); String authURL = newRequestToken.getAuthorizationURL(); requestToken = newRequestToken; // request token will be // needed to get access token Intent browserIntent = new Intent(Intent.ACTION_MAIN, Uri .parse(authURL)); browserIntent.setClassName(container.$context(), WEBVIEW_ACTIVITY_CLASS); container.$context().startActivityForResult(browserIntent, requestCode); } catch (TwitterException e) { Log.i("Twitter", "Got exception: " + e.getMessage()); e.printStackTrace(); form.dispatchErrorOccurredEvent(Twitter.this, "Authorize", ErrorMessages.ERROR_TWITTER_EXCEPTION, e.getMessage()); DeAuthorize(); // clean up } catch (IllegalStateException ise){ //This should never happen cause it should return // at the if (checkAccessToken...). We mark as an error but let continue Log.e("Twitter", "OAuthConsumer was already set: launch IsAuthorized()"); handler.post(new Runnable() { @Override public void run() { IsAuthorized(); } }); } } }); }
Example #30
Source File: TwitterOauthWizard.java From Onosendai with Apache License 2.0 | 4 votes |
protected void stashRequestToken (final RequestToken token) { if (this.requestToken != null) throw new IllegalStateException("Request token alrady stashed."); if (token == null) throw new IllegalStateException("Can not stash a null token."); this.requestToken = token; }