Crowdbotics
Published in

Crowdbotics

Add Instagram Login To Your NodeJS App Using PassportJS

Learn how Instagram’s API works with Oauth, and implement the full login flow using MongoDB.

How does Instagram login work?

Instagram uses Oauth2.0 for authentication and authorization. Instagram login can be implemented for conventional apps and serverless apps. We will quickly look into both methods.

Pre-requisite

  • Node js
  • Express JS
  • Passport JS
  • Register an App with Instagram

Register an App with Instagram

Before moving forward, we need to register a client with Instagram.

http://localhost:3000/auth/instagram/callback

Captcha problem

While registering a new client app, you might face a captcha problem. To solve that, you can use the Diable Content Security plugin.

Login using Instagram

We will use passport.js, PasspostJS is a go-to library to implement different types of authentications into your application. It’s a middleware for your NodeJs app.

express insta-auth
npm install passport-instagram
var Instagram = require('passport-instagram');
const InstagramStrategy = Instagram.Strategy;

Initialize Passport JS

We will now initialize PassportJs. If your application uses session (most probably it does) then you need to use passport session too. PassportJS will serialize and deserialize user instances to and from the session. Make sure to use express.session() before passport.session() to ensure that the login session is restored in the correct order.passport.session() alters the req object and change the 'user' value that is currently the session id (from the client cookie) into the deserialized user object. In case of logout, passportJs simply removes users information using deserializeUser.

app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser((user, done) => {
done(null, user)
})
passport.deserializeUser((user, done) => {
done(null, user)
})

Passport Instagram Strategy

Different application such as Instagram, Twitter or Google can have different authentication methods. PassposJS bundles different authentication mechanisms into modules which are called as strategies. We are using Instagram strategy for our application.

passport.use(new InstagramStrategy({
clientID: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET",
callbackURL: "YOUR_CALL_BACK_URL"
}, (accessToken, refreshToken, profile, done) => {

}))
passport.use(new InstagramStrategy({
clientID: "YOUR_CLIENT_ID",
clientSecret: "YOUR_CLIENT_SECRET",
callbackURL: "YOUR_CALL_BACK_URL"
}, (accessToken, refreshToken, profile, done) => {
User.findOne({ 'instagram.id': profile.id }, function(err, user) {
if (err) return callback(err);
if (user) {
return done(null, user); // Check if user already exists
}
const {
id,
full_name,
username,
profile_picture,
bio,
website,
counts: { media, follows, followed_by }
} = profile._json.data;
const new_user = new User({
instagram: {
id,
accessToken,
full_name,
username,
profile_picture,
bio,
website,
counts: {
media,
follows,
followed_by
}
}
});
new_user.save(function(err, user) { //saving a new user into mongo
if (err) {
throw err;
}
return done(null, user);
});
});
}))

Routes Configuration

Now we will configure some routes to create a login flow.


app.get('/auth/instagram', passport.authenticate('instagram'));
app.get(
'/auth/instagram/callback',
passport.authenticate('instagram', {
successRedirect: '/profile',
failureRedirect: '/login'
})
);

Under the hood

Let’s see what's happening under the hood? Once you call the passport authentication, it will go to Instagram, once user finished, Instagram will hit our callback URL with a code, this code will be exchange for access_token on the server side by PassportJS. If we don’t use passportJS, we need to do this ourself. PassportJS is internally performing authorization and authentication for us.

const instaConfig = {
clientID: CLIENT_ID,
clientSecret: CLIENT_SECRET,
callbackURL: CALLBACK_URL
};
const instagramInit = function(accessToken, refreshToken, profile, callback) {
User.findOne({
'instagram.id': profile.id
}, function(err, user) {
if (err) return callback(err);
if (user) {
return callback(null, user); // Check if user already exists
}
const {
id,
full_name,
username,
profile_picture,
bio,
website,
counts: {
media,
follows,
followed_by
}
} = profile._json.data;
const new_user = new User({
instagram: {
id,
accessToken,
full_name,
username,
profile_picture,
bio,
website,
counts: {
media,
follows,
followed_by
}
}
});
new_user.save(function(err, user) {
if (err) {
throw err;
}
return callback(null, user);
});
});
};
passport.use(new InstagramStrategy(instaConfig, instagramInit));
app.get('/profile', ensureAuthenticated, (request, response) => {
const { instagram } = request.user;
response.render('profile', { user: instagram });
});
function ensureAuthenticated(request, response, next) {
if (request.isAuthenticated()) {
return next();
}
response.redirect('/');
}
app.get('/profile', ensureAuthenticated, (request, response) => {
const { instagram } = request.user;
response.render('profile', { user: instagram });
});
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});

Full working code

You can check the full code here.

Conclusion

You don’t need to use PassportJS for this purpose but it’s one of the most famous library in the node ecosystem with more than 120k downloads weekly. It provides more than 500 strategies for authentication, hence become an all-around solution for your authentication management.

Extra sauce (Instagram Private APIs)

Apart from official APIs to integrate your application with Instagram developers created their own libraries to work with Instagram without using official APIs. (Instagram APIs were very poor in the beginning, so many developers created workarounds). You can check out some examples here and here.

Notes

Instagram started deprecating its API support and the current version of API will be fully deprecated till 2020 😐. You can access Instagram API's through the Facebook developer portal, though they are currently supporting only business accounts. Also, Instagram recently launched Instagram Graph API (access through the Facebook developer portal).

Building A Web Or Mobile App?

Crowdbotics is the fastest way to build, launch and scale an application.

--

--

The fastest way to build your next app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store