Skip to content

Delegated Chat

A delegated share shows each user of your application only their own chat history and their own documents. Your backend vouches for the user; the browser never sees the gateway key or the user’s assertion.

Read How the User Is Passed first — it defines exactly how the user is passed (sub of a signed JWT in X-End-User-Assertion).

Delegated chat: ticket flow between browser, your backend and RagtyDelegated chat: ticket flow between browser, your backend and Ragty

You implement steps 2, 3 and 6 (highlighted in orange). Everything else is done by the component and Ragty.

Configure your identity provider so that your backend can obtain, for the currently signed-in user, a JWT with:

  • iss = the issuer registered in Ragty, aud = the registered audience,
  • sub = the immutable user ID (same value as used for document ingestion),
  • exp ≤ 5 minutes, signed RS256 with a kid from the registered JWKS.

With Keycloak or another OIDC provider use token exchange to obtain a token with the Ragty audience. If your IdP cannot do that, mint the assertion yourself:

Generate an RSA key pair (2048 bit or more) for this purpose only, keep the private key in your secret manager, and publish the public key as a JWKS ({"keys":[{…,"kid":"2026-11-portal","use":"sig","alg":"RS256"}]}) at an HTTPS URL. Give that URL to the Ragty administrator.

// Maven: com.nimbusds:nimbus-jose-jwt
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import java.time.Instant;
import java.util.Date;
public final class EndUserAssertionService {
private static final String ISSUER = "https://idp.example.com/realms/customers";
private static final String AUDIENCE = "ragty-chat";
private final RSAKey signingKey; // private RSA JWK with kid, loaded from your secret manager
public EndUserAssertionService(RSAKey signingKey) {
this.signingKey = signingKey;
}
/** @param userId immutable ID of the authenticated user — never taken from the browser */
public String issueFor(String userId) throws JOSEException {
Instant now = Instant.now();
JWTClaimsSet claims = new JWTClaimsSet.Builder()
.issuer(ISSUER)
.audience(AUDIENCE)
.subject(userId)
.issueTime(Date.from(now))
.expirationTime(Date.from(now.plusSeconds(120)))
.build();
SignedJWT jwt = new SignedJWT(
new JWSHeader.Builder(JWSAlgorithm.RS256).keyID(signingKey.getKeyID()).type(JOSEObjectType.JWT).build(),
claims);
jwt.sign(new RSASSASigner(signingKey));
return jwt.serialize();
}
}

Step 2: Implement the ticket endpoint (your backend)

Section titled “Step 2: Implement the ticket endpoint (your backend)”

Add one authenticated endpoint, e.g. POST /api/m8ty/ticket, that:

  1. requires the user’s normal session (and your CSRF protection),
  2. validates the nonce from the request body,
  3. mints the assertion for the session user,
  4. calls Ragty with the gateway key and returns the ticket JSON unchanged.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;
import java.util.regex.Pattern;
import org.springframework.http.*;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
@RestController
class M8tyTicketController {
private static final URI TICKETS = URI.create("https://rag.example.com/api/v1/embed/tickets");
private static final String SHARE_ID = "shr_XXXXXXXXXXXXXXXXXXXXXXXX";
private static final String PAGE_ORIGIN = "https://portal.example.com"; // the origin showing the chat
private static final Pattern NONCE = Pattern.compile("[A-Za-z0-9_-]{16,128}");
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build();
private final String gatewayKey = System.getenv("M8TY_GATEWAY_KEY"); // from your secret manager
private final EndUserAssertionService assertions;
M8tyTicketController(EndUserAssertionService assertions) {
this.assertions = assertions;
}
@PostMapping(path = "/api/m8ty/ticket", produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> ticket(@RequestBody Map<String, String> body, Authentication auth) throws Exception {
String nonce = body.get("nonce");
if (nonce == null || !NONCE.matcher(nonce).matches()) {
return ResponseEntity.badRequest().build();
}
String userId = auth.getName(); // the authenticated user only
String assertion = assertions.issueFor(userId); // sub = userId
String json = "{\"share_id\":\"" + SHARE_ID + "\",\"origin\":\"" + PAGE_ORIGIN
+ "\",\"nonce\":\"" + nonce + "\"}";
HttpRequest request = HttpRequest.newBuilder(TICKETS)
.timeout(Duration.ofSeconds(10))
.header("Authorization", "Bearer " + gatewayKey)
.header("X-End-User-Assertion", assertion)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
// Log status only — never the assertion, the key or the response body.
return ResponseEntity.status(HttpStatus.BAD_GATEWAY).build();
}
return ResponseEntity.ok()
.cacheControl(CacheControl.noStore())
.body(response.body()); // {"ticket":"…","expires_in":60}
}
}

The component calls your getTicket function with a nonce whenever it needs a session — on start, about every 10 minutes when the session expires, and after an administrator ended all sessions. Return the ticket JSON of your endpoint.

<script type="module" src="https://rag.example.com/embed-assets/v1/m8ty-chat.js" crossorigin="anonymous"></script>
<m8ty-chat id="support-chat" share="shr_XXXXXXXXXXXXXXXXXXXXXXXX" locale="de"
style="display:block;height:600px"></m8ty-chat>
<script type="module">
const chat = document.getElementById("support-chat");
chat.getTicket = async (nonce) => {
const response = await fetch("/api/m8ty/ticket", {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json", "X-CSRF-Token": window.csrfToken },
body: JSON.stringify({ nonce }),
});
if (!response.ok) throw new Error("ticket request failed");
return response.json(); // { ticket, expires_in }
};
chat.addEventListener("m8ty-session-expired", () => {
// e.g. the user logged out in another tab: send them to your login page
});
</script>
  1. Log in as user A, ask a question, reload — the history is shown.
  2. Log in as user A on another browser — the same history is shown.
  3. Log in as user B — an empty chat; A’s chats are not visible.
  4. Call your ticket endpoint without a session — it must return 401/403 and never reach Ragty.
  5. Open the page from a non-allowed origin — the chat must not start.