DEV Community

Tejaswa Hinduja
Tejaswa Hinduja

Posted on

JWT Authentication in typescript,express

Assuming you have express and typescript setup , Lets get right into it

Step1:- To protect a route we need to first create a token when a user logs in and then verify it when the user tries to reach a protected route.So lets create a function to generate tokens

How this function works:-
The jwt.sign() function takes in 3 parameters as input:-

  • payload(in our case it is the Id):-payload is the data which we want to imbed in our token
  • secret:-This is a private key which we will define
  • {options}:-There are various optional functionalities we can add such as an expiry timing for the token, the issuer, audience ,etc.

This will create a token for us,Now we need to store this token somewhere so that whenever the user tries to reach a protected route they also send us the token which we can verify.
The best way to store the token is to store it in the cookies.

The res.cookie() function takes in 3 parameters:-
-name:- this is the name of the cookie , eg “jwt”,
-value:-token in our case is the value
-{options}:- other features like how long should the cookie last , security settings

Step2:-Now lets create a middleware to protect our routes


So we get our jwt token from the cookies and then verify it using jwt.verify() function,
the verify() function takes in two arguments
-our token
-the secret which we defined
So what the verify() function does is takes the header and payload from the token and recreates the signature using our secret and then compares it to the signature inside our token.
Here is a sample usage of this auth flow in a signup endpoint


Once all the checks are done, then gentoken() function creates the token.

Connect:-
x.com/Tej_Codes
github.com/TejaswaHinduja

Top comments (0)