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

Advertisements