Intergrating Twitter OAuth using java/spring/Twitter4j


The comprehensive link about Twitter approach for using Oauth (its same for other cases too ) can be found
TwitterOAuth
To cut it short following are the important steps:

Get the consumer key and consumer secret.Dev Twitter

Twitter API

Note: If you are going to make an webapp dont forget to put a valid url in the “CallBack Url” field. The valid url can be back to your localhost. But dont put “localhost” as twitter doesnt provide support. I had put http://127.0.0.1:8080/SpringMVC/callback for this application. The value of url can be changed at runtime.

Following are the steps using browser.. My homepage url is

http://localhost:8080/SpringMVC/welcome


When a user clicks on the hyperlink an oauth authorize request is sent to twitter by sharing the token key and token secret and user is redirected to twitter page.

After login into Twitter the user will be redirected to the callback url and the username will be displayed.

I am using Twitter4j for connecting with Twitter.

@RequestMapping("/welcome")
@Controller
public class WelcomeController {
        @Autowired
	private OAuthToken oauthToken;
        Twitter twitter = new TwitterFactory().getInstance();

	@Autowired
	private MyAccessToken accestoken;
	@RequestMapping(method = RequestMethod.GET)
	
	public String printWelcome(HttpServletResponse response,HttpServletRequest request) {

		twitter.setOAuthConsumer(oauthToken.getConsumerKey(),
		oauthToken.getConsumerSecret());
		RequestToken requestToken;
		try {
			
			String callbackURL = "http://127.0.0.1:8080/SpringMVC/callback";
             requestToken = twitter.getOAuthRequestToken(callbackURL);
             String token = requestToken.getToken();
 			String tokenSecret = requestToken.getTokenSecret();
			accestoken.setTokensecret(tokenSecret);
			accestoken.setToken(token);
			String authUrl = requestToken.getAuthorizationURL();
			request.setAttribute("authUrl", authUrl);
		} catch (TwitterException e) {
			e.printStackTrace();
		} 
		
		return "login";
	}
}

The callback url can be set as shown above. The MyAcessToken is used to persist the token for the request.

My login.jsp is

 <a href='<%=request.getAttribute("authUrl") %>'>Sign in with Twitter</a>

So when the user enters http://127.0.0.1/SpringMVC/welcome , they will be redirected to login.jsp.

When the user clicks on the “Sign in” link , it will be redirected to Twitter login site and then will be redirected to the callback url set. The controller to handle callback url is

@Controller
@RequestMapping("/callback")
public class CallBackController extends AbstractController{</code>

	@Autowired
	private OAuthToken oauthToken;
	
	@Autowired
	private MyAccessToken accessToken; 
	@Override
	@RequestMapping(method={RequestMethod.GET,RequestMethod.POST})
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
			Twitter twitter = new TwitterFactory().getInstance();
			
			twitter.setOAuthConsumer(oauthToken.getConsumerKey(), oauthToken.getConsumerSecret());
			String verifier = request.getParameter("oauth_verifier");
	       RequestToken requestToken = new RequestToken(accessToken.getToken(), accessToken.getTokensecret());
	       AccessToken accessToken = twitter.getOAuthAccessToken(requestToken,verifier);
	       twitter.setOAuthAccessToken(accessToken);
	       User user = twitter.verifyCredentials();
	       System.out.println(user.getName());
	       ModelAndView model = new ModelAndView("hello");
	       model.addObject("message", user.getName());
	       return model;
	}
}

Once the user comes back it will be redirected to “hello.jsp” with user name displayed.Note the MyAccessToken set for user before request is made is used here.

<html>;
<body>
<h1>Twitter Login successful for : ${message}</h1>
</body>
</html>

The oauthtoken is stored and configured in dispatcher-servlet xml which is loaded using web.xml

<bean>
<context:component-scan base-package="com.common.controller" />

<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="oauthToken" class="com.common.OAuthToken">
<property name="consumerKey" value="yourconsumerkey"/>
<property name="consumerSecret" value="yourconsumersecret"/>
</bean>
<bean id="accessToken" class="com.mkyong.common.MyAccessToken"/>
</beans>

The other model classes OAuthToken and MyAccessToken :

public class OAuthToken {

	public String consumerKey;
	public String consumerSecret;
	public String getConsumerKey() {
		return consumerKey;
	}
	public void setConsumerKey(String consumerKey) {
		this.consumerKey = consumerKey;
	}
	public String getConsumerSecret() {
		return consumerSecret;
	}
	public void setConsumerSecret(String consumerSecret) {
		this.consumerSecret = consumerSecret;
	}
}
public class MyAccessToken {

	private String token;
	private String tokensecret;
	public String getTokensecret() {
		return tokensecret;
	}
	public void setTokensecret(String tokensecret) {
		this.tokensecret = tokensecret;
	}
	public String getToken() {
		return token;
	}
	public void setToken(String token) {
		this.token = token;
	}
	
}

Download Source Code

15 thoughts on “Intergrating Twitter OAuth using java/spring/Twitter4j

  1. well, good one mate, but what if more than one user tries to register the same time? “MyAccessToken” is a Application Scoped Bean.

    The second user would overwrite the request token from the first user. Therefore, the second user will get an exception..

    It’s the same deal as I am struggling with at the moment…
    U have a solution for this?

      1. Really? “MyAccessToken” is ApplicationScoped or am I wrong? I can’t see any annotation that said it’s requestscoped. So if you create a bean like “MyAccessToken”, it will be a singleton, means created once.
        You then store the Requesttoken-Data into the singleton (WelcomeController).
        Finally you read this again in the “CallbackController”.
        Ok, but the “MyAccessToken” still is a singleton. Means if another request comes in, the data from this singleton (which only exists once) will be overwritten.. Correct me if I am wrong or please help me to understand it:)

  2. Exactly what I’ve thought. If i open 2 Browsers and let them try to login the same time, I get this error message in the first browser, Because it seems like the second browser overwrote the request token from the first.

    Error from Twitter:

    Woah there!

    This page is no longer valid. It looks like someone already used the token information you provided. Please return to the site that sent you to this page and try again … it was probably an honest mistake.

    1. ah .. ok ..good catch. Basically the access has to be request scoped and in my application it happened to be singleton class. So make the bean to request scope …

  3. Hi Harshit.
    Thanks for your example.

    I’m trying to run your example (downloading the source code). But I can’t see the first page to call. I tried with login.jsp directly, typing:
    http://localhost:7070/examples/jsp/oAuth/SpringMVC/src/main/webapp/WEB-INF/pages/login.jsp
    But when I made click in the link, a 404 error appears, because it’s trying to access to:
    http://localhost:7070/examples/jsp/oAuth/SpringMVC/src/main/webapp/WEB-INF/pages/null

    Could you tell me what I’m doing wrong?
    PS: I changed my tokens in mvc-dispatcher-servlet.xml

    Thanks in advance

    Tony

      1. Hi again Harshit.

        Thanks for your quick answer. The consumerKey and consumersecret are correct, but I can’t find the file to type the acces_token or the oauth_token_secret
        On the other hand, let me add that I’m completely new using jsp. I found a pom.xml Should I compile the project?

        Thanks,

        Tony

  4. Hi Harshit.

    I tried to execute it directly from browser (only changing the xml), but now I see that you’re using SpringMVC.
    I’m now following a tutorial to study the SpringMVC with the Eclipse ID
    Thanks,

    Tony

  5. Consumer Controlled Media Marketing has been a network controlled media as
    the message terminates once it reaches the user. We can play our own favorite games, on our very own Mobile Phones.
    If the author has not set the security feature to disallow anybody from
    copying the text in PDF file then you can select
    and copy the text in the Word file.

  6. I do not know whether it’s just me or if perhaps everyone else experiencing problems with your website.
    It appears as if some of the written text within your content are running off the screen. Can somebody else
    please comment and let me know if this is happening to them
    as well? This could be a problem with my internet browser because I’ve had this
    happen before. Cheers

Leave a comment