JWT in 300 Seconds
Tijani Ayomide
Posted on March 7, 2022
I have been using Node JS for quite some time now and where ever I go I kept on hearing the word JWT... JWT ... JWT. I asked myself what is this JWT and what is its usage in an application, in this tutorial I will try to explain what JWT is in 300 seconds
What is JWT
JSON Web Token is a proposed Internet standard for creating data with an optional signature
and/or optional encryption whose payload holds JSON that asserts some number of claims.
The tokens are signed either using a private secret or a public/private key._Your Pal WIKI š
So what WIKI is trying to say is JWT stands for āJSON Web Tokenā which is used mostly for authorization and authentication purposes.
letās break this down even further for simplicity's sake...
JSON stands for āJavaScript Object Notationā which is used for storing and transferring data from a server to a web page. An example of JSON
{
"firstName":"Lord",
"lastName":"GhostX"
},
{
"firstName":"Idris",
"lastName":"Olubisi"
},
{
"firstName":"T.Stark",
"lastName":"TheCyberSpirit"
}
Now a Token is used to authenticate and authorize users on the web to make sure that only validated identities can have access. So in a basic sense, JWT is used for transferring user data on the web in a secure way. I made mention of two verbs that we haven't really looked at āAuthorization and Authenticationā.
Authentication
Authentication refers to the process of identifying individual users and validating who they say they are. A simple example is a digital authentication, where the user is asked to fill in his/her username and password credentials and if they match, the user is granted access to the application or website.
Authorization
Authorization happens after the process of authentication. Once a userās identity is authenticated, authorization comes into play and checks if the user has access rights to resources such as databases or other additional personal information. A simple analogy for authorization is ensuring the user that sends a request to your server is the same user that logged in during authentication.
Why Should You Use JWT?
There are several reasons why applications use JSON Web Tokens for authentication:
š JWT is an excellent choice to be passed in HTML and HTTP environments due to its smaller footprint when compared to other types of tokens
š JSON Web Tokens can be signed using a shared secret and also by using public/private key pairs
šŖ It is easier to work with JWT as JSON parsers are standard in most programming languages
š®š”ļø JWT is also suitable for implementing authorization in large-scale web applications
How JWT works
JWT structure consists of:
Header
This consists of two parts: The Type of token (in our case JWT) and the signing algorithm (e.g HS512)
{
"alg": "HS256",
"type": "JWT"
}
Payload
This consists of the claim that provides information about a user who has been authenticated along with information such as token expiration time.
{
"sub": "1234567910",
"name": "John Doe",
"iat": "1516239022"
}
// sub - (subject) refers to who knows this token
// iat - The date and time the token was issued at
Signature
This is the final part, where the token is wrapped in the encoded header and payload alongside the algorithm and a secret
HMAC_SHA256
(
secret,
base64urlEncoding(header) + '.' +
base64urlEncoding(payload)
)
š” If you need to know more about JWT structure in more detail check out this wiki link here
Using JWT in Node JS
Let us create an API that uses JWT authentication to allow users to access certain routes by providing some login credentials.
Prerequisites
To follow along you will need to have:
- A good understanding of Node JS
- Postman and some basic knowledge on how to use Postman
- Working knowledge of JavaScript
We are going to create a Node.js application that includes JWT, that adds a security layer to each route that we define in the application. This is to prevent unauthorized access to users who don't have the right token included in their header request. (like your private snap š )
// Create a dir to house your project
>>> mkdir nodeJWT
>>> cd nodeJWT
>>> touch index.js
We would be working with a single file called index.js so that this app will be simple enough to follow. But before that letās initialize npm so we get our p*ackage.json* file on our directory
npm init -y
// This will prefill and create our package.json file for us
The next thing to do is install the packages we would need for this application
npm i express jsonwebtoken
Once that is done downloading, we can now use these modules /packages inside our index.js directory
// index.js
const express = require('express)
const jwt = require('jsonwebtoken')
const app = express()
app.get('/api', (req, res)=>{
res.send('Welcome to nodeJWT tutorial')
}
app.listen(3000)
npm run index.js
// To start your server
With these, you have your basic web server up and running, now let set up a few endpoints in other to use JWT
// index.js
const express = require('express)
const jwt = require('jsonwebtoken')
const app = express()
app.get('/api', (req, res)=>{
res.send('Welcome to nodeJWT tutorial')
}
app.get('/api/snaps', verifytoken, (req, res)=>{
// jwt.verify(req.token, "secretkey", (err, Data) => {
if (!verifytoken) {
res.sendStatus(403);
}else{
res.json({
message: 'Below are list of your private snapsš„'
Data
})
app.listen(3000)
Like your snaps, you don't want just anyone opening and viewing your private stuff, the verify() method takes in the request token as input and verifies whether it is correct to not, if not we print an error message of (403) Forbidden, otherwise, we print on the screen Below are the list of your private snaps.
Letās define another endpoint to simulate a user(you) trying to get access to your private snaps from your mobile
// index.js
const express = require('express)
const jwt = require('jsonwebtoken')
const app = express()
app.get('/api', (req, res)=>{
res.send('Welcome to nodeJWT tutorial')
}
app.get('/api/snaps', verifytoken, (req, res)=>{
if (!verifytoken) {
res.sendStatus(403);
}else{
res.json({
message: 'Below are list of your private snapsš„'
Data
})
})
app.post('/api/login', (req, res)=>{
const user = {
id: 1,
username: "john",
pin: "12345"
};
jwt.sign({ user: user }, "secretkey", (err, token) => {
res.json({
token
})
})
}
app.listen(3000)
So what we are doing here is sending a POST request with the username and pin then JWT uses the sign() method to create a JSON Web Token for this user and returns the token in JSON string. Now this token created for you will be taken back to the header in the first POST request route and the verifytoken function will take care of the rest.
Speaking of the verifytoken function, we haven't spoken about that yet... like the name suggests this function helps in verifying our token, making sure it exists and is correct.
// index.js
const verifytoken = (req, res, next) =>{
let token
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')){
try{
// Get token from Header
token = req.headers.authorization.split(' ')[1]
// Verify the Token
const decoded = jwt.verify(req.token, 'secretkey')
next()
}
catch(error){
console.log(error)
res.sendStatus(403)
}
}
if (!token){
res.sendStatus(401)
}
}
The function checks the header and makes sure it starts with āBearerā, if it does it would look something like Bearer āyour tokenā then we split the token from bearer using the split(ā ā) method once that is split we now have two separate entities āBearerā and āYour tokenā, you can access your token via its placement in the list [1].
We pass the token to req.token not forgetting to call the next() method in case we have any more middleware to invoke. If the token passed is wrong a status code (401) of Unauthorized is displayed.
Conclusion
In this tutorial, we learned about JWT authorization, and how to develop an API using JWT for authentication in Node.js.
Let's connect šļø
Posted on March 7, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.