JWT
JWT stands for Json Web Tokens, they are encrypted Json objects sent by the website. We use them to transmit confidential informations or verify your identity
In this tutorial, you will learn
Get the JWT
Take your "6JWT" file and rename it "pages"
You need to call the client to get the JWT. The client is in instance.getVariable().
In you api call, you should add one parameter in addition to the url (line 14)
How to use a Middleware
Modify each API to decode the jwt is a way to secure them, but it's terribly inefficient. We are going to use a middleware. A middleware test the jwt for every api call and run the call only if the JWT is verified.
Get your secret
You secret is the "key" to decrypt your JWT, if the JWT can be decrypted with this key, it's a valid one.
This secret is in the developer platform, in your app information. In the "Security" section, under the "secret token" field. You can put it in your "const" file
You may have noticed the "middleware.tsx" in your file. It's time to use it, move it to the src file (src/pages/middleware.tsx -> src/middleware.tsx). This file is always called when you make an api call.
This file is divided into 3 parts :
Imports
The middleware
Get the token
Test if there is a token
Test if the token is allowed
Config the paths
You have 4 things to import
NextResponse and NextRequest are from nextJS JwtVerify is what we'll use to verify our JWT. Secret is the secret you took from the dev platform
The middleware is used to get the token, test if there is a token, test if the token is allowed and return an error otherwise
To test if the token is allowed, we're going to use jose. To install it, simply do the following command in your terminal
This is your middleware
But how do the middleware know when he needs to be called ? It's all thanks to the config const
This line tells the middleware to apply when the file called is in "/api/*".
If you're working locally, the redirection of "onMessage" may delete the headers including the JWT. Don't be surprise if your intent/trigger don't work. You can fix it temporarily by using Requestly to add a header rule. The solution is to console.log the jwt given by your client and inject it when you call onMessage. Be aware that the JWT expire after 1h so you may need to change it multiple time
Last updated