Search code examples
javagoogle-app-enginetwitter4j

twitter4j getOauthAccessToken giving exception


I am trying to get a user's access token using twitter4j in my appengine project. My code is below

    HttpSession session = req.getSession();
    String tokenCopy = (String) session
            .getAttribute(Constants.TOKEN_SESSION_KEY);
    String tokenSecretCopy = (String) session
            .getAttribute(Constants.TOKENSECRET_SESSION_KEY);

    String oauth_token = req.getParameter("oauth_token");
    //The above is the same as the tokenCopy, verified by printing.
    String oauth_verifier = req.getParameter("oauth_verifier");

    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(Constants.CONSUMER_KEY,
            Constants.CONSUMER_SECRET);

    String extraHTML = "NOTHING\n";

    try {
        AccessToken accessToken;
        accessToken = twitter
                .getOAuthAccessToken(tokenCopy, oauth_verifier);
        // accessToken = twitter.getOAuthAccessToken(oauth_verifier);
        // accessToken = twitter.getOAuthAccessToken();

        String accessTokenStr = accessToken.getToken();
        String accessTokenSecret = accessToken.getTokenSecret();
        extraHTML = "<p>accessToken = " + accessTokenStr
                + ", accessTokenSecret = " + accessTokenSecret + "</p>\n";

        // TODO latertwitter.setOAuthAccessToken(accessToken);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        extraHTML = "<pre>" + e.getMessage() + "</pre>\n";
    }

Sadly, when my code runs, I always get the exception

401:Authentication credentials (https://dev.twitter.com/docs/auth) were missing or
incorrect. Ensure that you have set valid conumer key/secret, access token/secret,
and the system clock in in sync.

I know my CONSUMER_KEY and CONSUMER_SECRET are correct (I used them to create the twitter auth url and that works well). What am I missing here? Should I be passing something else to the call to getOAuthAccessToken() ?

Thanks.


Solution

  • I'm using RequestToken object, instead of String, everything else looks same.

    I mean that when i'm preparing authentication url, i'm doing following:

    RequestToken requestToken = twitter.getOAuthRequestToken(callbackUrl);
    session.setAttribute(Constants.TOKEN_SESSION_KEY, requestToken);
    

    and instead of your code's line #2 it will be:

    RequestToken tokenCopy = (RequestToken) session.getAttribute(Constants.TOKEN_SESSION_KEY);
    

    Everything else looks correct.