• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

HOW TO : SignIn with Twitter using Node.js and Express.js

June 1, 2015 //  by Mohamed Sanaulla//  Leave a Comment

In my previous posts, I have explained about few of the topics on NodeJS web application framework ExpressJS. Please read the topics: REST using ExpressJS, Working with MongooseJS and CRUD operations using MongoDB and NodeJS.

This post uses various combination on frameworks and shows you how to SignIn with Twitter using Node.js and Express.js frameworks. Accessing the social network websites like twitter and facebook through framework APIs become one of the important programming activities to implement the user actions in the websites. I have tried the template framework HandlebarsJS which is similar to another popular template framework Mustache in this example.

In this post I am going to show you few interesting things:

  1. Integrating Handlebars templates in Express.js
  2. Implemeting SignIn With Twitter
  3. Retrieving User’s latest 10 tweets after signin with Twitter

I am using the following new Node packages for this tutorial:

  1. express-handlebars: Node package to integrate Handlebars template engine with Express.js
  2. request: This package simplifies making HTTP request from the application. Node comes with default package for making HTTP requests, but I am making use of this as it provides support for OAuth Request signing. This OAuth request signing is required while authenticating with Twitter as we will see futher.
  3. querystring: This package helps in parsing the query strings into JSON objects and creating query string out of the JSON objects.

If you are interested in learning Node.js framework, please consider purchasing the below books for further reference:

  • Professional Node.js
  • Node.js in Action
  • Node.js Receipes

HandlebarsJS and ExpressJS Integration

HandlebarsJS is a templating framework which is used to generate dynamic views.

The below code sets up the Handlebars with ExpressJS:

//File Name: handlebars_demo.js
var express = require('express');

//NPM Module to integrate Handlerbars UI template engine with Express
var exphbs  = require('express-handlebars');

var app = express();

//Declaring Express to use Handlerbars template engine with main.handlebars as
//the default layout
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

app.get('/', function (req, res) {
  //Use hello.handlebars template with the JSON data passed as another argument
  res.render("hello", {name : "Sanaulla"});
});

app.listen(3000, function(){
  console.log('Server up: http://localhost:3000');
});

We need to create a HandlebarsJS template which is shown below:

//hello.handlebars
<h1>Hello Mr. {{name}} from Handlebars </h1>

We also create a layout file by name main.handlebars as shown below:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Example App</title>
</head>
<body>
    {{{body}}}
</body>
</html>

The above layout wraps any of the template output which means in this case the output of hello.handlebars replaces the {{{body}}}

The way the files are arranged is as shown below

node_samples
 |--handlebars_demo.js
 |--views
   |--hello.handlebars
   |--layouts
     |--main.handlebars

Now let us run the above javascript by using the command:

node handlebars_demo.js

Now open the following URL in your browser: http://localhost:3000/.

You will see Hello Mr. Sanaulla from Handlebars printed on the browser.

With this we have tried introduction to HandlebarsJS let us proceed to see how we can integrate with Twitter.

Implementing SignIn With Twitter using ExpressJS

The documentation here provides the different steps to authenticate with Twitter. Though the documentation is clear enough but its difficult to create a working solution following the official documentation.

Authenticating with Twitter involves 3 steps:

  1. Step-1: Obtaining a request token
  2. Step-2: Authenticating the user by redirecting to Twitter
  3. Step-3: Converting the request token to an access token

For the rest of the tutorial, the following code is common:

//File Name: social_signin.js
var express = require('express');

//NPM Module to integrate Handlerbars UI template engine with Express
var exphbs  = require('express-handlebars');

//NPM Module to make HTTP Requests
var request = require("request");

//NPM Module To parse the Query String and to build a Query String
var qs = require("querystring");

var app = express();

//Declaring Express to use Handlerbars template engine with main.handlebars as
//the default layout
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

Before starting off, you need to create an application on Twitter. After creating the app, you will have access to Consumer Key and Consumer Secret which is a must to authenticate with Twitter.

Step-1 : Obtaining the request token

In this tutorial, I obtain the request token on loading the page and use that request token to build the URL to Sign In With Twitter.

The below code makes call to Twitter to get request token.

//URL To obtain Request Token from Twitter
var requestTokenUrl = "https://api.twitter.com/oauth/request_token";

//To be obtained from the app created on Twitter
var CONSUMER_KEY = "kuDm1KBKBJH3PpusFxcAA";
var CONSUMER_SECRET = "5wOFqJe4R0Kf6SV9tXuqrzkpD7t7d8cvwZhPC7TW8";

//Oauth Object to be used to obtain Request token from Twitter
var oauth = {
  callback : "http://localhost:3000/signin-with-twitter",
  consumer_key  : CONSUMER_KEY,
  consumer_secret : CONSUMER_SECRET
}
var oauthToken = "";
var oauthTokenSecret = "";
app.get('/', function (req, res) {
  //Step-1 Obtaining a request token
  request.post({url : requestTokenUrl, oauth : oauth}, function (e, r, body){

    //Parsing the Query String containing the oauth_token and oauth_secret.
    var reqData = qs.parse(body);
    oauthToken = reqData.oauth_token;
    oauthTokenSecret = reqData.oauth_token_secret;

    //Step-2 Redirecting the user by creating a link
    //and allowing the user to click the link
    var uri = 'https://api.twitter.com/oauth/authenticate'
    + '?' + qs.stringify({oauth_token: oauthToken})
    res.render('home', {url : uri});
  });

});
app.listen(3000, function(){
  console.log('Server up: http://localhost:3000');
});

The code for the template home.handlebars is given below:

<h1>SignIn With Twitter Sample</h1>

<a href="{{url}}">Signin with Twitter</a>

Another template file main.handlebars is same as given above while introducing to Handlebars.

The directory structure is as given below:

|--social_signin.js
  |--views
    |--home.handlebars
    |--layouts
      |--main.handlebars

Lets run the above code by running node social_signin.js. This starts the server on port 3000.

Navigate to http://localhost:3000/, you should see the below output:

In the above screenshot the link Signin With Twitter redirects the user to Twitter to authenticate the user and authorise the app to make requests on behalf of the user. The request token obtained in this step is passed along with this link.

Step-2 Authenticating the user by redirecting to Twitter

There is nothing much to be done in the code in this step. The link genereted in the above step redirects the user to Twitter to authenticate and authorise.

And the callback we had sent earlier is invoked on successfully authenticating on Twitter.

The following data is sent to our callback: oauth_token and oauth_verifier.

Step-3 Converting the request token to an access token

In the callback we make use of the oauth_token and oauth_verifier to get the access token by making a oauth signed POST call to the URL: https://api.twitter.com/oauth/access_token

In the POST response after verifying the tokens and authenticating the user we get the oauth_token_secret, user_id, screen_name of the authenticated user.

The below code handles the Step-3:

//Callback to handle post authentication.
app.get("/signin-with-twitter", function(req, res){
  var authReqData = req.query;
  oauth.token = authReqData.oauth_token;
  oauth.token_secret = oauthTokenSecret;
  oauth.verifier = authReqData.oauth_verifier;

  var accessTokenUrl = "https://api.twitter.com/oauth/access_token";
  //Step-3 Converting the request token to an access token
  request.post({url : accessTokenUrl , oauth : oauth}, function(e, r, body){
    var authenticatedData = qs.parse(body);
    console.log(authenticatedData);
  });
});

With this we have successfully authenticated with twitter. Now let us see how to retrieve latest 10 tweets of the user.

Retrieving User’s latest 10 tweets after signin with Twitter

We make use of the oauth_token and oauth_token_secret along with the consumer_key and consumer_secret while making a call to the twitter API. The below code invokes the Twitter API with the right authentication data.


//Make a request to get User's 10 latest tweets
var apiUrl = "https://api.twitter.com/1.1/statuses/user_timeline.json" + "?"
  + qs.stringify({screen_name: authenticatedData.screen_name, count: 10});

var authenticationData = {
  consumer_key : CONSUMER_KEY,
  consumer_secret : CONSUMER_SECRET,
  token: authenticatedData.oauth_token,
  token_secret : authenticatedData.oauth_token_secret
};

request.get({url : apiUrl, oauth: authenticationData, json:true}, function(e, r, body){

  var tweets = [];
  for(i in body){
    var tweetObj = body[i];
    tweets.push({text: tweetObj.text});
  }

  var viewData = {
    username: authenticatedData.screen_name,
    tweets: tweets
  };

  res.render("my", viewData);

});

Wrapping Up

The directory structure for this sample is:

|--social_signin.js
|--views
  |--home.handlebars
  |--my.handlebars
  |--layouts
    |--main.handlebars

The complete code for this sample is:

//FileName: social_signin.js
var express = require('express');

//NPM Module to integrate Handlerbars UI template engine with Express
var exphbs  = require('express-handlebars');

//NPM Module to make HTTP Requests
var request = require("request");

//NPM Module To parse the Query String and to build a Query String
var qs = require("querystring");

var app = express();

//Declaring Express to use Handlerbars template engine with main.handlebars as
//the default layout
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

//URL To obtain Request Token from Twitter
var requestTokenUrl = "https://api.twitter.com/oauth/request_token";

//To be obtained from the app created on Twitter
var CONSUMER_KEY = "kuDm1KBKBJH3PpusFxcAA";
var CONSUMER_SECRET = "5wOFqJe4R0Kf6SV9tXuqrzkpD7t7d8cvwZhPC7TW8";

//Oauth Object to be used to obtain Request token from Twitter
var oauth = {
  callback : "http://localhost:3000/signin-with-twitter",
  consumer_key  : CONSUMER_KEY,
  consumer_secret : CONSUMER_SECRET
}
var oauthToken = "";
var oauthTokenSecret = "";
app.get('/', function (req, res) {
  //Step-1 Obtaining a request token
  request.post({url : requestTokenUrl, oauth : oauth}, function (e, r, body){

    //Parsing the Query String containing the oauth_token and oauth_secret.
    var reqData = qs.parse(body);
    oauthToken = reqData.oauth_token;
    oauthTokenSecret = reqData.oauth_token_secret;

    //Step-2 Redirecting the user by creating a link
    //and allowing the user to click the link
    var uri = 'https://api.twitter.com/oauth/authenticate'
    + '?' + qs.stringify({oauth_token: oauthToken})
    res.render('home', {url : uri});
  });

});

//Callback to handle post authentication.
app.get("/signin-with-twitter", function(req, res){
  var authReqData = req.query;
  oauth.token = authReqData.oauth_token;
  oauth.token_secret = oauthTokenSecret;
  oauth.verifier = authReqData.oauth_verifier;

  var accessTokenUrl = "https://api.twitter.com/oauth/access_token";
  //Step-3 Converting the request token to an access token
  request.post({url : accessTokenUrl , oauth : oauth}, function(e, r, body){
    var authenticatedData = qs.parse(body);
    console.log(authenticatedData);

    //Make a request to get User's 10 latest tweets
    var apiUrl = "https://api.twitter.com/1.1/statuses/user_timeline.json" + "?"
      + qs.stringify({screen_name: authenticatedData.screen_name, count: 10});

    var authenticationData = {
      consumer_key : CONSUMER_KEY,
      consumer_secret : CONSUMER_SECRET,
      token: authenticatedData.oauth_token,
      token_secret : authenticatedData.oauth_token_secret
    };

    request.get({url : apiUrl, oauth: authenticationData, json:true}, function(e, r, body){

      var tweets = [];
      for(i in body){
        var tweetObj = body[i];
        tweets.push({text: tweetObj.text});
      }

      var viewData = {
        username: authenticatedData.screen_name,
        tweets: tweets
      };

      res.render("my", viewData);

    });

  });
});

app.listen(3000, function(){
  console.log('Server up: http://localhost:3000');
});
<!-- FileName: main.handlebars-->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Example App</title>
</head>
<body>
    {{{body}}}
</body>
</html>

 

<!-- FileName: home.handlebars-->
<h1>SignIn With Twitter Sample</h1>

<a href="{{url}}">Signin with Twitter</a>

 

<!-- FileName: my.handlebars-->
<h1>Welcome {{username}} </h1>
<h3>Your tweets</h3>
<ul>
  {{#tweets}}
  <li>{{text}}</li>
  {{/tweets}}
</ul>

If you are interested in learning Node.js framework, please consider purchasing the below books for further reference:

  • Professional Node.js
  • Node.js in Action
  • Node.js Receipes

Category: ExpressJS, NodeJSTag: JavaScript Tutorials

About Mohamed Sanaulla

In his day job he works on developing enterprise applications using ADF. He is also the moderator of JavaRanch forums and an avid blogger.

Previous Post: « RESTful Example using ExpressJS + Node.js + MongooseJS
Next Post: Bootstrap Tutorials and Examples »

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

New Features in Spring Boot 1.4

Difference Between @RequestParam and @PathVariable in Spring MVC

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact