Twitter Authentication
Twitter Authentication
- In this tutorial, we will code Twitter authentication using ExpressJs and passport.js
To start, Firstly register on your Twitter development site and begin with the following steps:
- Go to the Twitter Developer page: Twitter. Sign in using the account.
- Create a new Project and call it whatever you want to.
- Create an app to get access tokens.
- You can use this access token. Now click on 'App Setting'.
- Click on Setup. And fill in the required details.
- Note: http://www.localhost:3000 works but not http://localhost:3000.
So, addwww in
both websites.
- Click on Save and you can access the client ID and client Secret.
-
Now let's move to the code part. here is an application file structure.
- Install passport and other modules in the project by the following command:
npm install passport passport-twitter, express, express-session,ejs
- For frontend part, views\pages\header.ejs and views\pages\home.ejs
In header.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<title>ExpressJS: login with Twitter</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="/public/css/style.css" type="text/css" media="screen">
</head>
<body>
<main id="site">
In home.ejs
<%- include('header') %>
<section class="jumbotron container mt-5">
<% if (!user) { %>
<h1>Welcome!</h1>
<p class="mt-5"><a href="/login/twitter" class="loginBtn loginBtn--twitter">Login with Twitter</a></p>
<% } else { %>
<h1>Hello, <%= user.displayName %></h1>
<p class="mt-5"><a href="/logout" class="btn btn-primary">Logout</a></p>
<% } %>
</section>
<%- include('footer') %>
In style.css
html, body {
background: #EEF2F7;
margin: 0;
padding: 0;
height: 100vh;
}
#site {
height: 100vh;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.btn-primary,
.btn-primary:hover,
.btn-primary:active {
border-radius: 0;
background-color: #fff;
color: #000;
text-decoration: none;
border: 2px solid;
min-width: 13em;
text-transform: uppercase;
letter-spacing: 2px;
text-shadow: none;
}
.btn-primary:hover {
background-color: #000;
color: #fff;
}
.jumbotron {
background: #fff;
text-align: center;
width: 30vw;
max-width: initial;
box-shadow:
0 2.8px 2.2px rgba(0, 0, 0, 0.034),
0 6.7px 5.3px rgba(0, 0, 0, 0.048),
0 12.5px 10px rgba(0, 0, 0, 0.06),
0 22.3px 17.9px rgba(0, 0, 0, 0.072),
0 41.8px 33.4px rgba(0, 0, 0, 0.086),
0 100px 80px rgba(0, 0, 0, 0.12);
}
@media screen and (max-width: 640px) {
#site {
display: block;
}
.jumbotron {
width: auto;
}
}
.loginBtn,
.loginBtn:hover {
box-sizing: border-box;
position: relative;
/* width: 13em; - apply for fixed size */
margin: 0.2em;
padding: 0 15px 0 46px;
border: none;
text-align: left;
line-height: 34px;
white-space: nowrap;
border-radius: 0.2em;
font-size: 16px;
color: #FFF;
display: inline-block;
text-decoration: none;
}
.loginBtn:before {
content: "";
box-sizing: border-box;
position: absolute;
top: 0;
left: 0;
width: 34px;
height: 100%;
}
.loginBtn:focus {
outline: none;
}
.loginBtn:active {
box-shadow: inset 0 0 0 32px rgba(0,0,0,0.1);
}
/* Twitter */
.loginBtn--twitter {
background-color: #1bb2e9;
background-image: linear-gradient(#1bb2e9, #1BAEE4);
/*font-family: "Helvetica neue", Helvetica Neue, Helvetica, Arial, sans-serif;*/
text-shadow: 0 -1px 0 #1BAEE4;
}
.loginBtn--twitter:before {
border-right: #1BAEE4 1px solid;
background: url(images/twitter.png) 6px 6px no-repeat;
}
.loginBtn--twitter:hover,
.loginBtn--twitter:focus {
background-color: #1BAEE4;
background-image: linear-gradient(#1BAEE4, #1bb2e9);
}
Now moving to the server part
- Now for routes In routes/index.js
'use strict';
const express = require('express');
const passport = require('passport');
const router = express.Router();
router.get('/', (req, res, next) => {
const { user } = req;
res.render('home', { user });
});
router.get('/login/twitter', passport.authenticate('twitter'));
router.get('/logout', (req, res, next) => {
req.logout();
res.redirect('/');
});
router.get('/return',
passport.authenticate('twitter', { failureRedirect: '/' }),
(req, res, next) => {
res.redirect('/');
});
module.exports = router;
- clientID, clientsecret, and callback URL are mentioned in .env
TWITTER_CONSUMER_KEY="YOUR_TWITTER_CONSUMER_KEY"
TWITTER_CONSUMER_SECRET="YOUR_CONSUMER_SECRET"
SESSION_SECRET="HelloTwitter"
- Lastly, for the server there we use passport and express to authenticate, In index.js:
'use strict';
require('dotenv').config();
const path = require('path');
const express = require('express');
const passport = require('passport');
const { Strategy } = require('passport-twitter');
const { TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, SESSION_SECRET } = process.env;
const port = process.env.PORT || 3000;
const app = express();
const routes = require('./routes');
passport.use(new Strategy({
consumerKey: TWITTER_CONSUMER_KEY,
consumerSecret: TWITTER_CONSUMER_SECRET,
callbackURL: 'http://www.localhost:3001/oauth/twitter'
},
(accessToken, refreshToken, profile, cb) => {
return cb(null, profile);
}));
passport.serializeUser((user, cb) => {
cb(null, user);
});
passport.deserializeUser((obj, cb) => {
cb(null, obj);
});
app.set('view engine', 'ejs');
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use(require('express-session')({ secret: SESSION_SECRET, resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', routes);
app.listen(port);
- Now start the server by command and the server will start at port 3000: http://localhost:3000/
npm start
Thus, Twitter authentication can be added to any website or app using Expressjs and passport.js.