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().
instance.getVariable().then((client : any) =>{ //ligne 143
client.getJWT().then(
(newJwt : string)=>{
//Your api call
})
)
})
In you api call, you should add one parameter in addition to the url (line 14)
const res = await fetch(api, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${jwt}` // Add the JWT to the Authorization header
}
})

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
The secret token in the "security" section
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
import { NextResponse,NextRequest } from 'next/server';
import { jwtVerify } from "jose"
import { secret } from './pages/consts';
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
npm install jose
This is your middleware
export async function middleware(request: NextRequest) {
const bearerToken = request.headers.get("authorization")?.split(' ')[1];
//bearerToken contains your JWT
if (!bearerToken) {
return new NextResponse(
JSON.stringify({ success: false, message: 'Authentication failed' }),
{ status: 401, headers: { 'content-type': 'application/json' } },
);
}
//if there is no token, the middleware returns an error 401
try {
const decoded = await jwtVerify(bearerToken, new TextEncoder().encode(secret));
return NextResponse.next();
//if the JWT is decoded, the middleware allows the api call
} catch (error) {
return new NextResponse(
JSON.stringify({ success: false, message: 'Invalid JWT' }),
{ status: 401, headers: { 'content-type': 'application/json' } },
);
//if the JWT is not decoded, the middleware returns an error 401
}
}
But how do the middleware know when he needs to be called ? It's all thanks to the config const
export const config = {
matcher: '/api/:path*',
};
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
Add a JWT key to the headers