Json Web Token Authentication JWT Explained Securing API

Video Tutorial


JSON Web Token is a technique for transmitting JSON data Between two parties securely where it uses digital signing for data verification it is widely used for API since it uses a very secure method for encrypting data and self-contained token verification, so it doesn’t keep track of the user’s token on the server database unlike regular token based authentication JWT allow you to validate the user’s token on the go without caching the token on the Server Database which makes it very flexible and performance friendly in terms of making fast and scalable apps, So Enough Talking about Academic stuff let’s see How it actually works.

How JWT Works?

The main Idea behind JWT is to have a self-contained token generated on each user login using the user’s credentials, then depending on your app you can store this token on a Cookie or the local storage for allowing the user to access the server resources after he logs in and that by sending the token on each request made by the user and make the server verifies the token validity in order to allow or not the user to access a certain server resource or edit/add data, it is very simple actually.

The generated JWT Token is Composed of a Three major parts (Header, Payload, and Signature) where the Header holds the Encryption and Hashing Algorithms used to sign the token, the Payload holds the user’s data (credentials) (Username, Email Full Name) Password is not included unless you have used a none reversible Hashing algorithm, and the Signature is a Passcode Specified by you to secure the token also used to encrypt and decrypt the token.

And that is why it is a Self-Contained Technique since it allows you to validate the token without the actual token stored on the server side since the token holds all the needed information for double checking (Header, Payload, and Signature).

Real World API Using JWT

JWT Library or Package is available for pretty much every programming language, in this example, we are going to use node js for server and API creating.

If you would like to better understand node js and Basic Server Creating I really recommend checking this Course Series.

We firstly Setup the Server using express and listen on a random port let’s say (PORT 3000), also we create a simple route that will allow users to access some kind of a private data only the specified user should be able to access it and view (route: /userData).

/* Make Sure to create the Server and Use the Body parser */
//Get Some Data From the Server
const data = "This is a Private Data stored on the Database Server Side, User Protected";
app.route('/userData').get(login_required, (req, res) => {
    return res.json({ status: 'Success', data: data });
//The login required will prevent from accessing the routes and allow only logged in users 
//And listen on Port 
app.listen(port, () => { console.log("Server Stared on Port: ' + port); })

Now we use a middleware in order to validate the JWT token on request if it is available else we will block the user from accessing the private data and force him/her to sign in first, So we create the Validation Middleware

app.use((req, res, next) => {
    //Check for authorization filed on the headers (which holds the token)
    if (
        req.headers &&
        req.headers.authorization &&
        req.headers.authorization.split(" ")[0] == "JWT"
    ) {
        //We Verify the Token with the PassCode (JWTSIGNATURE)
            req.headers.authorization.split(" ")[1],
            (err, decode) => {
                if (err) req.user = undefined; ///< Token Mismatch No 
                req.user = decode;
    } else {
        req.user = undefined;
//Login Required (For those how are not Logged in (GUESTS))
//For Allowing Only Logged in User to Access some routes we check if the user object does exists or //it is undefined, since we are validating the user on the above middle ware
function login_required(req, res, next) {
    if (req.user) {
    } else {
        return res.status(401).json({
            message: "Unauthorized User, Please Sing In First"

Now we are double checking for the Token we also need to allow the user to sing in, so create another route which receives a post request with the user credentials (in this case we will store the user’s credentials on a local variable) for a real app you may use this with a Database.

Now try to sing in using the sing_in route put the above credentials and you should get a success response with your token copy the token and try to put under the headers on the authorization filed for accessing the user’s data by submitting the route (/userData), the authorization filed may look like

"authorization": "JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"

Now if have done everything right, this should allow you to view the private data stored on the server and that is using a JWT Authentication Technique, very well.

What’s Next

You can use the JSON Web Token (JWT) Authentication Technique for more complicated tasks, but that was a very basic thing you can do and actually the most important part of how JWT Works.

No Comments Yet