Working With JWT(JSON Web Tokens)

Hi, I'm going To be Talking about Working with Json Web Tokens For authentication in node js. Now what is Json Web Tokens? Json Web Token is an Internet proposed standard for creating data with optional signature and/or optional encryption whose payload holds JSON that asserts some number of claims, i.e It is an Api that allows accessing of data based on authorized signatures due to its encryption. It is one of the best way of ensuring authentication and authorization of users in your application.

pic2.PNG

To get Started with using JWT with a node js application you'll have to install the dependency through npm(Node package manager).

nb: We will also be using packages "bycryptjs" to encrypt password passed in from the client

pic1.PNG

We first initialize our node-express application and import the "jwt" package

pic3.PNG

Next we pass in the form fields from the client e.g Name, email,password e.t.c Also Use the FindOne mongoDB method to check if there is an existing user in which if there is we return an error response to the client with its apprpriate status code else We save the data into the mongoose Model.

pic4.PNG

Next We use the byCrypt method genSalt to hash the client password then return a callback which saves the user on success into the database

Now we will be talking on how to Login in to the Signed Up user using jwt

pic5.PNG

In the Login function handler, we take in the email and matching password to authenticate the client, But mind that all fields must be entered in the form which can the validated by using the !(negation) operator to test if both the email and corresponding password was passed through from the client. Also We check the database using the findOne method on the email field to validate if there is an existing email to log in to, if there isn't we exit the handler by returning the appropriate error message and status code to the client.

If all above validation is passed we then use bycrptjs this time to compare the passed in password parameter from the client to see if it matches the decrypted passoword of the found user in the database, if it doesnt matches we return the error back to the client else we then use jwt(JSONWEBTOKEN) to sign the user into a seesion by using a secret config key(Note this config key must be kept in secret and not revealed as it pertains to security), which will then generate a unique token which needs to get passed back to the client with the client data for appropriate authentication and authorization

nb: It is advised to save the token into local Storage by the client side developing once logged to keep track of the token as a session cookie and remove it from local Storage once logged Out.

Thanks for reading my blog