# Add e-signatures and clickwrap with Spring Boot

> Build a signup clickwrap in Spring Boot with RestClient, Jackson and HttpSession, calling the Esign Comply REST API. No artifact beyond Spring's own starters.

Source: https://esigncomply.com/docs/quickstart/spring-boot

Last updated November 26, 2026

To add e-signatures and clickwrap with Spring Boot, call the REST API with `RestClient` and the secret key: there is no Java package. One controller method creates the session and keeps the pinned versions in the `HttpSession`, another confirms the record, and the browser SDK attaches to your checkbox. Esign Comply seals each acceptance as an independent record.

Follow the steps and each signature your app records is a valid electronic signature under the ESIGN Act, state UETA laws and New York's ESRA, and your clickwrap is built the way courts require: clear notice of the terms, an unmistakable act of assent, and a sealed record of both.

Paste this prompt into Cursor, Claude Code or another AI coding tool to have it build the same integration:

```text copy="Copy prompt" open="cursor"
Add Esign Comply clickwrap to my Spring Boot app: a signup form where the user accepts the Terms of Service and the Privacy Notice with a checkbox and a button.

Read these first and follow them exactly. If something conflicts with existing code, or you are unsure how to implement a step, stop and ask. Do not invent API methods, packages or legal wording.
- https://esigncomply.com/docs/quickstart/spring-boot.md (the steps and the tested code for Spring Boot)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

Spring Boot facts
- There is no Esign Comply package for Java. Do not install or invent one. The server calls the REST API at https://esigncomply.com/v1 with Authorization: Bearer and the secret key, using a RestClient built from the RestClient.Builder that Spring Boot provides.
- The browser SDK is a script tag: https://esigncomply.com/sdk/v1/esigncomply.js. It defines the global EsignComply.
- The secret key is in the environment variable ESIGNCOMPLY_API_KEY, which Spring Boot binds to the property esigncomply.api.key. Spring Boot does not read .env files on its own. Never write the key into application.properties. Never print the key.
- retrieve() throws on 4xx and 5xx. Use exchange() and read the status before you read the record.
- The API's JSON is snake_case. Put @JsonNaming(SnakeCaseStrategy.class) on the records that read it. Do not set spring.jackson.property-naming-strategy for the whole app: it renames the app's own JSON too. On Spring Boot 4 the Jackson imports are tools.jackson.databind.
- Keep the signer ID and the pinned version IDs in the HttpSession, or in the store the project already has. Read it with request.getSession(false) in the confirm route. Set server.servlet.session.cookie.same-site.
- Return the document HTML with the content type text/html, unmodified. In a Thymeleaf template that is th:utext: th:text escapes it.
- Without Spring Security there is no CSRF check. If the project has Spring Security, send its CSRF token with both POST requests.
- The page is on screen before the script has a session: render the checkbox disabled and enable it when observeAssent has resolved.

Build
1. Verify the key: GET /v1/usage with ESIGNCOMPLY_API_KEY. Stop if it fails.
2. Register the Terms of Service and the Privacy Notice as documents and publish one version of each from the documents in this project. If the project has none, register short sample documents and say so in your report. Never write or change the wording of the real documents. Create a profile: jurisdictions ["US-FED"], method "checkbox", assurance_level "L1".
3. Controller method for POST /api/ceremony: call POST /v1/sessions with an Idempotency-Key, save the signer ID and the pinned version IDs in the HttpSession, and return only clientToken, apiUrl and documents.
4. Controller method for GET /legal/{slug}: render the html from GET /v1/documents/{id}/versions/{version_id}/content inside <article data-esc-document>, unmodified.
5. Browser: EsignComply.attach({ clientToken, apiUrl }), presentDocument for each link, observeAssent({ region, checkbox, submit }), then complete() from the user's real click.
6. Controller method for POST /api/signup/confirm: call GET /v1/records/{id} and require: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the ones in the HttpSession. Only then create the account.

Never
- Never pre-check the box, auto-submit, or call .click() on the user's behalf.
- Never use "By continuing" or "By clicking below" wording. The notice names the button by its label and each document by its registered name.
- Never put the secret key, or any call that uses it, in code that reaches the browser.
- Never show "signed" or "accepted" before the server has confirmed the record.
- Never fall back to an acceptance with no record when a session is refused.

Check before you report success
- Run: npx esigncomply check --url http://localhost:8080/signup --callback http://localhost:8080/api/signup/confirm
  Fix every finding marked "block". List every finding marked "warn".
- Report the files you created or changed, anything you did not implement and why, and the conformance summary.

Then add the rules block to this project's instruction file: https://esigncomply.com/rules.md
```

The rest of this page is the same integration by hand, in eight steps.

## Before you start

- A test API key. [Create an account](https://esigncomply.com/signup) with your email, no card, then choose **Create test key** in the dashboard. The key is shown once and starts with `esc_test_`. An AI agent with an agent token creates it with `POST /v1/agent/api-keys`: see the [agent account API](https://esigncomply.com/docs/api/agent.md).
- Nothing else from Esign Comply. Test mode works on `localhost` with no card and no domain, and the Free plan includes it in full.
- A JDK and Maven. Spring Boot 4.2.0 requires at least Java 17. This page was run on Java 25 with Maven 3.10.2.
- `curl` and `jq` for steps 2 and 3, and Node.js 20.19 or later for the conformance check in step 7.

## Step 1. Install

There is no Esign Comply artifact to add. The server SDK exists for Node.js only, so a Spring Boot app calls the REST API directly with `RestClient`. The project needs two of Spring Boot's own starters: `spring-boot-starter-webmvc` for Spring MVC and Tomcat, and `spring-boot-starter-restclient` for the client. The page loads the browser SDK from a script tag.

```bash
mkdir esigncomply-quickstart && cd esigncomply-quickstart
mkdir -p src/main/java/com/example/quickstart src/main/resources/static
```

Save this as `pom.xml`. It is the build file of Spring Boot's own first-application tutorial, with the second starter, the Java version and the project's own name:

```xml file="pom.xml"
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>4.2.0</version>
	</parent>
	<groupId>com.example</groupId>
	<artifactId>esigncomply-quickstart</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<properties>
		<java.version>25</java.version>
	</properties>

	<dependencies>
		<!-- Spring MVC and Tomcat. -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-webmvc</artifactId>
		</dependency>
		<!-- RestClient, for the calls to the Esign Comply API. There is no Esign Comply artifact to add. -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-restclient</artifactId>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
```

The application class is the one every Spring Boot project has:

```java file="src/main/java/com/example/quickstart/QuickstartApplication.java"
// src/main/java/com/example/quickstart/QuickstartApplication.java
package com.example.quickstart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class QuickstartApplication {

	public static void main(String[] args) {
		SpringApplication.run(QuickstartApplication.class, args);
	}

}
```

## Step 2. Set the key

Put the key in `.env` in the project folder. Spring Boot does not read this file: you load it into the shell that starts the app, and Spring Boot binds the variables to properties.

```bash
# .env (never commit this file)
ESIGNCOMPLY_API_KEY=esc_test_us_...
```

Load the file into your shell for the commands in steps 2, 3 and 7, then check that the key works:

```bash
set -a; . ./.env; set +a
curl -s ${ESIGNCOMPLY_API_URL:-https://esigncomply.com/v1}/usage \
  -H "Authorization: Bearer $ESIGNCOMPLY_API_KEY" | jq '{plan_name, test_events}'
```

```json
{
  "plan_name": "Free",
  "test_events": {
    "used_this_month": 0,
    "quota_per_month": 500
  }
}
```

A `401` means the key is wrong or revoked: see [`invalid_api_key`](https://esigncomply.com/docs/api/errors.md#invalid_api_key). The rules for handling keys are in [/auth.md](https://esigncomply.com/auth.md).

The code reads the key as the property `esigncomply.api.key`. Spring Boot's rule for the name of the variable is: replace each dot with an underscore, remove dashes, and write it in upper case. In a test, the variable `ESIGNCOMPLY_API_KEY` answered to the property names `esigncomply.api.key` and `esigncomply.api-key`, and not to `esigncomply.apiKey`.

`application.properties` holds the settings that are not secret:

```properties file="src/main/resources/application.properties"
# src/main/resources/application.properties
# The key is not in this file. Spring Boot binds the environment variable ESIGNCOMPLY_API_KEY
# to the property esigncomply.api.key, and the other ESIGNCOMPLY_ variables the same way.

# Timeouts for the calls to the API.
spring.http.clients.connect-timeout=5s
spring.http.clients.read-timeout=10s

# The session cookie. Tomcat sets no SameSite attribute unless you ask for one.
server.servlet.session.cookie.same-site=lax
server.servlet.session.cookie.secure=${esigncomply.live:false}
```

## Step 3. Register a document version

Every record pins the exact version of each document by hash, so the documents are registered first. This block registers a Terms of Service and a Privacy Notice with one version each, and creates a profile: the Federal pack, a checkbox with a button, level L1. It is the same for every stack and needs `curl` and `jq`.

```bash
ESC=${ESIGNCOMPLY_API_URL:-https://esigncomply.com/v1}
KEY="Authorization: Bearer $ESIGNCOMPLY_API_KEY"
JSON="Content-Type: application/json"

# Two sample documents, one version each.
TERMS=$(curl -s $ESC/documents -H "$KEY" -H "$JSON" \
  -d '{"name":"Terms of Service","type":"terms"}' | jq -r .id); sleep 1
curl -s $ESC/documents/$TERMS/versions -H "$KEY" -H "$JSON" \
  -d '{"version_label":"1","language":"en","content":{"format":"markdown","text":"# Terms of Service\n\nThese are sample terms for a test."},"material_change":true}' \
  | jq -r .id; sleep 1
PRIVACY=$(curl -s $ESC/documents -H "$KEY" -H "$JSON" \
  -d '{"name":"Privacy Notice","type":"privacy_notice"}' | jq -r .id); sleep 1
curl -s $ESC/documents/$PRIVACY/versions -H "$KEY" -H "$JSON" \
  -d '{"version_label":"1","language":"en","content":{"format":"markdown","text":"# Privacy Notice\n\nThis is a sample privacy notice for a test."}}' \
  | jq -r .id; sleep 1

# A profile: Federal pack, checkbox plus button, L1.
PROFILE=$(curl -s $ESC/profiles -H "$KEY" -H "$JSON" \
  -d '{"name":"Signup","jurisdictions":["US-FED"],"method":"checkbox","assurance_level":"L1"}' | jq -r .id)

printf 'ESIGNCOMPLY_PROFILE_ID=%s\nESIGNCOMPLY_TERMS_ID=%s\nESIGNCOMPLY_PRIVACY_ID=%s\n' "$PROFILE" "$TERMS" "$PRIVACY"
```

It prints the two version IDs, then three lines with your own IDs:

```text
dv_YiWs9cmWoVSGp7ALPeZS
dv_bAYeA7QigKUH0iLhPpV7
ESIGNCOMPLY_PROFILE_ID=prof_SPVEgBT8a8Ror3mJ8M99
ESIGNCOMPLY_TERMS_ID=doc_bDgYFndAoC8tkeYibAVy
ESIGNCOMPLY_PRIVACY_ID=doc_mb2hnWKS0Qa7SKtucDW9
```

Add the three lines to `.env`, then load the file into your shell again. The pauses keep the script under the Free plan's 2 requests per second. Keep the names `Terms of Service` and `Privacy Notice`: the notice on your page names each document by its registered name, and rule [CR-02](https://esigncomply.com/docs/conformance.md#cr-02) checks that it does. With your own documents, publish the text you already have and change the notice to match. See [Documents](https://esigncomply.com/docs/api/documents.md) and [Profiles](https://esigncomply.com/docs/api/profiles.md).

## Step 4. Create a session on the server

`EsignComply.java` is the entire client: `call`, which makes an HTTPS call with the secret key and returns the status and the JSON answer, `send`, the one request behind it, and the records the answers are read into.

```java file="src/main/java/com/example/quickstart/EsignComply.java"
// src/main/java/com/example/quickstart/EsignComply.java
package com.example.quickstart;

import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;

import tools.jackson.databind.JsonNode;
import tools.jackson.databind.PropertyNamingStrategies.SnakeCaseStrategy;
import tools.jackson.databind.annotation.JsonNaming;

/** There is no Java package: these are plain HTTPS calls with the secret key, made with Spring's RestClient. */
@Component
class EsignComply {

	private final RestClient http;

	// Spring Boot hands out a RestClient.Builder that already has its JSON converter and the timeouts from application.properties.
	EsignComply(RestClient.Builder builder,
			@Value("${esigncomply.api.url:https://esigncomply.com/v1}") String apiUrl,
			@Value("${esigncomply.api.key:}") String apiKey) {
		this.http = builder.baseUrl(apiUrl).defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey).build();
	}

	/** One call to the Esign Comply API. Returns the HTTP status and the JSON answer. */
	<T> Answer<T> call(HttpMethod method, String path, Class<T> type, Object body, String idempotencyKey, Object... uriVariables) {
		ResponseEntity<T> response = send(method, path, type, body, idempotencyKey, uriVariables);
		// Rate limited: wait for the seconds in Retry-After, 1 at least and 5 at most, and send it again, twice at most.
		for (int attempt = 1; response.getStatusCode().value() == 429 && attempt < 3; attempt++) {
			String retryAfter = response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER);
			long seconds = (retryAfter != null && retryAfter.matches("\\d{1,4}")) ? Long.parseLong(retryAfter) : 1;
			try {
				Thread.sleep(1000 * Math.max(1, Math.min(seconds, 5)));
			}
			catch (InterruptedException ex) {
				Thread.currentThread().interrupt();
				break;
			}
			response = send(method, path, type, body, idempotencyKey, uriVariables);
		}
		return new Answer<>(response.getStatusCode().value(), response.getBody());
	}

	private <T> ResponseEntity<T> send(HttpMethod method, String path, Class<T> type, Object body, String idempotencyKey, Object[] uriVariables) {
		RestClient.RequestBodySpec request = this.http.method(method).uri(path, uriVariables).accept(MediaType.APPLICATION_JSON);
		if (body != null) {
			request.contentType(MediaType.APPLICATION_JSON).body(body);
		}
		if (idempotencyKey != null) {
			request.header("Idempotency-Key", idempotencyKey);
		}
		// retrieve() throws on 4xx and 5xx. exchange() hands the refusal back: the status is here, and the error envelope is the body.
		return request.exchange((sent, answer) -> ResponseEntity.status(answer.getStatusCode()).headers(answer.getHeaders()).body(answer.bodyTo(type)));
	}

	record Answer<T>(int status, T body) {
	}

	// The API's fields are snake_case. Without @JsonNaming, Jackson looks for clientToken, finds nothing and leaves null.
	@JsonNaming(SnakeCaseStrategy.class)
	record Session(String clientToken, String apiUrl, JsonNode documents, ApiError error) {
	}

	record ApiError(String code) {
	}

	@JsonNaming(SnakeCaseStrategy.class)
	record SignatureRecord(String id, String status, Boolean livemode, Signer signer, List<PinnedDocument> documents) {
	}

	@JsonNaming(SnakeCaseStrategy.class)
	record Signer(String externalId) {
	}

	@JsonNaming(SnakeCaseStrategy.class)
	record PinnedDocument(String versionId) {
	}

	@JsonNaming(SnakeCaseStrategy.class)
	record DocumentContent(String versionId, String html) {
	}

}
```

Four things here are specific to Spring Boot, and each one was seen in the test run.

The request ends in `exchange()`, not `retrieve()`. Spring's documentation says `RestClient` throws when it retrieves a response with a 4xx or 5xx status code. With `retrieve()`, a made-up record ID threw `HttpClientErrorException$NotFound: 404 Not Found`. With `exchange()` the same call came back as status `404` with the error envelope, which the confirmation can read.

The records carry `@JsonNaming(SnakeCaseStrategy.class)`. The API's fields are `client_token`, `api_url` and `version_id`, and Jackson looks for `clientToken`. Without the annotation the answer was read into a record whose `clientToken` was `null`, and nothing was thrown. Setting `spring.jackson.property-naming-strategy=SNAKE_CASE` for the whole app is not the fix: with it the confirm route no longer read `recordId` from the page's JSON, because it expected `record_id`.

The imports are `tools.jackson.databind`. Spring Boot 4 ships Jackson 3, which moved to that package: the jar of this project holds `jackson-databind-3.1.8.jar`.

The base URL and the path are joined as they are. With the base `.../v1` a path of `/sessions` worked, and a path without the leading slash was sent to `/v1sessions` and answered `404`. Values passed as URI variables are encoded: a record ID of `a/b?c` was sent as `a%2Fb%3Fc`.

When the API answers `429`, `call` waits for the seconds in `Retry-After`, 1 at least and 5 at most, and runs `send` again, up to twice. `Thread.sleep` holds one of Tomcat's request threads for that time: in the test, page requests sent while two confirmations waited were answered in under 0.01 seconds.

One controller carries the routes: the signup page, the two document pages, the session and the confirmation.

```java file="src/main/java/com/example/quickstart/SignupController.java"
// src/main/java/com/example/quickstart/SignupController.java
package com.example.quickstart;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.web.util.HtmlUtils;

import com.example.quickstart.EsignComply.Answer;
import com.example.quickstart.EsignComply.DocumentContent;
import com.example.quickstart.EsignComply.PinnedDocument;
import com.example.quickstart.EsignComply.Session;
import com.example.quickstart.EsignComply.SignatureRecord;

@Controller
class SignupController {

	private static final Logger log = LoggerFactory.getLogger(SignupController.class);

	private static final List<String> SEALED = List.of("recorded", "timestamped", "anchored");

	// The signer. In your app this is the signed-in user, or the account you are about to create.
	private static final Map<String, String> SIGNER = Map.of(
			"external_id", "user_7c1d",
			"email", "dana@example.org",
			"name", "Dana Whitfield",
			"class", "consumer",
			"country", "US",
			"region", "US-CA");

	private final EsignComply esc;
	private final String profileId;
	private final Map<String, String> documents;
	private final boolean live;

	SignupController(EsignComply esc,
			@Value("${esigncomply.profile.id:}") String profileId,
			@Value("${esigncomply.terms.id:}") String termsId,
			@Value("${esigncomply.privacy.id:}") String privacyId,
			@Value("${esigncomply.live:false}") boolean live) { // set ESIGNCOMPLY_LIVE=true in production only
		this.esc = esc;
		this.profileId = profileId;
		this.documents = Map.of("terms", termsId, "privacy", privacyId);
		this.live = live;
	}

	// The page is src/main/resources/static/signup.html.
	@GetMapping("/signup")
	String signup() {
		return "forward:/signup.html";
	}

	// The document pages: each one renders a registered version, unmodified.
	@GetMapping("/legal/{slug}")
	ResponseEntity<String> legal(@PathVariable String slug, @RequestParam(name = "v", defaultValue = "current") String version) {
		String documentId = this.documents.get(slug);
		if (documentId == null) {
			return ResponseEntity.notFound().build();
		}
		Answer<DocumentContent> answer = this.esc.call(HttpMethod.GET, "/documents/{id}/versions/{version}/content",
				DocumentContent.class, null, null, documentId, version);
		if (answer.status() != 200 || answer.body().html() == null) {
			return ResponseEntity.notFound().build();
		}
		// The version ID goes into an attribute, so it is escaped. The document HTML is written as it is.
		String page = "<!doctype html><meta charset=\"utf-8\"><article data-esc-document=\""
				+ HtmlUtils.htmlEscape(answer.body().versionId()) + "\">" + answer.body().html() + "</article>";
		return ResponseEntity.ok().contentType(new MediaType(MediaType.TEXT_HTML, StandardCharsets.UTF_8)).body(page);
	}

	// Step 4: create the session with the secret key. The browser gets the client token only.
	@PostMapping("/api/ceremony")
	@ResponseBody
	ResponseEntity<Map<String, Object>> ceremony(HttpServletRequest request) {
		// The page that runs the ceremony: the origin the browser reports, or the scheme and host the server saw.
		String origin = request.getHeader(HttpHeaders.ORIGIN);
		if (origin == null) {
			origin = ServletUriComponentsBuilder.fromContextPath(request).build().toUriString();
		}
		Answer<Session> answer = this.esc.call(HttpMethod.POST, "/sessions", Session.class, Map.of(
				"profile", this.profileId,
				"signer", SIGNER,
				"documents", List.of(
						Map.of("document", this.documents.get("terms"), "version", "current"),
						Map.of("document", this.documents.get("privacy"), "version", "current")),
				"context", Map.of("url", origin + "/signup", "locale", "en-US", "purpose", "account_signup")),
				"signup-" + SIGNER.get("external_id") + "-" + UUID.randomUUID());
		Session created = answer.body();
		if (answer.status() != 201) {
			String code = (created != null && created.error() != null) ? created.error().code() : "unknown";
			return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body(Map.of("error", code));
		}

		// Server-owned state: the servlet session. The data stays in the memory of this server,
		// and the browser holds only the session ID in the JSESSIONID cookie.
		HttpSession session = request.getSession();
		session.setAttribute("signerId", SIGNER.get("external_id"));
		session.setAttribute("versionIds", created.documents().findValuesAsString("version_id").stream().sorted().toList());
		// The documents go to the browser as the API sent them: a JsonNode is written unchanged.
		return ResponseEntity.ok(Map.of("clientToken", created.clientToken(), "apiUrl", created.apiUrl(), "documents", created.documents()));
	}

	// Step 6: confirm the record with the secret key before the account exists.
	@PostMapping("/api/signup/confirm")
	@ResponseBody
	ResponseEntity<Map<String, Object>> confirm(@RequestBody ConfirmRequest body, HttpServletRequest request) {
		Answer<SignatureRecord> answer = this.esc.call(HttpMethod.GET, "/records/{id}", SignatureRecord.class, null, null,
				body.recordId() != null ? body.recordId() : "missing");
		SignatureRecord record = answer.body();
		HttpSession session = request.getSession(false); // false: a caller without a session does not get a new one

		boolean confirmed = answer.status() == 200 && session != null
				&& SEALED.contains(record.status())
				&& Boolean.valueOf(this.live).equals(record.livemode())
				&& record.signer() != null && record.signer().externalId().equals(session.getAttribute("signerId"))
				&& record.documents().stream().map(PinnedDocument::versionId).sorted().toList().equals(session.getAttribute("versionIds"));

		if (!confirmed) {
			log.info("refused");
			return ResponseEntity.status(HttpStatus.CONFLICT).body(Map.of("confirmed", false));
		}
		log.info("confirmed {} ({})", record.id(), record.status());
		// Only now create the account, and store record.id() and the record's receipt with it.
		return ResponseEntity.ok(Map.of("confirmed", true, "recordId", record.id()));
	}

	record ConfirmRequest(String recordId) {
	}

}
```

The signer is a fixed test person here. In your app it is the signed-in user or the account you are about to create.

The pinned versions are in the `HttpSession`, because it is the servlet container's own and keeps them on the server. The browser got a cookie named `JSESSIONID` with a 32-character ID, marked `HttpOnly`, and the signer ID and the version IDs stayed in the memory of Tomcat. `SameSite=Lax` comes from `application.properties`: without that line the cookie had no `SameSite` attribute at all. After a restart, the same cookie with a real record ID was answered `409`.

The confirm route asks for the session with `getSession(false)`. A method parameter of type `HttpSession` creates a session for every caller: in a test, a `POST` with no cookie got a new `JSESSIONID`. With `getSession(false)` it got none.

`context.url` is built from the `Origin` header the browser sends with the `POST`. A request without one falls back to the scheme and host the server saw, and all of them come from the client. A request with `Origin: https://evil.example` was refused by the API with `domain_mismatch`, and the route answered `502`. So was a request with no `Origin` and `Host: evil.example`.

Start the app from the shell that loaded `.env`:

```bash
mvn spring-boot:run
```

```text
 :: Spring Boot ::                (v4.2.0)

2026-11-26T02:09:59.801Z  INFO 52 --- [           main] o.s.boot.tomcat.TomcatWebServer          : Tomcat started on port 8080 (http) with context path '/'
2026-11-26T02:09:59.808Z  INFO 52 --- [           main] c.e.quickstart.QuickstartApplication     : Started QuickstartApplication in 2.168 seconds (process running for 2.61)
```

## Step 5. Attach the ceremony in the browser

The browser SDK renders nothing. It observes the checkbox, the notice, the links and the button you built, and reports each step from the signer's browser straight to Esign Comply. Save the page as `src/main/resources/static/signup.html`:

```html file="src/main/resources/static/signup.html"
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Create account</title>
    <style>
      body { font: 16px/1.5 system-ui, sans-serif; max-width: 480px; margin: 48px auto; padding: 0 20px; }
      a { color: #0b57d0; text-decoration: underline; }
      button { font: inherit; padding: 10px 16px; }
    </style>
  </head>
  <body>
    <h1>Create account</h1>
    <form id="signup">
      <div id="assent">
        <!-- The page is on screen before the script has a session, so the box stays disabled until the SDK watches it. -->
        <label><input id="agree" type="checkbox" disabled /> I agree to the Terms of Service and Privacy Notice</label>
        <p>
          By checking the box and clicking Create account, you agree to the
          <a id="tos-link" href="/legal/terms">Terms of Service</a> and acknowledge the
          <a id="privacy-link" href="/legal/privacy">Privacy Notice</a>.
        </p>
        <button id="create-account" type="submit" disabled>Create account</button>
      </div>
      <p id="message" role="alert"></p>
    </form>

    <script src="https://esigncomply.com/sdk/v1/esigncomply.js"></script>
    <script type="module">
      const agree = document.querySelector("#agree");
      const submit = document.querySelector("#create-account");
      const message = document.querySelector("#message");

      // Your server creates the session and returns only the client token and the pinned documents.
      const response = await fetch("/api/ceremony", { method: "POST" });
      const { clientToken, apiUrl, documents } = await response.json();

      const ceremony = await EsignComply.attach({ clientToken, apiUrl });
      ceremony.on("change", ({ remainingSteps }) => {
        submit.disabled = remainingSteps.some((step) => step !== "signature.applied");
      });

      // Point each link at the exact version this session pinned, then report it.
      const links = [document.querySelector("#tos-link"), document.querySelector("#privacy-link")];
      for (const [i, link] of links.entries()) {
        link.search = "?v=" + documents[i].version_id;
        await ceremony.presentDocument({ versionId: documents[i].version_id, mode: "hyperlink", link });
      }
      await ceremony.observeAssent({
        region: document.querySelector("#assent"), // notice, links, checkbox, button
        checkbox: agree,
        submit,
      });
      agree.disabled = false; // the SDK watches the box from here on. Only the user ticks it.

      document.querySelector("#signup").addEventListener("submit", async (event) => {
        event.preventDefault();
        try {
          const result = await ceremony.complete(); // the signing act, from the signer's own click
          // The result came to the browser. Your server confirms the record before anything is granted.
          const confirmed = await fetch("/api/signup/confirm", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ recordId: result.recordId }),
          });
          message.textContent = confirmed.ok
            ? `Account created. Record ${result.recordId}`
            : "We could not confirm whether your acceptance was recorded. Please wait while we check.";
        } catch (error) {
          message.textContent = error.message;
        }
      });
    </script>
  </body>
</html>
```

Spring Boot serves `static/` from the classpath, and the `signup` method forwards `/signup` to the file. Under `mvn spring-boot:run` the app serves the copy in `target/classes`: an edit of the page did not show until the app was restarted.

Open [http://localhost:8080/signup](http://localhost:8080/signup). The button stays disabled until the box is ticked. Tick it, click **Create account**, and the page shows:

```text
Account created. Record rec_yNSNVc7CnKUV47BiPg0x
```

The checkbox starts unchecked and disabled. The page is on screen before the script has a session, and the script enables the box once the SDK observes it. In a test without `disabled` and with the session request held back, a box ticked in that time stayed ticked, and the SDK reported a finding for [CR-01](https://esigncomply.com/docs/conformance.md#cr-01) at Block level: the control had already been used when the SDK started watching it. With `disabled`, the same early click did nothing. One page load sent one `POST /api/ceremony`.

Each link opens a document page on your own server that renders the registered version. The `legal` method builds the page as a string, escapes only the version ID, which goes into an attribute, and sets the content type itself. In a test with `HtmlUtils.htmlEscape()` around the document, the page showed the tags as text and the SDK reported a finding for [CR-08](https://esigncomply.com/docs/conformance.md#cr-08) at Block level: the page behind the link did not match the registered version. The explicit content type matters too: a method that returned the string with `@ResponseBody` alone was sent as `text/plain` to a client that accepts anything, and as `text/html` to a browser.

## Step 6. Confirm the record on the server

The result of `complete()` was delivered to the browser, so your server does not trust it. The `confirm` method reads the record with the secret key and grants access only when four things hold: the status is `recorded`, `timestamped` or `anchored`; `livemode` is what this deployment expects; the signer is the one in the session; and the document versions are exactly the ones this server pinned there. This step is never optional.

The app logs one line for each confirmation:

```text
2026-11-26T11:45:45.706Z  INFO 1 --- [nio-8080-exec-6] c.example.quickstart.SignupController    : confirmed rec_yNSNVc7CnKUV47BiPg0x (recorded)
```

A record ID that was made up is refused with status `409`. So is a real record ID sent without the session cookie, or with a session ID the server never issued:

```bash
curl -s -X POST http://localhost:8080/api/signup/confirm \
  -H "Content-Type: application/json" -d '{"recordId":"rec_made_up"}'
```

```json
{"confirmed":false}
```

That request carried no token of any kind, and Spring let it through to the method: CSRF protection is part of Spring Security, and this project does not have it. In the test a `POST` with no token and the `Origin` of another site reached the `confirm` method, which refused the made-up record. What refuses a forged confirmation here is the check itself. If your app has Spring Security, send its CSRF token with both `POST` requests.

A `POST` with no JSON never reaches the method. Spring answered `400` to an empty body and `415` to a body with no JSON content type.

See [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md) for the webhook that backs this route up when the browser closes early.

## Step 7. Check the result

Open the dashboard and choose **Records**. The test record is there with what was observed, what was asserted, and its evidence report, watermarked TEST.

Then run the conformance check against the page. It opens the page in headless Chromium at three window sizes, signs as a visitor would, and tries four things that must be refused. One of them posts a made-up record ID to your confirm route. The checker is a Node.js command line tool, so it needs Node.js 20.19 or later, in a folder of its own:

```bash
mkdir -p esc-check && cd esc-check
npm init -y && npm install esigncomply playwright
npx playwright install chromium
npx esigncomply check --url http://localhost:8080/signup --callback http://localhost:8080/api/signup/confirm
```

The report for this page's code, shortened:

```text
Violations that must be refused
  REFUSED   Submit with the checkbox untouched      No record was made.
  REFUSED   Completion from another origin          The API answered 403 domain_mismatch.
  REFUSED   Programmatic click                      No record was made.
  REFUSED   Forged success posted to your callback  http://localhost:8080/api/signup/confirm answered 409.

Ceremonies
  390x844    record rec_Af3ymKJiZe5sKZf6wQZZ  session ses_QPuma3p9cjiiJJA3xswA, 5 events
  768x1024   record rec_am55FHvcYk1y4BL0ym9C  session ses_HuEoAiiMgq2BRTTbNFk3, 5 events
  1440x900   record rec_FqixpeCh51VCgEn1kqhV  session ses_tPE9EVEjk6xuuaNQKUNw, 5 events

Summary: 0 block, 0 warn, 27 pass.
```

The app logged a `confirmed` line for each of the three records.

Fix every finding marked `block` and read every finding marked `warn`. Each one names the rule the screen missed, the measurement and the fix. In test mode a finding never stops a record from being sealed, so read the report. The rules are on [Conformance rules](https://esigncomply.com/docs/conformance.md), and every flag of the command is on the [CLI page](https://esigncomply.com/docs/sdk/cli.md).

## Step 8. Go live

Going live takes three steps on the Esign Comply side. There is no plan to choose and no checkout: the Free plan records 10 live signatures a month.

1. Register your production domain and verify it. See [Register a domain](https://esigncomply.com/docs/guides/domains.md).
2. Add your organization's legal name, country and address under **Go live** in the dashboard.
3. Create a live key. It is shown once and starts with `esc_live_`.

Test and live share nothing, so create the documents and the profile again with the live key, or copy them to live from the dashboard, and use the live IDs in production.

Then switch the server over:

- Set the live key as `ESIGNCOMPLY_API_KEY` and set `ESIGNCOMPLY_LIVE=true` in the environment of the production process only. From then on the `confirm` method refuses every test record there, and the session cookie is marked `Secure`.
- Build the jar with `mvn package` and start it with `java -jar target/esigncomply-quickstart-0.0.1-SNAPSHOT.jar`. The jar holds the page and `application.properties`, and not `.env`. In the test it was 20 MB, it served `/signup` when it was started from another folder, and it recorded the signature shown in step 5.
- The `HttpSession` lives in the memory of one server, for 30 minutes without a request by default. With more than one instance, keep the pinned versions in your database. Store the record ID and the receipt beside the user either way.
- Behind a proxy that terminates TLS, the server sees `http`. In the test a request with `X-Forwarded-Proto: https` was seen as `http` by default, and as `https` with `server.request.header.forwarded.strategy` set to `web-server` or to `framework`. The session route does not depend on it, because the browser sends `Origin`.

In live mode `context.url` must be inside your registered domain, and browser calls are accepted only from it. By default a live signature with a finding at Block level is recorded and you are told at once which rule failed. Turn on blocking, on the dashboard's Conformance page, and it is refused before it is sealed. Run the check from step 7 until no finding is at Block level before you switch keys.

## Troubleshooting

- **`missing_api_key` from `/api/ceremony`.** The JVM has no `ESIGNCOMPLY_API_KEY` in its environment. Spring Boot does not read `.env`, and the app starts without the key: in the test it answered `502` with this code. Run `set -a; . ./.env; set +a` in the shell that starts the app. See [`missing_api_key`](https://esigncomply.com/docs/api/errors.md#missing_api_key).
- **`429` when the `confirm` method reads the record.** `call` waits for the seconds in `Retry-After`, 1 at least and 5 at most, and runs `send` again, up to twice. Nothing else is retried. In the test, four confirmations sent at once from the session that signed all answered `200`, two of them a second later than the others. The API's log showed why: two reads got `429` and passed on the next attempt. Four session requests sent at once went the same way. See [`rate_limit_exceeded`](https://esigncomply.com/docs/api/errors.md#rate_limit_exceeded). When the route answers `409` for a real record, the cause is a session that is gone: a restart, or 30 minutes without a request.
- **`recordId` is `null` in the `confirm` method.** The app sets `spring.jackson.property-naming-strategy=SNAKE_CASE`, and Jackson now expects `record_id` in the page's JSON. Take the property out and keep `@JsonNaming` on the records that read the API, or send `record_id` from the page.

## Questions about the Spring Boot quickstart

### Is there a Maven artifact for Esign Comply?

No. The server SDK exists for Node.js only. A Spring Boot app calls the REST API directly, and this quickstart does it with `RestClient` and Jackson, so the build file lists two of Spring Boot's own starters and nothing else.

### Which Java and Spring Boot versions does the quickstart need?

It was run on Spring Boot 4.2.0 with Java 25. Spring Boot 4.2.0 requires at least Java 17, and the build file sets `java.version` to 25: change that line for an older JDK. The imports from `tools.jackson` are Jackson 3, the default JSON library of Spring Boot 4.

### Can Spring Boot read the .env file itself?

Not on its own. With the variables missing from the environment and `.env` in the working directory, the session route answered `502` with `missing_api_key`. With `spring.config.import=optional:file:.env[.properties]` the file was read as properties in a test: `${ESIGNCOMPLY_API_KEY}` resolved then, `${esigncomply.api.key}` did not, and a quoted value kept its quotes.

### Can the document page be a Thymeleaf template?

Yes, with `th:utext`. In a test with Thymeleaf 3.1.7, `th:text` printed the document with its tags escaped, and `th:utext` printed it as it is. The registered version is HTML that came from the API with your secret key, and the page has to render it unmodified.

### Why did an edit of signup.html not show?

Because `mvn spring-boot:run` serves the copy of the page in `target/classes`, which Maven made when the app started. In the test the running app kept serving the old page after the file under `src/main/resources/static` had changed. Restart the app to see the edit.

### Does the Spring Boot quickstart need a domain or a card?

No. Test mode works on `localhost` with a test key, no card and no domain. You register and verify a domain only when you go live, and the Free plan then records 10 live signatures a month.

## Next steps

- [E-signatures and clickwrap for Spring Boot](https://esigncomply.com/spring-boot): what the integration gives you on this stack, with the things to watch for.
- [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md): the checks in step 6 and the `record.completed` webhook.
- [Sessions API](https://esigncomply.com/docs/api/sessions.md) and [Records API](https://esigncomply.com/docs/api/records.md): every field of the two calls this server makes.
- [Add e-signatures and clickwrap with Node.js](https://esigncomply.com/docs/quickstart/nodejs.md): the same flow with the server SDK.
- [All quickstarts](https://esigncomply.com/docs/quickstart.md#quickstarts-by-stack-and-platform).
