If you implement "Login With Twitter" for your website, users don't need to remember  password for your website, so users will feel comfortable to use your website. In advance, you can access users  timeline feed. Twitter is providing Twitter4J to implement twitter api using java, download this twitter4j and add it to build path

Project

I have provided sample project here, download it. Open Setup.java and give your twitter app credentials, database credentials. Create MySQL database schema with name "demos". Created below specified table. Import this project into Eclipse, add it to tomcat server, run index.html

Implementation

  1. When user click on Login with twitter button, Provide them access link which is generated by Twitter4j with your app credentials. 
  2. User will be redirected to twitter api page
  3. Once user gives permission, access token and oauth verifier will be sent to callback URL
  4. Now verify the access token with oauth verifier. It will generate access token object which will have access token and access token secret 
  5. Now save access token and access token secret in database with user details like twitter user id and screen name.
User cant change their twitter user id, so we can use this to identify user. If user login again, we can process user's account using twitter user id. Whenever you want to update status on user's timeline, you can do with these saved access tokens.

Create App In Twitter Developer Page

Open twitter apps webpage.  Create your app and get Consumer Key and Consumer Secret Key. Observe below diagram.

Database Table

Created database table like below.

CREATE TABLE `demos`.`twitter_user` (
  `user_id` INT NOT NULL AUTO_INCREMENT COMMENT '',
  `twitter_user_id` INT NULL COMMENT '',
  `screen_name` VARCHAR(45) NULL COMMENT '',
  `access_token` VARCHAR(100) NULL COMMENT '',
  `access_token_secret` VARCHAR(100) NULL COMMENT '',
  `created_date` DATETIME NULL DEFAULT CURRENT_TIMESTAMP COMMENT '',
  PRIMARY KEY (`user_id`)  COMMENT '',
  UNIQUE INDEX `twitter_user_id_UNIQUE` (`twitter_user_id` ASC)  COMMENT '');

Prepare Signin Link

Observe below code. Configure twitter object with Consumer Key and Secret Key, Generate request token with callback URL, save it to session. Generate authentication URL and redirect to that URL
// configure twitter api with consumer key and secret key
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
  .setOAuthConsumerKey(Setup.CONSUMER_KEY)
  .setOAuthConsumerSecret(Setup.CONSUMER_SECRET);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
request.getSession().setAttribute("twitter", twitter);
try {
    
    // setup callback URL
    StringBuffer callbackURL = request.getRequestURL();
    int index = callbackURL.lastIndexOf("/");
    callbackURL.replace(index, callbackURL.length(), "").append("/callback");

    // get request object and save to session
    RequestToken requestToken = twitter.getOAuthRequestToken(callbackURL.toString());
    request.getSession().setAttribute("requestToken", requestToken);
    
    // redirect to twitter authentication URL
    response.sendRedirect(requestToken.getAuthenticationURL());

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

Callback Servlet

Callback servlet will receive oauth_verifier parameter. Verify access token with that verification code, then you will get access token object, Now save or update access token or access token secret to database. Here we identify user with twitter user id that is always constant. TwitterDAO.selectTwitterUser method gives user object based on twitter user id.
// Get twitter object from session
Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
//Get twitter request token object from session
RequestToken requestToken = (RequestToken) request.getSession().getAttribute("requestToken");
String verifier = request.getParameter("oauth_verifier");
try {
    // Get twitter access token object by verifying request token 
    AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
    request.getSession().removeAttribute("requestToken");
    
    // Get user object from database with twitter user id
    UserPojo user = TwitterDAO.selectTwitterUser(accessToken.getUserId());
    if(user == null) {
       // if user is null, create new user with given twitter details 
       user = new UserPojo();
       user.setTwitter_user_id(accessToken.getUserId());
       user.setTwitter_screen_name(accessToken.getScreenName());
       user.setAccess_token(accessToken.getToken());
       user.setAccess_token_secret(accessToken.getTokenSecret());
       TwitterDAO.insertRow(user);
       user = TwitterDAO.selectTwitterUser(accessToken.getUserId());
    } else {
       // if user already there in database, update access token
       user.setAccess_token(accessToken.getToken());
       user.setAccess_token_secret(accessToken.getTokenSecret());
       TwitterDAO.updateAccessToken(user);
    }
    request.setAttribute("user", user);
} catch (TwitterException | DBException e) {
    throw new ServletException(e);
} 
request.getRequestDispatcher("/status.jsp").forward(request, response);

0 comments:

Blogroll

Follow this blog by Email

Popular Posts