What is JWT ?
A JWT (JSON Web Token) is a secure way to transmit information between a client (like a browser) and a server.
JWT has three parts
Headercontains the token type and algorithmPayloadcontains the user dataSignatureensures the token's have not been tampered
MECHANISM
- Once a user logs in, the server generates a token and sends it to the client.
- The client then includes this token in every subsequent request’s headers for authentication.
How client includes token in every request ?
Authorization: Bearer <your-token-here>
Server checks with jwt.verify
If the token is valid then the access is granted
Primary Stuff to understand
- Stateless: Server doesn’t need to store sessions.
- Expiration : Token can expire in specific time-interval
- Middleware verification on each request : Middleware ensures the user is authenticated.
RUN THE server : node app.js
Generate new token :
curl -X POST http://localhost:5000/login \
-H "Content-Type: application/json" \
-d '{"username":"vivek","password":"viveksharma"}'Expected Response :
{
"token": "eyJhbGciOiJIUzI1NiIsIpQ1..."
}
Now checking protected route layout
curl -X GET http://localhost:5000/layout \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsIpQ1..."Introducing Access and Refresh Tokens
If expiry not set then jwt tokens will stay forever
General issues :
- If token expires too soon, users must log in again every time.
- If the token lives too long, it’s a security risk.
Thus this is where access and refresh tokens comes into play
- Access Token - short-lived -> Used to access protected APIs.
- Refresh Token - long-lived -> Used only to get a new access token when it expires.
This has been implemented in server.js
Keep the following info in .env
ACCESS_TOKEN_SECRET=testuser1
REFRESH_TOKEN_SECRET=testuser1Performing Login to get the tokens
curl -X POST http://localhost:5000/login \
-H "Content-Type: application/json" \
-d '{"username":"vivek"}'
Response
{
"accessToken": "short-lived-token",
"refreshToken": "long-lived-token"
}
Access Protected Route
curl -X GET http://localhost:5000/layout \
-H "Authorization: Bearer <accessToken>"Getting a new access token using refresh token
curl -X POST http://localhost:5000/token \
-H "Content-Type: application/json" \
-d '{"token":"<refreshToken>"}'
Performing Invalidation of Refresh Token
curl -X POST http://localhost:5000/logout \
-H "Content-Type: application/json" \
-d '{"token":"<refreshToken>"}'
NOTED : Here i have included a case for enabling google calendar via api. You need to make sure that you have account in gcp and you have a project initiated
- Visit [Google Cloud](Visit: https://console.cloud.google.com/)
- Make sure you are signed in and already project is created, if not then create one
- Go to API & SERVICES and then LIBRARY
- Enable it
Create OAuth 2.0 Credentials
- Go to APIs & Services → Credentials
- Click + CREATE CREDENTIALS → OAuth client ID
- You will redirected to consent screen
- Fill all the basic info in consent screen
- Add
https://developers.google.com/oauthplaygroundto authorize domain - Once this is done , you will get GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET
- copy them in .env file
- Visit https://developers.google.com/oauthplayground
- Click gear icon ⚙️ on top right
- Check Use your own OAuth credentials
- Paste your
GOOGLE_CLIENT_IDandGOOGLE_CLIENT_SECRET - In left sidebar , find and select the scope
https://www.googleapis.com/auth/calendar - Click Authorize API'S
- Sign in with your Google account and allow permissions
- Click Exchange authorization code for tokens
- You will now get access tokens and refresh tokens
- Copy them and put in .env
NEXT IN THE LIST : Session Token, ID Token and CSRF Token