---
title: "Implémentez JWT dans votre application"
slug: "implement-jwt-in-your-application"
updated: 2026-10-12T08:20:14Z
published: 2026-10-12T08:20:14Z
canonical: "docs.document360.com/implement-jwt-in-your-application"
---
> ## Documentation Index
> Fetch the complete documentation index at: https://docs.document360.com/llms.txt
> Use this file to discover all available pages before exploring further.
# Implémentez JWT dans votre application
Après avoir terminé la configuration JWT dans Document360, votre application a besoin d’une route backend pour gérer la dernière étape du flux de connexion.
Voici l’itinéraire :
- Valide que l’utilisateur est déjà authentifié dans votre application
- Envoie une requête sécurisée à l’URL de génération de code de Document360
- Récupère un code d’autorisation à usage unique
- Redirige l’utilisateur vers le site de la base de connaissances avec ce code
NOTE
Les lecteurs n’ont pas besoin d’un compte Document360 séparé. L’authentification est entièrement gérée via votre application. Un compte dans votre application suffit pour qu’un lecteur puisse accéder à la base de connaissances.
---
## Exemples de code
Les exemples ci-dessous montrent comment implémenter la route d’authentification backend en C#, Node.js et Java.
### C #
```
///
/// Example endpoint to authenticate a user and retrieve a token from the identity server,
/// and redirect the user to the Knowledge Base (KB) using the token code.
///
/// Client ID issued for your application
/// Client secret associated with the client ID
/// Redirects to the KB with the issued code
[HttpGet]
[Route("authenticate")]
public async Task AuthenticateAsync(string clientId, string clientSecret)
{
if (!HttpContext.User.Identity.IsAuthenticated)
{
// user is not authenticated, redirect to an error or login page
return Unauthorized(new { message = "User not authenticated" });
}
// Ensure you have the correct client ID and secret from your Document360 JWT configuration
var authToken = Encoding.ASCII.GetBytes($"{clientId}:{clientSecret}");
// Create an HttpClient instance
using var httpClient = new HttpClient();
// Set the Authorization header with Basic authentication
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
// Prepare the payload with user information
var payload = new
{
username = User.Identity.Name,
firstName = "FirstName", // Replace or customize as needed
lastName = "LastName",
emailId = "user@example.com", // Replace with actual user email
readerGroupIds = new List { "group1", "group2" }, // Replace with actual reader group IDs if needed (Optional)
tokenValidity = 3600, // Token validity in seconds (Optional, default is 5 minutes)
providerName = "app.example.com" // Domain of the matching JWT configuration (Required when multiple JWT configurations are active)
};
var payloadContent = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");
// Identity server token endpoint - replace with your actual URL
string identityServerUrl = "codeGeneration endpoint, you can find that in JWT config portal";
// KB login URL to redirect after successful token issuance
string kbLoginUrl = "https://{your subdomain}.document360.io";
var response = await httpClient.PostAsync(identityServerUrl, payloadContent);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
var tokenJson = JObject.Parse(content);
// Extract the code from the response
var tokenCode = (string)tokenJson.SelectToken("code");
// Construct the KB login URL with code query parameter
string finalRedirectUrl = $"{kbLoginUrl}?code={tokenCode}";
return Redirect(finalRedirectUrl);
}
else
{
// Handle error response from the identity server
var error = await response.Content.ReadAsStringAsync();
return StatusCode((int)response.StatusCode, new { error = "Token request failed", details = error });
}
}
```
### Node.js
```
const express = require('express');
const https = require('https');
const axios = require('axios');
const app = express();
app.use(express.json());
const clientId = 'your-client-id';
const clientSecret = 'your-client-secret';
const codeGenerationUrl = 'https://identity.document360.net/jwt/generateCode';
const kbLoginUrl = 'https://your-subdomain.document360.net/jwt/authorize';
app.get('/authenticate', async (req, res) => {
try {
const isAuthenticated = true; // Replace with your actual auth logic
if (!isAuthenticated) {
return res.status(401).json({ message: 'User not authenticated' });
}
const authHeader = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
const payload = {
username: 'john.doe',
firstName: 'John',
lastName: 'Doe',
emailId: 'john.doe@example.com',
readerGroupIds: ['group1', 'group2'],
tokenValidity: 3600,
providerName: 'app.example.com' // Domain of the matching JWT configuration
};
const response = await axios.post(
codeGenerationUrl,
payload,
{
headers: {
'Authorization': `Basic ${authHeader}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
httpsAgent: new https.Agent({ maxVersion: 'TLSv1.2' })
}
);
const tokenCode = response.data?.code;
if (!tokenCode) {
return res.status(500).json({ message: 'No code received from Document360' });
}
console.log("Redirecting to:", `${kbLoginUrl}?code=${tokenCode}`);
return res.redirect(`${kbLoginUrl}?code=${tokenCode}`);
} catch (error) {
return res.status(500).json({
message: 'JWT SSO failed',
details: error.response?.data || error.message
});
}
});
```
### Java
```
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.nio.charset.StandardCharsets;
import java.util.*;
@RestController
public class JwtSsoController {
private final String clientId = "your-client-id";
private final String clientSecret = "your-client-secret";
private final String codeGenerationUrl = "https://identity.document360.io/api/jwt/generate-code";
private final String kbLoginUrl = "https://your-subdomain.document360.io/jwt/authorize";
@GetMapping("/authenticate")
public ResponseEntity> authenticate() {
// Example: Check if user is authenticated in your system
boolean isAuthenticated = true; // Replace with actual logic
if (!isAuthenticated) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("User not authenticated");
}
// Create Basic Auth header
String auth = clientId + ":" + clientSecret;
String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Basic " + encodedAuth);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// Construct payload
Map payload = new HashMap<>();
payload.put("username", "john.doe");
payload.put("firstName", "John");
payload.put("lastName", "Doe");
payload.put("emailId", "john.doe@example.com");
payload.put("readerGroupIds", Arrays.asList("group1", "group2"));
payload.put("tokenValidity", 3600);
payload.put("providerName", "app.example.com"); // Domain of the matching JWT configuration
HttpEntity