Example usage for twitter4j Twitter getOAuthRequestToken

List of usage examples for twitter4j Twitter getOAuthRequestToken

Introduction

In this page you can find the example usage for twitter4j Twitter getOAuthRequestToken.

Prototype

RequestToken getOAuthRequestToken(String callbackURL) throws TwitterException;

Source Link

Document

Retrieves a request token

Usage

From source file:net.codestory.http.filters.twitter.TwitterAuthenticator.java

License:Apache License

@Override
public URI getAuthenticateURI(String callbackUri) {
    Twitter twitter = twitterFactory.getInstance();
    try {/*from   ww  w.j av  a 2 s  .c  o  m*/
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackUri);
        oauthRequestByToken.put(requestToken.getToken(), requestToken);
        return URI.create(requestToken.getAuthenticationURL());
    } catch (TwitterException e) {
        throw new AuthenticationException(e);
    }
}

From source file:net.firejack.platform.web.security.twitter.TwitterAuthenticationProcessor.java

License:Apache License

@Override
public void processAuthentication(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws IOException, ServletException {
    if (StringUtils.isBlank(getTwitterConsumerKey()) || StringUtils.isBlank(getTwitterConsumerSecret())) {
        logger.error("Twitter consumer key or consumer secret configs were not set.");
        response.sendRedirect(getDefaultPageUrl());
    } else {//from ww  w . j  a v a 2  s.  c o m
        HttpSession httpSession = request.getSession(true);
        Twitter twitter = (Twitter) httpSession.getAttribute(ATTR_TWITTER_API);
        if (twitter == null) {
            twitter = populateTwitterService();
            httpSession.setAttribute(ATTR_TWITTER_API, twitter);
        }
        if (isRequestTokenCase(request)) {
            RequestToken requestToken;
            try {
                requestToken = twitter.getOAuthRequestToken(getCallbackUrl());
                httpSession.setAttribute(ATTR_TWITTER_REQUEST_TOKEN, requestToken);
                response.sendRedirect(requestToken.getAuthenticationURL());//show twitter authentication form
            } catch (TwitterException e) {//service is unavailable
                logger.error("Twitter service is unavailable.");
                logger.error(e.getMessage(), e);
                cleanSessionInformation(httpSession);
                response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                        "Twitter service is unavailable.");
            } catch (IllegalStateException e) {//access token is already available
                logger.error("access token is already available");
                cleanSessionInformation(httpSession);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Twitter processor already having information about access token.");
            }
        } else if (isAuthenticationCallback(request)) {
            RequestToken requestToken = (RequestToken) httpSession.getAttribute(ATTR_TWITTER_REQUEST_TOKEN);

            String verifier = request.getParameter("oauth_verifier");
            try {
                twitter.getOAuthAccessToken(requestToken, verifier);
                httpSession.removeAttribute(ATTR_TWITTER_REQUEST_TOKEN);

                String browserIpAddress = request.getRemoteAddr();
                AuthenticationToken authenticationToken = this.getOpenFlameToken(twitter, browserIpAddress);

                if (authenticationToken == null) {
                    logger.error("Authentication token is null.");
                }
                getSignInProcessor().processSignInInternal(request, response, authenticationToken);
            } catch (TwitterException e) {
                logger.error(e.getMessage(), e);
                cleanSessionInformation(httpSession);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
            }
        }
    }
}

From source file:net.nitram509.controller.TwitterSignInHttpController.java

License:Open Source License

public RequestToken retrieveTwitterRequestToken(HttpServletRequest request) throws TwitterException {
    Twitter twitter = twitterClientToolbox.getTwitterAsTweetGatewayApp();
    String callbackURL = computeCallbackUrl(request);
    return twitter.getOAuthRequestToken(callbackURL);
}

From source file:net.wasdev.gameon.auth.twitter.TwitterAuth.java

License:Apache License

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ConfigurationBuilder c = new ConfigurationBuilder();
    c.setOAuthConsumerKey(key).setOAuthConsumerSecret(secret);

    Twitter twitter = new TwitterFactory(c.build()).getInstance();
    request.getSession().setAttribute("twitter", twitter);

    try {//  www. j av  a2s . co m
        // twitter will tell the users browser to go to this address once
        // they are done authing.
        StringBuffer callbackURL = request.getRequestURL();
        int index = callbackURL.lastIndexOf("/");
        callbackURL.replace(index, callbackURL.length(), "").append("/TwitterCallback");

        // to initiate an auth request, twitter needs us to have a request
        // token.
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());

        // stash the request token in the session.
        request.getSession().setAttribute("requestToken", requestToken);

        // send the user to twitter to be authenticated.
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (TwitterException e) {
        throw new ServletException(e);
    }

}

From source file:org.celstec.arlearn2.oauth.OauthTwitterWorker.java

License:Open Source License

public void redirectToTwitterForAuthentication(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(client_id, client_secret);
    RequestToken token = null;//  w  ww .j a  v a2s .c  o  m
    try {
        token = twitter.getOAuthRequestToken(redirect_uri);
        req.getSession().setAttribute("requestToken", token);
        String loginUrl = token.getAuthenticationURL() + "&force_login=true";
        resp.sendRedirect(loginUrl);
    } catch (TwitterException e) {
        e.printStackTrace();
        log.log(Level.SEVERE, e.getErrorMessage(), e);
    }
}

From source file:org.eventjuggler.services.security.authc.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;//  w ww.  ja  v  a  2s .  c  o m

    provideSecrets(oAuthCredential);
    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);
    String verifier = request.getParameter("oauth_verifier");
    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(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.fenixedu.bennu.social.domain.api.TwitterAPI.java

License:Open Source License

@Override
public String getAuthenticationUrlForUser(User user) {

    try {//from w  ww  .  jav a2s . c  o m
        TwitterFactory tf = new TwitterFactory();
        Twitter twitter = tf.getInstance();
        twitter.setOAuthConsumer(getClientId(), getClientSecret());

        RequestToken oauthRequestToken = twitter.getOAuthRequestToken(getCallbackURL());

        String oauthToken = oauthRequestToken.getToken();
        String oauthTokenSecret = oauthRequestToken.getTokenSecret();
        String authorizationURL = oauthRequestToken.getAuthorizationURL();

        LOGGER.info("Received OauthToken. Token: " + oauthToken + ", TokenSecret: " + oauthTokenSecret
                + ", AuthenticationURL: " + authorizationURL);

        TwitterUser twitterUser = new TwitterService().getAuthenticatedUser(user);
        twitterUser.setOauthToken(oauthToken);
        twitterUser.setOauthTokenSecret(oauthTokenSecret);

        return authorizationURL;

    } catch (TwitterException e) {
        LOGGER.error("Received TwitterException:" + e.getErrorMessage());
        e.printStackTrace();
        return "";
    }
}

From source file:org.gameontext.auth.twitter.TwitterAuth.java

License:Apache License

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    ConfigurationBuilder c = new ConfigurationBuilder();
    c.setOAuthConsumerKey(key).setOAuthConsumerSecret(secret);

    Twitter twitter = new TwitterFactory(c.build()).getInstance();
    request.getSession().setAttribute("twitter", twitter);

    try {/*from w  ww.  j  a  va  2s. c o m*/
        // twitter will tell the users browser to go to this address once
        // they are done authing.
        String callbackURL = authURL + "/TwitterCallback";

        // to initiate an auth request, twitter needs us to have a request
        // token.
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL);

        // stash the request token in the session.
        request.getSession().setAttribute("requestToken", requestToken);

        // send the user to twitter to be authenticated.
        response.sendRedirect(requestToken.getAuthenticationURL());

    } catch (TwitterException e) {
        throw new ServletException(e);
    }

}

From source file:org.gatein.security.oauth.twitter.TwitterProcessorImpl.java

License:Open Source License

@Override
public InteractionState<TwitterAccessTokenContext> processOAuthInteraction(HttpServletRequest request,
        HttpServletResponse response) throws IOException, OAuthException {
    Twitter twitter = twitterFactory.getInstance();

    HttpSession session = request.getSession();

    //See if we are a callback
    RequestToken requestToken = (RequestToken) session
            .getAttribute(OAuthConstants.ATTRIBUTE_TWITTER_REQUEST_TOKEN);

    try {//w ww  .j a va 2s  .  com
        if (requestToken == null) {
            requestToken = twitter.getOAuthRequestToken(redirectURL);

            // Save requestToken to session, but only temporarily until oauth workflow is finished
            session.setAttribute(OAuthConstants.ATTRIBUTE_TWITTER_REQUEST_TOKEN, requestToken);

            if (log.isTraceEnabled()) {
                log.trace("RequestToken obtained from twitter. Redirecting to Twitter for authorization");
            }

            // Redirect to twitter to perform authentication
            response.sendRedirect(requestToken.getAuthenticationURL());

            return new InteractionState<TwitterAccessTokenContext>(InteractionState.State.AUTH, null);
        } else {
            String verifier = request.getParameter(OAuthConstants.OAUTH_VERIFIER);

            // User denied scope
            if (request.getParameter(OAuthConstants.OAUTH_DENIED) != null) {
                throw new OAuthException(OAuthExceptionCode.USER_DENIED_SCOPE,
                        "User denied scope on Twitter authorization page");
            }

            // Obtain accessToken from twitter
            AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);

            if (log.isTraceEnabled()) {
                log.trace("Twitter accessToken: " + accessToken);
            }

            // Remove requestToken from session. We don't need it anymore
            session.removeAttribute(OAuthConstants.ATTRIBUTE_TWITTER_REQUEST_TOKEN);
            TwitterAccessTokenContext accessTokenContext = new TwitterAccessTokenContext(accessToken.getToken(),
                    accessToken.getTokenSecret());

            return new InteractionState<TwitterAccessTokenContext>(InteractionState.State.FINISH,
                    accessTokenContext);
        }
    } catch (TwitterException twitterException) {
        throw new OAuthException(OAuthExceptionCode.TWITTER_ERROR, twitterException);
    }
}

From source file:org.jetbrains.webdemo.servlet.TwitterServlet.java

License:Apache License

private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    try {// ww  w . j  a va  2s  . c o m
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(apiKey, apiSecret);
        request.getSession().setAttribute("twitter", twitter);
        String callbackURL = request.getScheme() + "://" + request.getServerName() + ":"
                + request.getServerPort() + "/twitter/tweet";
        request.getSession().setAttribute("tweetText", request.getParameter("tweet-text"));
        request.getSession().setAttribute("kotlin-level", request.getParameter("kotlin-level"));
        RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL);
        request.getSession().setAttribute("requestToken", requestToken);
        response.sendRedirect(requestToken.getAuthenticationURL());
    } catch (Throwable e) {
        throw new ServletException(e);
    }
}