Every web application and API uses a form of authentication to protect resources and restrict them to only verified users. We’ll be going through how to create authentication for an API using JWT’s (JSON Web Tokens) and a package passport. Let’s take a brief introduction into how they work.
According to JWT.IO
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.
Now JWT’s are secure because they are digitally signed and if the information contained within is tampered in any way, it renders that token invalid. We’ll look at how this is made possible later on. JWT’S consist of three parts seperated by dots.
Header : this contains the type of algorithm used to verify the token and the type of token e.g
{
"type" : "JWT",
"alg" : "HS256"
}
*Payload *: contains the claims. Claims are information about the user together with other additional metadata e.g
{
id : 1
name : 'devgson'
iat : 1421211952
}
Note : iat
is a metadata indicating the date and time the token was signed. More information about metadata can be found here.
Signature : The signature encodes the information in the header and payload in base64
format together with a secret key. All this information is then signed by the algorithm specified in the header eg HMACSHA256. The signature verifies that the message being sent wasn’t tampered along the way.
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret
)
Note : JWT’s should not be used to transfer/store secure information cause anyone that manages to intercept the token can easily decode the header and payload within, it’s just encoded inbase64
format after all. All the signature does is verify that the token hasn’t been tampered in any way. It doesn’t stop the token from being tampered with. However, there are extra security measures that can be put in place to achieve a higher level of security. For a broad and in-depth explanation of JWT’s, read this book
Passport is an authentication middleware, it is used to authenticate requests, It makes use of strategies eg Local strategy or with the rise of social networking, single sign-on using an OAuth provider such as facebook or twitter. Applications can choose which strategies they want to employ and there are individual packages for each strategy.We’ll be using the local(email/password) strategy in this tutorial. More info about passport and it’s available strategies could be found here. Now let’s get started.
Lets create a folder structure for the files we’ll be using :
-model
---model.js
-routes
---routes.js
---secure-routes.js
-auth
---auth.js
-app.js
-package.json
Install the necessary packages
$ npm install --save bcrypt body-parser express jsonwebtoken mongoose passport passport-local passport-jwt
bcrypt
: for hashing user passwords, jsonwebtoken
: for signing tokens, passport-local
: package for implementing local strategy, passport-jwt : middleware for getting and verifying JWT’s. Here’s how our application is going to work :
First of all, let’s create the user schema. A user should only provide email and password, that would be enough information.
model/model.js
const mongoose = require('mongoose')
const bcrypt = require('bcrypt');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
email : {
type : String,
required : true,
unique : true
},
password : {
type : String,
required : true
}
});
...
Now we don’t want to store passwords in plain text because if an attacker manages to get access to the database, the password can be easily read so we want to avoid this. We’ll make use of a package called ‘bcrypt’ to hash user passwords and store them safely.
model/model.js
....
//This is called a pre-hook, before the user information is saved in the database
//this function will be called, we'll get the plain text password, hash it and store it.
UserSchema.pre('save', async function(next){
//'this' refers to the current document about to be saved
const user = this;
//Hash the password with a salt round of 10, the higher the rounds the more secure, but the slower
//your application becomes.
const hash = await bcrypt.hash(this.password, 10);
//Replace the plain text password with the hash and then store it
this.password = hash;
//Indicates we're done and moves on to the next middleware
next();
});
//We'll use this later on to make sure that the user trying to log in has the correct credentials
UserSchema.methods.isValidPassword = async function(password){
const user = this;
//Hashes the password sent by the user for login and checks if the hashed password stored in the
//database matches the one sent. Returns true if it does else false.
const compare = await bcrypt.compare(password, user.password);
return compare;
}
const UserModel = mongoose.model('user',UserSchema);
module.exports = UserModel;
We’ll use the passport local strategy to create middleware that will handle user registration and login. This will then be plugged into certain routes and be used for authentication.
auth/auth.js
const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const UserModel = require('../model/model');
//Create a passport middleware to handle user registration
passport.use('signup', new localStrategy({
usernameField : 'email',
passwordField : 'password'
}, async (email, password, done) => {
try {
//Save the information provided by the user to the the database
const user = await UserModel.create({ email, password });
//Send the user information to the next middleware
return done(null, user);
} catch (error) {
done(error);
}
}));
//Create a passport middleware to handle User login
passport.use('login', new localStrategy({
usernameField : 'email',
passwordField : 'password'
}, async (email, password, done) => {
try {
//Find the user associated with the email provided by the user
const user = await UserModel.findOne({ email });
if( !user ){
//If the user isn't found in the database, return a message
return done(null, false, { message : 'User not found'});
}
//Validate password and make sure it matches with the corresponding hash stored in the database
//If the passwords match, it returns a value of true.
const validate = await user.isValidPassword(password);
if( !validate ){
return done(null, false, { message : 'Wrong Password'});
}
//Send the user information to the next middleware
return done(null, user, { message : 'Logged in Successfully'});
} catch (error) {
return done(error);
}
}));
....
Now that we have middleware for handling registration and login, let’s create routes that’ll use this middleware.
routes/routes.js
const express = require('express');
const passport = require('passport');
const jwt = require('jsonwebtoken');
const router = express.Router();
//When the user sends a post request to this route, passport authenticates the user based on the
//middleware created previously
router.post('/signup', passport.authenticate('signup', { session : false }) , async (req, res, next) => {
res.json({
message : 'Signup successful',
user : req.user
});
});
...
When the user logs in, the user information is passed to our custom callback which in turn creates a secure token with the information. This token is then required to be passed along as a query parameter when accessing secure routes(which we’ll create later).
routes/routes.js
....
router.post('/login', async (req, res, next) => {
passport.authenticate('login', async (err, user, info) => { try {
if(err || !user){
const error = new Error('An Error occured')
return next(error);
}
req.login(user, { session : false }, async (error) => {
if( error ) return next(error)
//We don't want to store the sensitive information such as the
//user password in the token so we pick only the email and id
const body = { _id : user._id, email : user.email };
//Sign the JWT token and populate the payload with the user email and id
const token = jwt.sign({ user : body },'top_secret');
//Send back the token to the user
return res.json({ token });
}); } catch (error) {
return next(error);
}
})(req, res, next);
});
module.exports = router;
Note : We set { session : false }
because we don’t want to store the user details in a session. We expect the user to send the token on each request to the secure routes. This is especially useful for API’s, it can be used to track users, block , etc… but if you plan on using sessions together with JWT’s to secure a web application, that may not be a really good idea performance wise, more details about this here.
So now we’ve handled user signup and login, The next step is allowing users with tokens access certain secure routes, but how do we verify that the token sent by the user is valid and hasn’t been manipulated in some way or just outright invalid. Let’s do that next.
auth/auth.js
....
const JWTstrategy = require('passport-jwt').Strategy;
//We use this to extract the JWT sent by the user
const ExtractJWT = require('passport-jwt').ExtractJwt;
//This verifies that the token sent by the user is valid
passport.use(new JWTstrategy({
//secret we used to sign our JWT
secretOrKey : 'top_secret',
//we expect the user to send the token as a query paramater with the name 'secret_token'
jwtFromRequest : ExtractJWT.fromUrlQueryParameter('secret_token')
}, async (token, done) => {
try {
//Pass the user details to the next middleware
return done(null, token.user);
} catch (error) {
done(error);
}
}));
Note : If you’ll need extra or sensitive details about the user that are not available in the token, you could use the _id available on the token to retrieve them from the database.
Now lets create some secure routes that only users with verified tokens can accces.
routes/secure-routes.js
const express = require('express');
const router = express.Router();
//Lets say the route below is very sensitive and we want only authorized users to have access
//Displays information tailored according to the logged in user
router.get('/profile', (req, res, next) => {
//We'll just send back the user details and the token
res.json({
message : 'You made it to the secure route',
user : req.user,
token : req.query.secret_token
})
});
module.exports = router;
So now we’re all done with creating the routes and authentication middleware, let’s put everything together and then test it out.
app.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passport = require('passport');
const app = express();
const UserModel = require('./model/model');
mongoose.connect('mongodb://127.0.0.1:27017/passport-jwt', { useMongoClient : true });
mongoose.connection.on('error', error => console.log(error) );
mongoose.Promise = global.Promise;
require('./auth/auth');
app.use( bodyParser.urlencoded({ extended : false }) );
const routes = require('./routes/routes');
const secureRoute = require('./routes/secure-route');
app.use('/', routes);
//We plugin our jwt strategy as a middleware so only verified users can access this route
app.use('/user', passport.authenticate('jwt', { session : false }), secureRoute );
//Handle errors
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({ error : err });
});
app.listen(3000, () => {
console.log('Server started')
});
Now that we’ve put everything together, let’s use postman to test our API authentication. First of all we’ll have to signup with an email and password. We can send over these details through the Body
of our request. When that’s done, click the send button to initiate the POST
request.
We can see the password is encrypted, therefore anyone with access to the database will have access to only the hashed password, we added ten(10) salt rounds to increase the security. You can read more about this here. Let’s now login with the credentials and get our token. Visit the /login
route, passing the email and password you used previously and then initiate the request.
Now we have our token, we’ll send over this token whenever we want to access a secure route. Let’s try this by accessing a secure route user/profile
, we’ll pass our token in a query parameter called secret_token
, The token will be collected, verified and we’ll be given access to the route if it’s valid.
As you can see, the valid token enables us gain access to the secure route. You could go ahead and try accessing this route but with an invalid token, the request will return an Unauthorized
error.
JSON web tokens provide a secure way for creating authentication. An extra layer of security can be added by encrypting all the information within the token, thereby making it even much more secure.
#node-js #api #javascript