Implement JWT in your application

Prev Next

After you create the JWT configuration in Document360, add one endpoint to your application, for example /docs/auth. Document360 sends readers to it whenever they need to sign in.

  1. Make it a protected route. If the reader has no session in your application, send them to your login page and return them to this endpoint after they sign in.
  2. Get a sign-in code. From your backend, call the Code generation URL with the Client ID, the secret token and the reader's details.
  3. Send the reader to the knowledge base. Redirect them to the Callback URL with the code, for example https://yourproject.document360.io/jwt/authorize?code=xyz.
  4. Point the Login URL at this endpoint. Make sure the Login URL of your JWT configuration is this endpoint's address. You can build the endpoint before or after the configuration is created; update the Login URL in Enterprise SSO if it changes.

Once this is in place, deep links work on their own: readers return to the article they first opened.

NOTE

Readers do not require a separate Document360 account. Authentication is handled entirely through your application. An account in your application is sufficient for a reader to access the knowledge base.


Code samples

The examples below show how to implement the sign-in endpoint in C#, Node.js, and Java. Each sample reads the Client ID, secret token, Code generation URL and Callback URL from server configuration. Copy these values from your JWT configuration; hosts differ by region, and a custom domain changes the Callback URL.

C#

/// <summary>
/// Sign-in endpoint for Document360 JWT. Set its address as the Login URL of your JWT configuration.
/// Gets a sign-in code from Document360 and redirects the reader to the knowledge base.
/// </summary>
[HttpGet]
[Route("docs/auth")]
public async Task<IActionResult> AuthenticateAsync()
{
    if (!HttpContext.User.Identity.IsAuthenticated)
    {
        // Send the reader to your login page and bring them back to this endpoint after sign-in
        return Challenge(new AuthenticationProperties { RedirectUri = Request.Path + Request.QueryString });
    }

    // Read these from your server configuration or secrets store, never from the request
    // (_config is an IConfiguration injected into the controller)
    string clientId = _config["Document360:ClientId"];
    string clientSecret = _config["Document360:ClientSecret"];
    string codeGenerationUrl = _config["Document360:CodeGenerationUrl"]; // Code generation URL from the configuration
    string callbackUrl = _config["Document360:CallbackUrl"];             // Callback URL, e.g. https://yourproject.document360.io/jwt/authorize

    var authToken = Encoding.ASCII.GetBytes($"{clientId}:{clientSecret}");

    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 the signed-in reader's details
    var payload = new
    {
        username = User.Identity.Name,
        firstName = "FirstName",           // Replace with the reader's first name
        lastName = "LastName",             // Replace with the reader's last name
        emailId = "user@example.com",      // Replace with the reader's email address
        readerGroupIds = new List<string> { "<reader group ID>" }, // Optional. IDs from Reader groups. Leave out to give access to the whole project
        tokenValidity = 60,                // Optional. Session length in MINUTES, 5 to 1440
        providerName = "app.example.com"   // Recommended when the project has 2 or more JWT configurations.
                                           // The Domain name of THIS configuration: Enterprise SSO > Edit > Server settings > Domain name
    };

    var payloadContent = new StringContent(JsonConvert.SerializeObject(payload), Encoding.UTF8, "application/json");

    var response = await httpClient.PostAsync(codeGenerationUrl, 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");

        return Redirect($"{callbackUrl}?code={Uri.EscapeDataString(tokenCode)}");
    }
    else
    {
        // A 401 here means the Client ID or secret token is wrong
        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 axios = require('axios');
const app = express();

app.use(express.json());

// Read these from your server configuration or secrets store
const clientId = process.env.D360_CLIENT_ID;
const clientSecret = process.env.D360_CLIENT_SECRET;
// Copy both values from your JWT configuration in Document360
const codeGenerationUrl = process.env.D360_CODE_GENERATION_URL; // Code generation URL
const callbackUrl = process.env.D360_CALLBACK_URL;               // Callback URL (uses your custom domain if you have one)

// Set this endpoint's address as the Login URL of your JWT configuration
app.get('/docs/auth', async (req, res) => {
  try {
    const isAuthenticated = true; // Replace with your actual auth logic

    if (!isAuthenticated) {
      // Send the reader to your login page and bring them back here after sign-in
      return res.redirect(`/login?returnTo=${encodeURIComponent(req.originalUrl)}`);
    }

    const authHeader = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');

    const payload = {
      username: 'john.doe',
      firstName: 'John',
      lastName: 'Doe',
      emailId: 'john.doe@example.com',
      readerGroupIds: ['<reader group ID>'], // Optional. IDs from Reader groups. Leave out to give access to the whole project
      tokenValidity: 60,                     // Optional. Session length in MINUTES, 5 to 1440
      providerName: 'app.example.com'        // Recommended with 2 or more JWT configurations: the Domain name of THIS configuration
    };

    const response = await axios.post(
      codeGenerationUrl,
      payload,
      {
        headers: {
          'Authorization': `Basic ${authHeader}`,
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      }
    );

    const tokenCode = response.data?.code;

    if (!tokenCode) {
      return res.status(500).json({ message: 'No code received from Document360' });
    }

    return res.redirect(`${callbackUrl}?code=${encodeURIComponent(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 {

    // Read these from your server configuration or secrets store
    private final String clientId = System.getenv("D360_CLIENT_ID");
    private final String clientSecret = System.getenv("D360_CLIENT_SECRET");
    // Code generation URL, copied from your JWT configuration (ends in /jwt/generateCode)
    private final String codeGenerationUrl = System.getenv("D360_CODE_GENERATION_URL");
    // Callback URL, copied from your JWT configuration (uses your custom domain if you have one)
    private final String callbackUrl = System.getenv("D360_CALLBACK_URL");

    // Set this endpoint's address as the Login URL of your JWT configuration
    @GetMapping("/docs/auth")
    public ResponseEntity<?> authenticate() {
        // Example: Check if user is authenticated in your system
        boolean isAuthenticated = true; // Replace with actual logic
        if (!isAuthenticated) {
            // Send the reader to your login page and bring them back here after sign-in
            HttpHeaders loginHeaders = new HttpHeaders();
            loginHeaders.setLocation(java.net.URI.create("/login?returnTo=/docs/auth"));
            return new ResponseEntity<>(loginHeaders, HttpStatus.FOUND);
        }

        // 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<String, Object> 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("<reader group ID>")); // Optional. Leave out to give access to the whole project
        payload.put("tokenValidity", 60);                                  // Optional. Session length in MINUTES, 5 to 1440
        payload.put("providerName", "app.example.com");                    // Recommended with 2 or more JWT configurations: the Domain name of THIS configuration

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(payload, headers);
        RestTemplate restTemplate = new RestTemplate();

        try {
            ResponseEntity<Map> response = restTemplate.postForEntity(codeGenerationUrl, request, Map.class);

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                String tokenCode = (String) response.getBody().get("code");

                if (tokenCode == null || tokenCode.isEmpty()) {
                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                            .body("No code returned from Document360");
                }

                // Redirect to the Callback URL with the code
                String redirectUrl = UriComponentsBuilder.fromHttpUrl(callbackUrl)
                        .queryParam("code", tokenCode)
                        .toUriString();

                HttpHeaders redirectHeaders = new HttpHeaders();
                redirectHeaders.setLocation(java.net.URI.create(redirectUrl));
                return new ResponseEntity<>(redirectHeaders, HttpStatus.FOUND);

            } else {
                return ResponseEntity.status(HttpStatus.BAD_GATEWAY)
                        .body("Failed to get code from Document360: " + response.getStatusCode());
            }

        } catch (Exception ex) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("JWT SSO error: " + ex.getMessage());
        }
    }
}

Code generation URL reference

Request: HTTP POST to the Code generation URL, with the Client ID and a secret token as HTTP Basic authentication and a JSON payload.

Response: {"success":true,"code":"…"} on success. HTTP 401 with {"success":false,"error":"validation failed"} when the Client ID or secret token is wrong.

Code lifetime: each code is valid for 5 minutes and works once.

Payload fields

Field Send it? Notes
username Always The reader's user name in your application
firstName, lastName Always The reader's name
emailId Always The reader's email address
readerGroupIds Optional Reader group IDs. Leave out for access to the whole project
tokenValidity Optional Session length in minutes, 5 to 1440. Default 5
providerName With 2+ JWT configurations The configuration's Domain name. Lets Document360 renew the session through the right Login URL when it times out
NOTE

The Code generation URL doesn't reject a payload with missing identity fields, so a typo in a field name fails silently. Send all four identity fields with exactly these names.


Re-authenticating readers with multiple JWT configurations

Send providerName when your project has 2 or more JWT configurations. It tells Document360 which configuration the reader signed in through. When the reader's session times out, Document360 sends them back to that configuration's Login URL. If they are still signed in to your application, they return to the knowledge base without seeing any login screen.

Set providerName to the configuration's Domain name, found at Settings > Users & Permissions > Enterprise SSO > Edit icon > Server settings. Each configuration's sign-in endpoint sends its own Domain name. The value must match exactly (letter case doesn't matter); one that matches no active configuration makes readers enter their domain on the login page instead. With only one JWT configuration, providerName isn't needed.

{
  "username": "john.doe",
  "firstName": "John",
  "lastName": "Doe",
  "emailId": "john.doe@example.com",
  "readerGroupIds": ["<reader group ID>"],
  "tokenValidity": 60,
  "providerName": "app.example.com"
}

Developer checklist

Before going live, verify the following:

  • Set the Login URL of your JWT configuration to your protected sign-in endpoint.
  • Copy the Client ID, Code generation URL and Callback URL from the configuration into your server settings.
  • Store both secret tokens in a secrets manager. They are shown only once.
  • Call the Code generation URL from your backend only, using HTTP Basic authentication.
  • Redirect the reader to the Callback URL within 5 minutes of getting the code. Each code works once.
  • If your project has 2 or more JWT configurations, include providerName in the payload with the Domain name of the matching configuration.
  • Use HTTPS on every endpoint in the flow.
  • Test sign-in, session expiry and automatic renewal before going live.

A 401 from the Code generation URL means the Client ID or secret is wrong. "Invalid authentication code" on the knowledge base means the code expired, was already used, or belongs to another project.

Next, test the whole flow: see Test your JWT configuration.


Redirecting to a specific page after login

By default, readers return to the page they were trying to open when they were asked to sign in. If sign-in takes longer than 10 minutes, or there was no such page, they land on the Home page of your knowledge base, or on /docs if the Home page is unpublished.

To send readers to a different page, add redirectUrl to the Callback URL using the following URL pattern.

URL pattern

https://<Knowledge base URL>/jwt/authorize?code=<code>&redirectUrl=<redirect path>

Parameters

  • <Knowledge base URL>: the main URL of your knowledge base site.
  • <code>: the code generated by the Document360 code generation endpoint.
  • <redirect path>: the relative path where you want readers to land after login, for example /docs/getting-started. Full URLs are ignored.

Example

https://example.document360.io/jwt/authorize?code=<one-time code>&redirectUrl=/docs/5-basic-things-to-get-started
NOTE

When a reader is sent to sign in, the knowledge base site saves the page they asked for in a short-lived cookie (redirectTo, valid for 10 minutes). The cookie stays on the knowledge base site: it isn't sent to your application, and your application doesn't need to read it or pass anything back. After sign-in, the knowledge base site reads the cookie and returns the reader to the article they last tried to open. To send readers somewhere else instead, add redirectUrl to the Callback URL. The value must be a relative path, for example &redirectUrl=/docs/getting-started; full URLs are ignored.