OAuth is an open standard supported by many major websites such as google twitter etc allowing user to share resources such as videos photos etc.

You may have noticed that many websites allow uses to register or login with their social network account -facebook account,twitter account etc-.In this tutorial we will see how you can use Scribe API to allow your users login to your website using their twitter account.

Before we begin the implementation of TwitterLogin controller note that you must have a twitter API key.

The TwitterLogin login contoller will look something like this:

package com.javaonly.controllers.readControllers;

import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.TwitterApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

public class TwitterLoginController extends ReadController {

    public void execute() {
        OAuthService service = new ServiceBuilder().provider(TwitterApi.class).apiKey("your api key").apiSecret("your api secret key").build();
        Token requestToken = service.getRequestToken();
        
        String authorizationUrl = service.getAuthorizationUrl(requestToken);
        Verifier verifier = new Verifier("The verifing PIN you got from the authorizationUrl");
        Token accessToken = service.getAccessToken(requestToken,verifier);
        OAuthRequest request = new OAuthRequest(Verb.GET, http://api.twitter.com/1/account/verify_credentials.xml);
    
    service.signRequest(accessToken, request);
    Response response = request.send();
        this.setReturnPage("/mainPage.jsp");
    }
}

In the above controller note that you must make a request to the authorization url in order to obtain  the verifing PIN.This is something that can be implemented in many ways.For example display a popup window with the the authorization url and then ask users to submit the PIN that they will get.

When authorization is completed you will get an xml response that will contain user details such as name,screen name,location,etc

 For more information on controllers please refer to FrontController tutorial