The web is fundamentally about people and the huge popularity of Social Media has echoed this notion. Social media is one of the must go-to places for everybody who surfs online. At times, we can’t decide what to surf on the internet unless we check one of the social media sites. Most of the corporations use social media to post their news, updates and even for important announcements. Social media integration on websites also gives the viewer an impression of the social presence of the company or, the individual.
More consumers are connected than ever before, and if you are not engaging with them via social media, you are wasting an opportunity.
Every social media site like Twitter, Facebook etc. provides APIs using which, one can view or post updates via an app or, another site. The app or, site using social media has to be authenticated and should have enough rights to do so. For this, the site should be authenticated via OAuth and use the OAuth token for each interaction. Handling the task of authentication and making sure to send the security details on each interaction is made possible via libraries like hello.js .
In this article, we will see how hello.js can be used to fetch feeds from some of the most widely used social media sites and display them on a webpage using Bootstrap and jQuery. This article was technically reviewed by Ravi Kiran.
This article is published from the DNC Magazine for .NET Developers and Architects. Download this magazine from here [Zip PDF] or Subscribe to this magazine for FREE and download all previous and current editions
Understanding OAuth
If you haven’t heard of OAuth or OpenID, you have most certainly used it in day to day life. Have you provided your google username/password and logged in to StackOverflow OR used your WordPress.com account to post comments on someone’s blog OR used third party Twitter clients whom you have given permission to use your Twitter account OR used Facebook to post comments on some tech blog site? If answer to any of the above is a YES, you have seen OAuth or OpenID in action. As defined on Techopedia – “OAuth is an open-source protocol that enables users to share their data and resources stored on one site with another site, under a secure authorization scheme, based on a token-based authorization mechanism.
I am taking an excerpt from an article written by Sumit Maitra where he explains OAuth accurately.
Basic premise of OAuth is, instead of having to remember a different username and password for every application we visit on the internet, we have a dedicated Authentication provider with whom we can register our user name and password. Applications (aka Relying Party) redirect us to this provider for authentication and after a successful authentication; the provider passes back a token to the replying party who initiated the request. The target Application then uses the token to verify the identity of the person and provide further access to Application Features.
OAuth was initiated by Twitter when they were working on building their OpenID implementation for Twitter API. Their need was more towards controlling what features to make available based on Authentication Types offered at the Provider and those sought by the relying party. For example when a Relying party signs up for Twitter Authentication access, they can request for a Read-Only connection (this gives them read permissions to a user’s stream), a Read/Write connection (this gives them read and write permissions on a user’s stream) and a Read/Write with Direct Messages connection (giving them maximum possible access to user’s data). Thus, when a user authenticates with Twitter over OAuth, they are told exactly what kind of access they are providing.
On the other hand, OpenID simply ensures that you are who you claim to be by verifying your username and password. It has no way of controlling feature access.
In even simpler terms and for the sake of explanation, OpenID is about Authentication, OAuth is about Authentication and Authorization (for features at the Provider).
Shown here is an architecture of External Authentication using OAuth 2.0 –
The diagram above demonstrates the Authentication process for an OAuth provider. The overall workflow is as follows:
1. Application (Relying Party) registers with OAuth provider and obtains an Application specific key (secret). This is a one-time process done offline (not shown in the image).
2. Next the Application (Relying Party) has to pass the Application key to the provider every time it intends to authenticate someone.
3. User of the Relying Party needs to be registered with the Provider (again a one-time offline process)
4. Every authentication request directs the user to the Auth Provider’s site. The user enters the Username and Password that they obtained by creating an account with the provider. The Provider verifies the account credentials, then it matches the Application Key and provides a token back to the Relying Party with which only the Authorized actions can be performed.
For more info see: http://oauth.net
Connect to Twitter, Facebook and Instagram - The implementation
With OAuth knowledge under our belt, we will write code that allows us to connect to three social media sites - Twitter, Facebook and Instagram using only JavaScript .
To help us with this objective, we’ll use a very useful library from Andrew Dodson called Hello.js (http://adodson.com/hello.js/).
Hello.js is a client-side JavaScript SDK for authenticating with OAuth2 (and OAuth1 with a oauth proxy) web services and querying their REST APIs. HelloJS standardizes paths and responses to common APIs like Google Data Services, Facebook Graph and Windows Live Connect. It's modular, so that list is growing. No more spaghetti code!
Hello.js is a library that saves us from all the complex stuff behind an OAuth authentication, presenting us with a simple model and some easy to use API’s.
Let’s create a website using the Free Visual Studio Community Edition or Visual Studio Code editor and use Hello.js in it. Open Visual Studio and create a new empty website.
Visual Studio automatically provides a local server to host our website. This is a necessary step because, as stated previously, OAuth is a dialogue between two servers.
Now that our local server is setup, we can create our OAuth clients on Twitter, Facebook and Instagram. Normally these actions can be performed in the “Developer” section of many social media sites.
At the end of the process, we would have registered a trusted application with a Client ID value, necessary for OAuth connections.
Generating Keys from Social Media sites
For Twitter:
1. Go to http://dev.twitter.com
2. Login with your Twitter account and select “My applications” in your avatar menu
3. Hit “Create a new application”
Add some basic information like “Application Name” and “Description” and some important data like the “Website” and “Callback URL”. Fill these fields with our website data as shown here:
At the end of the registration process, Twitter will release an API Key and an API Secret for your app:
For Instagram:
1. Go to https://instagram.com/developer
2. Login with your Instagram account and hit “Register Your Application”
3. Hit “Register a New Client”
Here add some basic information like “Application Name” and “Description” and some important data like the “Website URL” and “Redirect URI(s)”. Fill these details with our website data as shown here
The Redirect URI(s) field points to a redirect page. We will create the redirect.html page shortly.
Don’t forget to “Disable Implicit OAuth” in the Security tab in order for the app to work correctly in our scenario:
At the end of the registration process, Instagram will release an API Key and an API Secret for your app.
For Facebook:
1. Go to http://developer.facebook.com
2. Login with your Facebook account and select “My applications” on your avatar menu
3. Hit “Add a New App”
Here add some basic information like “Application Name” and “Description” and some important data like the “Site URL”. Fill these details with our website data as follows:
At the end of the registration process, Facebook will release an API Key and an API Secret for your app:
For OAuth1 or OAuth2 authentication with explicit grant services like Twitter, we need to use an OAuth Proxy service exposed by Hello.js.
For Hello.js proxy registration:
1. Go to https://auth-server.herokuapp.com
2. Login using a supported provider
3. Add your app to the “Managed apps” list
Once our setup is now complete, it is time to see some code.
The JavaScript code
In order to write code that can be reused in many situations, we will write a jQuery plugin. For those who are not familiar with jQuery plugin authoring and usage, you can refer to these articles on DotNetCurry https://www.dotnetcurry.com/jquery/1069/authoring-jquery-plugins and https://www.dotnetcurry.com/jquery/1109/jquery-plugin-for-running-counter.
Data displaying
Let us create a new page called Plugin.html that will include all necessary plugins and add references to some JavaScript and CSS code. In the <head> section, add the following reference:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/hellojs/1.6.0/hello.all.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/masonry/3.3.1/masonry.pkgd.min.js"></script>
<script type="text/javascript" src="jQuery.socialmedia.js"></script>
<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link href="jQuery.socialmedia.css" rel="stylesheet" />
And add an empty div and two buttons on the page as shown here. The buttons and page are styled using Bootstrap:
<body>
<div class="container-fluid">
<h1>My social media accounts!</h1>
<button class="btn btn-primary" id="connect">Connect to socials</button>
<button class="btn btn-primary" id="fetch">Get data!</button>
<div id="mySocialMedia" style="margin-top: 20px"></div>
</div>
</body>
Plugin initialization
The following script runs in the document.ready() event on the “#connect” button click event handler and fills the div “mySocialMedia” with user profile information coming from Twitter, Instagram and Facebook.
$("#mySocialMedia").socialmedia({
twitter: {
enabled: true,
key: TWITTER_CLIENT_ID
},
instagram: {
enabled: true,
key: INSTAGRAM_CLIENT_ID
},
facebook: {
enabled: true,
key: FACEBOOK_CLIENT_ID
}
});
In the plugin call, we must change TWITTER_CLIENT_ID, INSTAGRAM_CLIENT_ID and FACEBOOK_CLIENT_ID keys, with the API keys (NOT with the secret key), as provided in the registrations we performed on individual social media sites.
The Redirection page
Now add a new page called redirect.html. This page is necessary for OAuth in order to work correctly, and is the same page we have defined previously in the Twitter and Instagram app registrations.
The redirect.html page is handled by Hello.js and is purely to indicate redirection.
<html>
<head>
<title>Hello, redirecting...</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
</head>
<body>
<div class="loading"><span>•</span><span>•</span><span>•</span></div>
<h2>Please close this window to continue.</h2>
<script>
window.onbeforeunload = function () {
document.getElementsByTagName('h2')[0].innerHTML = "Redirecting, please wait";
}
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/hellojs/1.6.0/hello.all.min.js"></script>
</body>
</html>
HelloJs initialization and Socials login
Let’s see the plugin code - the core of this article. Inside the Init() function of the plugin, we can see the Hello.js integration. The code based on the options passed, can activate and login to all supported social networks (Instagram, Twitter and Facebook) and display login information.
// If twitter is enabled initalize hello js for it
if (_opts.twitter.enabled) {
hello.init({
twitter: _opts.twitter.key
},
{
redirect_uri: 'redirect.html', // Redirected page
oauth_proxy: 'https://auth-server.herokuapp.com/proxy' // Since Twitter use OAuth2 with Explicit Grant we need to use hello.js proxy
});
// Twitter connection handler
setTimeout(function () { connectToTwitter($twitterEl); }, 2000);
}
// If instagram is enabled initalize hello js for it
if (_opts.instagram.enabled) {
hello.init({
instagram: _opts.instagram.key
},
{
redirect_uri: 'redirect.html',
});
// Instagram connection handler
setTimeout(function () { connectToInstagram($instagramEl); }, 2000);
}
// If facebook is enabled initalize hello js for it
if (_opts.facebook.enabled) {
hello.init({
facebook: _opts.facebook.key
},
{
redirect_uri: 'redirect.html',
});
// Facebook connection handler
setTimeout(function () { connectToFacebook($facebookEl); }, 2000);
}
}
Now that we are logged in to our favorite social media sites, the next step is to fetch our feeds from these socials!
Social Data fetching
The script we will see shortly runs in document.ready() event on the “#fetch” button click event handler and fills the div “mySocialMedia” with data fetched from Twitter, Instagram and Facebook.
The fetch method uses Hello.js in order to simplify all the OAuth request to each social site, with some very simple API’s.
For demo purposes, all the data fetched from the socials are added in an array, shuffled and displayed in a responsive grid system using Masonry (http://masonry.desandro.com/) from David DeSandro.
Let’s see the plugin code. Inside the fetch() function of the plugin, we can see the Hello.js and Masonry integration. Since each response from the socials is asynchronous, we will use jQuery’s deferred API. Deferred is an important concept and if you are not familiar with it, check: https://api.jquery.com/jquery.deferred/ and https://www.dotnetcurry.com/jquery/1022/jquery-ajax-deferred-promises
The code sends request to each social and concats and shuffles the response inside an array. The social data fetch code shown here is only for Twitter, however the complete code will contain details for all the three social media sites we are connecting to.
First we will create three Deferred objects and on completion, call the rendering function inside the main div.
// Deferred objects
var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();
// Waiting for the deferred completion
$.when(d1, d2, d3).done(function (v1, v2, v3) {
// Build one concatenated array with the result of each data fetch result
fecthedData = fecthedData.concat(v1);
fecthedData = fecthedData.concat(v2);
fecthedData = fecthedData.concat(v3);
// Schuffle the array result
fecthedData = shuffleArray(fecthedData);
// Render the mixed fetched data
renderFetchedData(_$this, fecthedData);
});
fetchTwitterData(_opts.twitter, d1);
fetchInstagramData(_opts.instagram, d2);
fetchFacebookData(_opts.facebook, d3);
}
Since we are logged in to Twitter in the Init() code, if twitter integration is enabled in the plugin initialization, we get its instance and fetch data from twitter. The fetch is done using Hello.js that simplifies this operation. The core functionality of the app requests twitter for the 50 latest tweets (or a number you chose) and loads them in the “tweet” array. When the data fetch is completed, the deferred object “resolve” method is called and the operation continues.
function fetchTwitterData(o, d) {
if (!o.enabled) {
d.resolve([]);
return;
}
// Twitter instance
var twitter = hello('twitter');
twitter.api('twitter:/me/share', { limit: o.maxElements }, function (r) {
var tweets = [];
for (var i = 0; i < r.data.length; i++) {
var o = r.data[i];
tweets.push({ social: 'twitter', text: o.text });
};
d.resolve(tweets);
});
}
Result
Run the page and hit “Connect to socials” and then click on “Get data!” buttons. We will see our social profile images and then our social media data (tweets, facebook posts and instagram images) displayed.
Conclusion
Social media integration is one of the key aspects for several web sites. A number of websites display their media feeds on their pages to show the visitors their active presence on the social media. Hello.js makes this process easier by providing an easy to use Authentication API. This article covered a simple example of the integration and I hope you found it useful enough to use it on your own websites.
Download the entire source code of this article (Github)
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Irvin Dominin is currently working as lead of a technical team in SISTEMI S.p.A. (Turin, Italy) on .NET, jQuery and windows Projects. He is an
active member on StackOverflow. You can reach him at: irvin[dot]dominin[attherate]gmail[dot]com or on
LinkedIn