Developer Platform
  • Home
  • Getting Started
    • General Information
    • Features Overview
    • Security
  • APPs
    • Public Apps
      • Shopify
      • Salesforce
      • Zendesk
      • Google Analytics
    • Build your App
      • Getting started
      • My Apps
      • App information
      • App Parameters
      • App Plugins
      • Add Webhooks
      • Submit your Apps
      • App security
      • Developer Policy
  • Use Cases
    • Copilots
      • Product Catalog sync through API
      • FAQ sync through API
    • Visitor experience
      • Integrating custom buttons into your site
      • Check availability before escalating to iAdvize
      • Authenticated Messaging
        • Introduction
        • Web client-side implementation
          • Authenticated Messaging overview
          • Brief timeline of the integration process
          • How to enable authenticated mode in the administration portal?
          • How to implement the customer authentication backend (token provider)?
          • How to authenticate with iAdvize in client's website?
          • How to deal with activation success or failure?
          • How to logout?
          • Compatibility with Mobile SDK
          • FAQ
        • Web backend implementation
          • Important information and recommendations
          • Signature and Encryption Detailed Process
          • Technical backend implementation
          • FAQ
      • Cross-domain Conversation Continuity
      • Customize replies with Markdown
    • Agent workspace
      • Custom App example and step-by-step tutorial
        • Get Started
        • Work with the Desk
        • Intent / Trigger
        • JWT
        • References
    • Administration
      • Users
        • SAML SSO Authentication - Implementation Guide
        • Create, update and delete users via API
        • Manage the availability of your users with the iAdvize API
        • Integrate the iAdvize conversation panel into an existing tool
    • Data & Analytics
      • Anonymize a conversation or visitor data
      • Create a custom dashboard
      • Find contact data using GraphQL
      • Retrieve conversations data
      • Retrieve messages exchanged within a conversation
  • Technologies
    • GraphQL API
      • Terminology
      • Reference
      • Authentication
      • Schema lifecycle
      • Error Management
      • Pagination
    • REST API (deprecated)
      • Statistic (deprecated)
      • Group (deprecated)
      • Call meeting (deprecated)
      • Operator (deprecated)
      • Skill (deprecated)
      • Transaction (deprecated)
      • Visitor (deprecated)
    • Webhooks
      • Reference
      • Guides
    • Desk events
      • Reference
    • Web & Mobile SDK
      • Javascript Web SDK
        • Reference
      • Javascript Callbacks
        • Reference
        • Guides
      • Mobile SDK
        • Fourme (latest)
        • Epoisses
        • Dauphin
        • Cantal
        • 🤝Support Policy
        • 🤔Frequently Asked Questions
    • Custom App
    • External Bot
      • Implementation
        • Configuration flow
        • Conversation flow
        • Conversation objects
      • Configuration
      • FAQ
      • Best practices
Powered by GitBook
On this page
  • Get the JWT
  • How to use a Middleware

Was this helpful?

  1. Use Cases
  2. Agent workspace
  3. Custom App example and step-by-step tutorial

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

PreviousIntent / TriggerNextReferences

Last updated 1 year ago

Was this helpful?

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

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

How to get the JWT
How to use a Middleware
The secret token in the "security" section
Add a JWT key to the headers