Dev bits
Published in

Dev bits

A guide for adding JWT token-based authentication to your single page Node.js applications

Original Photo by Kevin Ku

JSON Web Tokens (JWT)

  • A client sends username/password combination to the server
  • The server validates the authentication
  • If authentication is successful, the server creates a JWT token else establishes an error response
  • On successful authentication, the client gets JWT token in the response body
  • Client stores that token in local storage or session storage.
  • From next time, the client for making any request supplies the JWT token in request headers like this. Authorization: Bearer <jwt_token>
  • Server upon receiving the JWT validates it and sends the successful response else error.

Developing the sample application

  • Express JS — For serving requests
  • jsonwebtoken — For writing and verifying JWT tokens
npm install
touch server.js middleware.js config.js
.
├── config.js
├── middleware.js
├── package-lock.json
├── package.json
└── server.js
└── node_modules
  1. Capture headers with names ‘x-access-token’ or ‘Authorization.’
  2. If the header is in ‘Authorization: Bearer xxxx…’ format, strip unwanted prefix before token.
  3. Using jwt package and secret string, validate the token.
  4. If anything goes wrong, return an error immediately before passing control to next handler.
  5. Export the middleware function for other modules to use.
let token = jwt.sign({username: username},            config.secret,            { expiresIn: '24h' // expires in 24 hours            }            );// return the JWT token for the future API callsres.json({        success: true,        message: 'Authentication successful!',        token: token});
app.post(‘/login’, handlers.login);app.get(‘/’, middleware.checkToken, handlers.index);
app.get(‘/v1/someResource’, middleware.checkToken, handlers.someHandler);
app.post(‘/v1/anotherResource’, middleware.checkToken, handlers.anotherHandler);
node server.js // starts server on 8000 port
curl -X GET http://localhost:8000{"success":false,"message":"Auth token is not supplied"}
curl --header "Content-Type: application/json" \
--request POST \
--data '{"password":"password", "username":"admin"}' \
http://localhost:8000/login
{
"success":true,
"message":"Authentication successful!", "token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNTM0OTMzNTY2LCJleHAiOjE1MzUwMTk5NjZ9.3xOdoxpK8hb42ykjMIl6rwLafB63Y-EQNOO9fFamp68"
}
curl -X GET \
-H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNTM0OTI1MTQwLCJleHAiOjE1MzUwMTE1NDB9.MIcWFBzAr5WVhbaSa1kd1_hmEZsepo8fXqotqvAerKI' \
http://localhost:8000
{
"success": true,
"message": "Index page"
}

--

--

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
Naren Yellavula

Senior Engineer @ Dolby. "To understand the universe, know yourself"