List of usage examples for twitter4j Twitter getOAuthRequestToken
RequestToken getOAuthRequestToken(String callbackURL) throws TwitterException;
From source file:org.jwebsocket.plugins.twitter.TwitterPlugIn.java
License:Apache License
private void requestAccessToken(WebSocketConnector aConnector, Token aToken) { TokenServer lServer = getServer();// w w w.j a v a2 s .co m // instantiate response token Token lResponse = lServer.createResponse(aToken); String lMsg; String lCallbackURL = aToken.getString("callbackURL"); try { if (!mCheckAuth(lResponse)) { mLog.error(lResponse.getString("msg")); } else { // get a new Twitter object for the user TwitterFactory lTwitterFactory = new TwitterFactory(); Twitter lTwitter = lTwitterFactory.getInstance(); lTwitter.setOAuthConsumer(mSettings.getConsumerKey(), mSettings.getConsumerSecret()); // pass callback URL to Twitter API if given RequestToken lReqToken = (lCallbackURL != null ? lTwitter.getOAuthRequestToken(lCallbackURL) : lTwitter.getOAuthRequestToken()); String lAuthenticationURL = lReqToken.getAuthenticationURL(); String lAuthorizationURL = lReqToken.getAuthorizationURL(); lResponse.setString("authenticationURL", lAuthenticationURL); lResponse.setString("authorizationURL", lAuthorizationURL); lMsg = "authenticationURL: " + lAuthenticationURL + ", authorizationURL: " + lAuthorizationURL; lResponse.setString("msg", lMsg); if (mLog.isInfoEnabled()) { mLog.info(lMsg); } aConnector.setVar(OAUTH_REQUEST_TOKEN, lReqToken); aConnector.setVar(TWITTER_VAR, lTwitter); } } catch (Exception lEx) { lMsg = lEx.getClass().getSimpleName() + ": " + lEx.getMessage(); mLog.error(lMsg); lResponse.setInteger("code", -1); lResponse.setString("msg", lMsg); } // send response to requester lServer.sendToken(aConnector, lResponse); }
From source file:org.kawalpemilukada.login.login.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from w w w .ja v a 2 s .c o m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String form_action = request.getParameter("form_action"); if (form_action == null) { form_action = ""; } PrintWriter out = response.getWriter(); if (form_action.equalsIgnoreCase("loginfb")) { String tahun = request.getParameter("tahun"); if (tahun == null) { tahun = ""; } Facebook facebook = new FacebookFactory().getInstance(); request.getSession().setAttribute("facebook", facebook); request.getSession().setAttribute("tahun", tahun); StringBuffer callbackURL = request.getRequestURL(); int index = callbackURL.lastIndexOf("/"); callbackURL.replace(index, callbackURL.length(), "").append("/callbackfb"); response.sendRedirect(facebook.getOAuthAuthorizationURL(callbackURL.toString()) + "&display=popup"); } if (form_action.equalsIgnoreCase("logintwit")) { String tahun = request.getParameter("tahun"); if (tahun == null) { tahun = ""; } Twitter twitter = new TwitterFactory().getInstance(); request.getSession().setAttribute("twitter", twitter); request.getSession().setAttribute("tahun", tahun); String rurl = request.getParameter("rurl"); StringBuffer callbackURL = request.getRequestURL(); int index = callbackURL.lastIndexOf("/"); callbackURL.replace(index, callbackURL.length(), "").append("/callbackTwit?rurl=" + rurl); try { RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString()); request.getSession().setAttribute("requestToken", requestToken); response.sendRedirect(requestToken.getAuthenticationURL()); } catch (TwitterException e) { request.getSession().removeAttribute("twitter"); request.getSession().removeAttribute("tahun"); } } if (form_action.equalsIgnoreCase("loginmobiletwit")) { String t = "twit"; UserData user = CommonServices.getUser(request); LinkedHashMap record = new LinkedHashMap(); Gson gson = new Gson(); StringBuffer sb = new StringBuffer(); String line = null; BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } JSONObject input = (JSONObject) JSONValue.parse(sb.toString()); if (user == null) { try { JSONObject twit = (JSONObject) input.get("user"); String id = CommonServices.getVal(twit.get("id")); id = id.replaceAll(t, ""); user = ofy().load().type(UserData.class).id(t + id).now(); if (user == null) { String accessToken = CommonServices.getVal(twit.get("token")); String accessTokenSecret = CommonServices.getVal(twit.get("secret")); String consumerKey = new CommonServices().getPropValues("kpu.properties", "consumerKey", request); String consumerSecret = new CommonServices().getPropValues("kpu.properties", "consumerSecret", request); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey) .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken) .setOAuthAccessTokenSecret(accessTokenSecret); Twitter twitter = new TwitterFactory(cb.build()).getInstance(); User u = twitter.showUser(twitter.getId()); user = new UserData("twit" + CommonServices.getVal(twitter.getId())); user.imgurl = u.getBiggerProfileImageURLHttps().replace("http://", "https://"); user.nama = CommonServices.getVal(u.getName()); user.link = "https://twitter.com/" + CommonServices.getVal(twitter.getScreenName()); user.email = ""; user.uuid = CommonServices.getVal(twit.get("uuid")); user.type = t; ofy().save().entity(user).now(); Dashboard dashboard = CommonServices.getDashboard(CommonServices.setParentId("2015", "0")); Dashboard dashboard2014 = CommonServices .getDashboard(CommonServices.setParentId("2014", "0")); dashboard.users = CommonServices.getuserSize() + ""; ofy().save().entity(dashboard).now(); dashboard2014.users = dashboard.users + ""; ofy().save().entity(dashboard2014).now(); } else { user.lastlogin = CommonServices.JakartaTime(); user.uuid = CommonServices.getVal(twit.get("uuid")); if (user.link.equalsIgnoreCase("https://twitter.com/kawalpemilukada") || user.link.equalsIgnoreCase( "https://www.facebook.com/app_scoped_user_id/10153164750839760/")) { user.userlevel = 100000000; } ofy().save().entity(user).now(); } request.getSession().setAttribute("UserData", JSONValue.parse(gson.toJson(user))); MobileSession mobileSession = new MobileSession(user.uid + "#" + user.uuid); JSONObject device = (JSONObject) input.get("device"); mobileSession.platform = CommonServices.getVal(device.get("platform")); mobileSession.version = CommonServices.getVal(device.get("version")); mobileSession.cordova = CommonServices.getVal(device.get("cordova")); mobileSession.model = CommonServices.getVal(device.get("model")); mobileSession.manufacturer = CommonServices.getVal(device.get("manufacturer")); mobileSession.appversion = CommonServices.getVal(device.get("appversion")); ofy().save().entity(mobileSession).now(); record.put("sessionid", mobileSession.uuid); } catch (Exception e) { } record.put("sumber", "bukan dari session"); } else { MobileSession mobileSession = new MobileSession(user.uid + "#" + user.uuid); JSONObject device = (JSONObject) input.get("device"); mobileSession.platform = CommonServices.getVal(device.get("platform")); mobileSession.version = CommonServices.getVal(device.get("version")); mobileSession.cordova = CommonServices.getVal(device.get("cordova")); mobileSession.model = CommonServices.getVal(device.get("model")); mobileSession.manufacturer = CommonServices.getVal(device.get("manufacturer")); mobileSession.appversion = CommonServices.getVal(device.get("appversion")); ofy().save().entity(mobileSession).now(); record.put("sessionid", mobileSession.uuid); record.put("sumber", "dari session"); } record.put("user", JSONValue.parse(gson.toJson(user))); response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("loginmobilefb")) { UserData user = CommonServices.getUser(request); LinkedHashMap record = new LinkedHashMap(); Gson gson = new Gson(); StringBuffer sb = new StringBuffer(); String line = null; BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } JSONObject input = (JSONObject) JSONValue.parse(sb.toString()); if (user == null) { String t = "fb"; JSONObject fb = (JSONObject) input.get("user"); String id = CommonServices.getVal(fb.get("id")); id = id.replaceAll(t, ""); try { user = ofy().load().type(UserData.class).id(t + id).now(); if (user == null) { user = new UserData("fb" + CommonServices.getVal(fb.get("id"))); user.imgurl = "https://graph.facebook.com/" + fb.get("id") + "/picture"; user.nama = CommonServices.getVal(fb.get("name")); user.link = CommonServices.getVal(fb.get("link")); user.email = CommonServices.getVal(fb.get("email")); user.type = t; user.uuid = CommonServices.getVal(fb.get("uuid")); ofy().save().entity(user).now(); Dashboard dashboard = CommonServices.getDashboard(CommonServices.setParentId("2015", "0")); Dashboard dashboard2014 = CommonServices .getDashboard(CommonServices.setParentId("2014", "0")); dashboard.users = CommonServices.getuserSize() + ""; ofy().save().entity(dashboard).now(); dashboard2014.users = dashboard.users + ""; ofy().save().entity(dashboard2014).now(); } else { user.lastlogin = CommonServices.JakartaTime(); user.uuid = CommonServices.getVal(fb.get("uuid")); if (user.link.equalsIgnoreCase("https://twitter.com/kawalpemilukada") || user.link.equalsIgnoreCase( "https://www.facebook.com/app_scoped_user_id/10153164750839760/")) { user.userlevel = 100000000; } ofy().save().entity(user).now(); } request.getSession().setAttribute("UserData", JSONValue.parse(gson.toJson(user))); MobileSession mobileSession = new MobileSession(user.uid + "#" + user.uuid); JSONObject device = (JSONObject) input.get("device"); mobileSession.platform = CommonServices.getVal(device.get("platform")); mobileSession.version = CommonServices.getVal(device.get("version")); mobileSession.cordova = CommonServices.getVal(device.get("cordova")); mobileSession.model = CommonServices.getVal(device.get("model")); mobileSession.manufacturer = CommonServices.getVal(device.get("manufacturer")); mobileSession.appversion = CommonServices.getVal(device.get("appversion")); ofy().save().entity(mobileSession).now(); record.put("sessionid", mobileSession.uuid); } catch (Exception e) { } record.put("sumber", "bukan dari session"); } else { record.put("sumber", "dari session"); MobileSession mobileSession = new MobileSession(user.uid + "#" + user.uuid); JSONObject device = (JSONObject) input.get("device"); mobileSession.platform = CommonServices.getVal(device.get("platform")); mobileSession.version = CommonServices.getVal(device.get("version")); mobileSession.cordova = CommonServices.getVal(device.get("cordova")); mobileSession.model = CommonServices.getVal(device.get("model")); mobileSession.manufacturer = CommonServices.getVal(device.get("manufacturer")); mobileSession.appversion = CommonServices.getVal(device.get("appversion")); ofy().save().entity(mobileSession).now(); record.put("sessionid", mobileSession.uuid); } record.put("user", JSONValue.parse(gson.toJson(user))); response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("cekauth")) { UserData user = CommonServices.getUser(request); LinkedHashMap record = new LinkedHashMap(); Gson gson = new Gson(); if (user == null) { record.put("status", "belum login"); } else { record.put("user", JSONValue.parse(gson.toJson(user))); if (user.terverifikasi.equalsIgnoreCase("Y")) { record.put("status", "terverifikasi"); } else { record.put("status", "Data Anda belum terverifikasi."); } } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } if (form_action.equalsIgnoreCase("verifikasi")) { LinkedHashMap record = new LinkedHashMap(); StringBuffer sb = new StringBuffer(); String line = null; BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) { sb.append(line); } JSONArray input = (JSONArray) JSONValue.parse(sb.toString()); String nama = ""; String jenis_kelamin = ""; String no_tps = ""; try { String url = new CommonServices().getPropValues("kpu.properties", "verifikasiURL", request); String inputx = getWeb(url + input.get(0).toString()); JSONObject data = (JSONObject) JSONValue.parse(inputx); nama = data.get("nama").toString(); jenis_kelamin = data.get("jenis_kelamin").toString(); } catch (Exception e) { nama = ""; } if (nama == null || nama.equalsIgnoreCase("")) { try { String url = new CommonServices().getPropValues("kpu.properties", "verifikasiURL2015", request); String inputx = getWeb(url + input.get(0).toString()); LinkedHashMap data = getJsonNik(inputx); nama = data.get("nama").toString(); jenis_kelamin = data.get("jenis kelamin").toString(); no_tps = data.get("no_tps").toString(); } catch (Exception e) { nama = ""; } } JSONArray matchs = new JSONArray(); if (nama.equalsIgnoreCase(input.get(1).toString())) { UserData user = CommonServices.getUser(request); double match = 0; //if (data.get("nama").toString().equalsIgnoreCase(user.nama)) { //match = 100; //} else { String[] sosialnamaParts = user.nama.toString().split(" "); String[] namaParts = nama.toString().split(" "); int dibagi = sosialnamaParts.length; if (namaParts.length > dibagi) { dibagi = namaParts.length; } double increase = 100 / dibagi; String iiString = ""; for (int i = 0; i < namaParts.length; i++) { String namaPart = namaParts[i]; for (int ii = 0; ii < sosialnamaParts.length; ii++) { String fbnamaPart = sosialnamaParts[ii]; if (namaPart.equalsIgnoreCase(fbnamaPart) && (!iiString.contains(ii + ""))) { match = match + increase; matchs.add(namaPart + " sesuai dengan " + fbnamaPart); iiString = iiString + "[" + ii + "]"; break; } } } // } if (match > 100) { match = 100; } if (match >= 60) { user.terverifikasi = "Y"; user.notps = no_tps; ObjectifyService.ofy().save().entity(user).now(); Gson gson = new Gson(); record.put("user", JSONValue.parse(gson.toJson(user))); } record.put("status", match + ""); record.put("matchs", matchs); } else { record.put("status", "Data NIK: " + input.get(0).toString() + " dan Nama: " + input.get(1).toString() + " tidak ditemukan."); } response.setContentType("text/html;charset=UTF-8"); out.print(JSONValue.toJSONString(record)); out.flush(); } }
From source file:org.keycloak.social.twitter.TwitterIdentityProvider.java
License:Open Source License
@Override public Response performLogin(AuthenticationRequest request) { try {//from w ww .j a v a 2 s . c o m Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(getConfig().getClientId(), getConfig().getClientSecret()); URI uri = new URI(request.getRedirectUri() + "?state=" + request.getState()); RequestToken requestToken = twitter.getOAuthRequestToken(uri.toString()); ClientSessionModel clientSession = request.getClientSession(); clientSession.setNote("twitter_token", requestToken.getToken()); clientSession.setNote("twitter_tokenSecret", requestToken.getTokenSecret()); URI authenticationUrl = URI.create(requestToken.getAuthenticationURL()); return Response.temporaryRedirect(authenticationUrl).build(); } catch (Exception e) { throw new IdentityBrokerException("Could send authentication request to twitter.", e); } }
From source file:org.keycloak.social.twitter.TwitterProvider.java
License:Open Source License
@Override public AuthRequest getAuthUrl(SocialProviderConfig config, String state) throws SocialProviderException { try {/*ww w. j ava 2s . c o m*/ Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(config.getKey(), config.getSecret()); URI uri = new URI(config.getCallbackUrl() + "?state=" + state); RequestToken requestToken = twitter.getOAuthRequestToken(uri.toString()); return AuthRequest.create(requestToken.getAuthenticationURL()) .setAttribute("token", requestToken.getToken()) .setAttribute("tokenSecret", requestToken.getTokenSecret()).build(); } catch (Exception e) { throw new SocialProviderException(e); } }
From source file:org.mla.cbox.shibboleth.idp.authn.impl.InitializeTwitterContext.java
License:Apache License
@Override protected void doExecute(@Nonnull final ProfileRequestContext profileRequestContext, @Nonnull final AuthenticationContext authenticationContext) { /* Create a new TwitterContext */ final TwitterContext twitterContext = new TwitterContext(); /* Set the Twitter integration details for the context */ twitterContext.setTwitterIntegration(this.twitterIntegration); log.debug("{} Created TwitterContext using TwitterIntegration with consumer key {}", getLogPrefix(), this.twitterIntegration.getOauthConsumerKey()); /* Create a new Twitter class instance and add it to the context */ Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(this.twitterIntegration.getOauthConsumerKey(), this.twitterIntegration.getOauthConsumerSecret()); twitterContext.setTwitter(twitter);/*from w w w . j a v a2 s.co m*/ /* Find the Spring context and from it the current flow execution URL */ SpringRequestContext springRequestContext = (SpringRequestContext) profileRequestContext .getSubcontext(SpringRequestContext.class); RequestContext requestContext = springRequestContext.getRequestContext(); String flowUrl = requestContext.getFlowExecutionUrl(); /* Construct the callback URL using the flow execution URL and the server details */ ServletExternalContext externalContext = (ServletExternalContext) requestContext.getExternalContext(); HttpServletRequest request = (HttpServletRequest) externalContext.getNativeRequest(); StringBuilder callbackUrlBuilder = new StringBuilder().append(request.getScheme()).append("://") .append(request.getServerName()).append(flowUrl).append("&_eventId=proceed"); String callbackUrl = callbackUrlBuilder.toString(); /* Query Twitter for the request token and include the callback URL */ try { log.debug("{} Obtaining request token with callback URL {}", getLogPrefix(), callbackUrl); RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl); twitterContext.setRequestToken(requestToken); log.debug("{} Obtained request token", getLogPrefix()); } catch (TwitterException e) { log.error("{} Error obtaining request token from Twitter: {}", getLogPrefix(), e.getErrorMessage()); ActionSupport.buildEvent(profileRequestContext, AuthnEventIds.NO_CREDENTIALS); return; } /* Save the context as a sub context to the authentication context */ authenticationContext.addSubcontext(twitterContext, true); return; }
From source file:org.picketlink.extensions.core.social.twitter.TwitterAuthenticationMechanism.java
License:Open Source License
@Override protected Principal doAuthenticate(UserCredential credential, AuthenticationResult result) throws AuthenticationException { TwitterCredential oAuthCredential = (TwitterCredential) credential; HttpServletRequest request = oAuthCredential.getRequest(); HttpServletResponse response = oAuthCredential.getResponse(); HttpSession session = request.getSession(); Principal principal = null;/*from ww w. ja v a 2 s. c o m*/ Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(clientID, clientSecret); //See if we are a callback RequestToken requestToken = (RequestToken) session.getAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE); if (requestToken != null) { String verifier = request.getParameter("oauth_verifier"); try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); session.setAttribute("accessToken", accessToken); session.removeAttribute("requestToken"); } catch (TwitterException e) { throw new AuthenticationException(e); } try { principal = new TwitterPrincipal(twitter.verifyCredentials()); checkUserInStore((TwitterPrincipal) principal); } catch (TwitterException e) { throw new AuthenticationException(e); } return principal; } try { requestToken = twitter.getOAuthRequestToken(returnURL); session.setAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE, requestToken); response.sendRedirect(requestToken.getAuthenticationURL()); } catch (Exception e) { throw new AuthenticationException(e); } return principal; }
From source file:org.picketlink.social.auth.TwitterAuthenticator.java
License:Apache License
@Override public void authenticate() { if (httpServletRequest == null) { throw new IllegalStateException("http request not available"); }/* w w w .j a v a 2s . co m*/ if (httpServletResponse == null) { throw new IllegalStateException("http response not available"); } if (configuration == null) { throw new IllegalStateException("configuration not available"); } HttpSession session = httpServletRequest.getSession(); ServletContext servletContext = httpServletRequest.getServletContext(); String clientID = configuration.getClientID(); String clientSecret = configuration.getClientSecret(); String returnURL = configuration.getReturnURL(); Principal principal = null; Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(clientID, clientSecret); //See if we are a callback String verifier = httpServletRequest.getParameter("oauth_verifier"); RequestToken requestToken = (RequestToken) session.getAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE); if (verifier != null && requestToken == null) { //Let us fall back String twitterSentRequestToken = httpServletRequest.getParameter("oauth_token"); if (twitterSentRequestToken != null) { requestToken = (RequestToken) servletContext.getAttribute(twitterSentRequestToken); } if (requestToken == null) { throw new IllegalStateException("Verifier present but request token null"); } //Discard the stored request tokens servletContext.removeAttribute(twitterSentRequestToken); session.removeAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE); } if (requestToken != null && verifier != null) { try { AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier); session.setAttribute("accessToken", accessToken); session.removeAttribute("requestToken"); } catch (TwitterException e) { throw new AuthenticationException("Twitter Login:", e); } try { principal = new TwitterPrincipal(twitter.verifyCredentials()); setStatus(AuthenticationStatus.SUCCESS); setAccount(new User(principal.getName())); return; } catch (TwitterException e) { throw new AuthenticationException("Twitter Login:", e); } } try { requestToken = twitter.getOAuthRequestToken(returnURL); session.setAttribute(TWIT_REQUEST_TOKEN_SESSION_ATTRIBUTE, requestToken); //back up in the case the browser provides a new session to the user on twitter callback servletContext.setAttribute(requestToken.getToken(), requestToken); httpServletResponse.sendRedirect(requestToken.getAuthenticationURL()); } catch (Exception e) { throw new AuthenticationException("Twitter Login:", e); } if (principal != null) { setStatus(AuthenticationStatus.SUCCESS); setAccount(new User(principal.getName())); } }
From source file:org.smarttechie.servlet.TwitterLoginServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("TwitterLoginServlet:doGet"); ConfigurationBuilder cb = new ConfigurationBuilder(); Properties props = new TwitterProperties().getProperties(); cb.setDebugEnabled(true).setOAuthConsumerKey((String) props.get("twitterConsumerKey")) .setOAuthConsumerSecret((String) props.get("twitterConsumerSecret")) .setOAuthRequestTokenURL((String) props.get("twitterRequestTokenURL")) .setOAuthAuthorizationURL((String) props.get("twitterAuthorizeURL")) .setOAuthAccessTokenURL((String) props.get("twitterAccessTokenURL")); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); request.getSession().setAttribute("twitter", twitter); try {/*from www. ja v a 2 s.c o m*/ StringBuffer callbackURL = request.getRequestURL(); System.out.println("TwitterLoginServlet:callbackURL:" + callbackURL); int index = callbackURL.lastIndexOf("/"); callbackURL.replace(index, callbackURL.length(), "").append("/TwitterCallback"); RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString()); request.getSession().setAttribute("requestToken", requestToken); System.out.println("requestToken.getAuthenticationURL():" + requestToken.getAuthenticationURL()); response.sendRedirect(requestToken.getAuthenticationURL()); } catch (TwitterException e) { throw new ServletException(e); } }
From source file:org.tomochika1985.twitter.AppSession.java
License:Apache License
public Twitter getTwitterSession(Request request) throws NeedAuthenticationException { if (request == null) throw new IllegalArgumentException("'request' is missing"); //?Twitter????????? if (twitterSession != null) return twitterSession; // AccessTokenDB?????????????AccessToken?? // Twitter???????? // ????AccessToken???????????OAuth?? // OAuth?RequestToken??? Twitter client = new TwitterClient(); client.setOAuthConsumer(consumerKey, consumerSecret); RequestToken token = null;//from w w w .j a va 2 s . c om try { token = client.getOAuthRequestToken(RequestUtils.toAbsolutePath("login", "/")); } catch (TwitterException ex) { throw new RuntimeException(ex); } this.requestToken = token; this.lastAccessUrl = request.getClientUrl().toString(); dirty(); throw new RedirectToUrlException(token.getAuthorizationURL()); }
From source file:org.wso2.carbon.identity.authenticator.twitter.TwitterAuthenticator.java
License:Open Source License
/** * Initiate the authentication request// w w w. ja v a2 s . c o m */ @Override protected void initiateAuthenticationRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationContext context) throws AuthenticationFailedException { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); Map<String, String> authenticatorProperties = context.getAuthenticatorProperties(); String apiKey = authenticatorProperties.get(TwitterAuthenticatorConstants.TWITTER_API_KEY); String apiSecret = authenticatorProperties.get(TwitterAuthenticatorConstants.TWITTER_API_SECRET); configurationBuilder.setIncludeEmailEnabled(true); Twitter twitter = new TwitterFactory(configurationBuilder.build()).getInstance(); twitter.setOAuthConsumer(apiKey, apiSecret); try { String queryParams = FrameworkUtils.getQueryStringWithFrameworkContextId(context.getQueryParams(), context.getCallerSessionKey(), context.getContextIdentifier()); String callbackURL = getCallbackUrl(authenticatorProperties); RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString()); String subStr = queryParams .substring(queryParams.indexOf(TwitterAuthenticatorConstants.TWITTER_SESSION_DATA_KEY + "=")); String sessionDK = subStr .substring(subStr.indexOf(TwitterAuthenticatorConstants.TWITTER_SESSION_DATA_KEY + "="), subStr.indexOf("&")) .replace((TwitterAuthenticatorConstants.TWITTER_SESSION_DATA_KEY + "="), ""); request.getSession().setAttribute(TwitterAuthenticatorConstants.TWITTER_SESSION_DATA_KEY, sessionDK); request.getSession().setAttribute(TwitterAuthenticatorConstants.TWITTER_REQUEST_TOKEN, requestToken); request.getSession().setAttribute(TwitterAuthenticatorConstants.AUTHENTICATOR_NAME.toLowerCase(), twitter); response.sendRedirect(requestToken.getAuthenticationURL()); } catch (TwitterException e) { log.error("Exception while sending to the Twitter login page.", e); throw new AuthenticationFailedException(e.getMessage(), e); } catch (IOException e) { log.error("Exception while sending to the Twitter login page.", e); throw new AuthenticationFailedException(e.getMessage(), e); } }