JSON Web Tokens are replacing cookies for authentication purposes pretty significantly. In this blog post I am going to show you how you can implement JWT in your api. I am going node express in this example.


What is a JSON Web token

Formal is definition in official site. JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties. So:-

  1. JWT is based on RFC 7519 Industry standard.
  2. Used to securely communicate JSON objects.
  3. They are self contained mean they all information use to decrypt the token is in the token itself except the secret obviously.
  4. JWT consists of a header, payload and signature. These three parts are connect by .

A JWT looks like this

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNDkyNjg1MDUwLCJleHAiOjE0OTUyNzcwNTB9.bHMstzcHfZQBND3QrugO4v3kTa7Zy7yifuuhWJbwhI0

You may see here three parts separated by . The information we wanna store sits in the second part.


Lets Code a Login API using JWT


Result(Using postman to test APIs)


Trying to access protected api without authorization token

Got unauthorized error
ss1


Logging in with right credentials

Got the token back in the response
ss2


Accessing protected route with authorization token

Successfully entered the api
f99365a296a3435e358fd35c2cadb252