JVM CAPTCHA Integration
The following tutorial will guide you on how to integrate the TrustCaptcha CAPTCHA solution into your Java, Kotlin, Groovy or Scala backend to retrieve and evaluate the CAPTCHA verification result.
Quick start
Section titled “Quick start”If you only need the simple case, the static shortcut is the shortest path:
import com.trustcomponent.trustcaptcha.TrustCaptcha;import com.trustcomponent.trustcaptcha.model.VerificationResult;
VerificationResult result = TrustCaptcha.getVerificationResult("<your_api_key>", "<verification_token_from_the_client>");if (!result.isVerificationPassed() || result.getScore() > 0.5) { // possibly an automated request}import com.trustcomponent.trustcaptcha.TrustCaptcha
val result = TrustCaptcha.getVerificationResult("<your_api_key>", "<verification_token_from_the_client>")if (!result.verificationPassed || result.score > 0.5) { // possibly an automated request}For everything beyond that — custom timeouts, a proxy, a custom API host — use the builder further down.
Preparation
Section titled “Preparation”You should have already completed the following steps before you start with CAPTCHA validation in your JVM backend.
Read the basic Information: For a basic overview, please read the get started guide. We also recommend that you familiarize yourself with the technical concept of TrustCaptcha.
Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.
A frontend with TrustCaptcha: Integrate the TrustCaptcha widget into your frontend. Go to the CAPTCHA widget guide.
Existing JVM project: You need a JVM project in which you want to integrate TrustCaptcha.
Verification token: You need the verification token from your frontend, which you receive every time you successfully solve the CAPTCHA.
Follow the three steps below to retrieve and evaluate the CAPTCHA verification result in your JVM backend.
You can find the source code of our JVM CAPTCHA integration on Github.
1. Add dependency
Section titled “1. Add dependency”To use the TrustCaptcha JVM library, you first need to add the corresponding dependencies to your project.
<dependency> <groupId>com.trustcomponent</groupId> <artifactId>trustcaptcha</artifactId> <version>3.0.0</version></dependency>dependencies { // Other dependencies implementation 'com.trustcomponent:trustcaptcha:3.0.0'}dependencies { // Other dependencies implementation("com.trustcomponent:trustcaptcha:3.0.0")}libraryDependencies ++= Seq( // Other dependencies "com.trustcomponent" % "trustcaptcha" % "3.0.0",)You can find our TrustCaptcha JVM package on Maven Central.
2. Fetch result
Section titled “2. Fetch result”In the next step, retrieve the CAPTCHA result from our servers.
If the CAPTCHA widget has been successfully solved in the frontend, you will receive a so-called verification token. Send this to your backend. You will also need an api-key. You can manage your API keys in the dashboard of your CAPTCHA.
Use the TrustCaptcha class of our JVM integration to retrieve the verification result from our servers. For the simple case use the static shortcut shown right below; for advanced configuration (custom API host, timeouts, proxy) use the builder/constructor variant further down on this page.
// Retrieving the verification resultVerificationResult verificationResult;try { verificationResult = TrustCaptcha.getVerificationResult("<your_api_key>", "<verification_token_from_the_client>");} catch (CaptchaFailureException e) { // Fetch verification result failed - handle error}// Retrieving the verification resultval verificationResult = try { TrustCaptcha.getVerificationResult("<your_api_key>", "<verification_token_from_the_client>")} catch (e: CaptchaFailureException) { // Fetch verification result failed - handle error}// Retrieving the verification resultVerificationResult verificationResulttry { verificationResult = TrustCaptcha.getVerificationResult("<your_api_key>", "<verification_token_from_the_client>")} catch (CaptchaFailureException e) { // Fetch verification result failed - handle error}// Retrieving the verification resultvar verificationResult: VerificationResult = nulltry { verificationResult = TrustCaptcha.getVerificationResult("<your_api_key>", "<verification_token_from_the_client>")} catch { case e: CaptchaFailureException => // Fetch verification result failed - handle error}3. Evaluate the result
Section titled “3. Evaluate the result”Once you have successfully fetched the verification result, you can plan your next steps based on it. A concrete overview of all the information contained in the verification result and their respective meanings can be found in the result validation overview.
// Act on the verification resultif (!verificationResult.isVerificationPassed() || verificationResult.getScore() > 0.5) { logger.warn("Verification failed or bot score > 0.5 – possible automated request.");}// Act on the verification resultif (!verificationResult.verificationPassed || verificationResult.score > 0.5) { logger.warn("Verification failed or bot score > 0.5 – possible automated request.")}// Act on the verification resultif (!verificationResult.isVerificationPassed() || verificationResult.getScore() > 0.5) { logger.warn("Verification failed or bot score > 0.5 – possible automated request.")}// Act on the verification resultif (!verificationResult.isVerificationPassed || verificationResult.getScore > 0.5) { logger.warn("Verification failed or bot score > 0.5 – possible automated request.")}Configured usage
Section titled “Configured usage”If you need more control — a different API host, custom timeouts, or a proxy — use the builder. The builder is the only way to configure these options; the static shortcut always uses the defaults.
import com.trustcomponent.trustcaptcha.TrustCaptcha;import java.net.InetSocketAddress;import java.net.Proxy;
TrustCaptcha trustCaptcha = TrustCaptcha.builder("<your_api_key>") .apiHost("https://api.trustcomponent.com") .connectTimeoutMs(3000) .readTimeoutMs(5000) .proxy("proxy.example.com", 8080) .build();
VerificationResult result = trustCaptcha.getVerificationResult("<verification_token_from_the_client>");import com.trustcomponent.trustcaptcha.TrustCaptcha
val trustCaptcha = TrustCaptcha.builder("<your_api_key>") .apiHost("https://api.trustcomponent.com") .connectTimeoutMs(3000) .readTimeoutMs(5000) .proxy("proxy.example.com", 8080) .build()
val result = trustCaptcha.getVerificationResult("<verification_token_from_the_client>")A built TrustCaptcha instance is immutable and thread-safe: build it once at application startup and reuse it for as many requests as you like.
Builder options
Section titled “Builder options”| Method | Type | Default | Description |
|---|---|---|---|
builder(apiKey) | String (required) | — | Your API key. Must not be null or empty. |
.apiHost(...) | String | https://api.trustcomponent.com | Override the API host. Useful for staging environments. |
.connectTimeoutMs(...) | int | 3000 | Connect timeout in milliseconds. |
.readTimeoutMs(...) | int | 5000 | Read timeout in milliseconds. |
.proxy(host, port) | String, int | none | Convenience overload — configures an HTTP proxy at host:port. |
.proxy(java.net.Proxy) | java.net.Proxy | none | Pass a fully built java.net.Proxy instance for advanced setups. |
.build() | — | — | Returns the configured TrustCaptcha instance. |
Failover
Section titled “Failover”Our service runs in a high-availability setup, so outages are rare in practice. If you want maximum availability — even for the unlikely case where our service is unreachable — you can decide upfront how your backend should react, so your forms and processes don’t block during such an event. Read the Failover behavior page first — it covers the concept, the required widget-side opt-in, the operational checklist, and how to filter failover-derived results in high-security flows.
Once you’ve decided on a policy, the library surfaces the two relevant cases as typed exceptions, both extending FailoverException:
ServerUnreachableException— high-trust (your backend cannot reach our servers). For example: allow the request and log the incident.ClientReportedServerUnreachableException(HTTP412) — low-trust (the widget claimed a failover, but the backend reaches us fine). For example: reject or soft-challenge.
try { VerificationResult result = trustCaptcha.getVerificationResult(token); // Handle the result as you normally would (isVerificationPassed(), getScore(), your own policy).} catch (ServerUnreachableException e) { // Example: our servers are unreachable. Allow + log.} catch (ClientReportedServerUnreachableException e) { // Example: widget claimed an outage but the backend reaches us. Reject or soft-challenge.}Exceptions
Section titled “Exceptions”When the result cannot be retrieved successfully the library raises a typed exception. All exceptions extend CaptchaFailureException so they can be caught with a single catch clause.
| Exception | When it is thrown |
|---|---|
ApiKeyInvalidException | The API key was rejected (HTTP 403). |
VerificationTokenInvalidException | The verification token could not be parsed (malformed base64 / missing verificationId). |
VerificationNotFoundException | No verification was found for the given verification token (HTTP 404). |
VerificationNotFinishedException | The verification has not yet been completed by the user (HTTP 423). |
VerificationResultExpiredException | The result has expired and can no longer be retrieved (HTTP 410). |
VerificationResultRetrievalLimitReachedException | The result has reached its maximum retrieval count (HTTP 429). |
ServerUnreachableException | The TrustCaptcha server could not be reached at all (connection error / timeout). Subclass of FailoverException. See Failover behavior. |
ClientReportedServerUnreachableException | The widget claimed a failover, but the gateway has no record of a recent outage (HTTP 412). Subclass of FailoverException. See Failover behavior. |
Example implementation
Section titled “Example implementation”The following example shows a possible implementation of TrustCaptcha in a JVM backend.
In this example: When a POST request is sent to /api/example, the CAPTCHA verification token is sent to the JVM backend in the request body. In the backend, our library is used to retrieve the CAPTCHA verification result from our servers and evaluate it. If the verification fails or the bot score exceeds 0.5, a warning is displayed. In addition, the entire verification result is returned to the client.
Hint: The steps and thresholds shown are examples and should be adapted to your individual requirements in your specific use case.
The complete example including source code can be found on Github.
import com.trustcomponent.trustcaptcha.TrustCaptcha;import com.trustcomponent.trustcaptcha.exception.CaptchaFailureException;import com.trustcomponent.trustcaptcha.model.VerificationResult;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.*;
@RestController@CrossOrigin(originPatterns = {"http://localhost:[*]", "http://127.0.0.1:[*]"})public class ApiController {
private static final Logger logger = LoggerFactory.getLogger(ApiController.class);
@PostMapping("/api/example") public ResponseEntity<VerificationResult> postApiExample(@RequestBody VerificationRequest verificationRequest) {
// Retrieving the verification result VerificationResult verificationResult; try { verificationResult = TrustCaptcha.getVerificationResult("<your_api_key>", verificationRequest.getVerificationToken()); } catch (CaptchaFailureException e) { // Fetch verification result failed - handle error throw new RuntimeException(e); }
// Act on the verification result if (!verificationResult.isVerificationPassed() || verificationResult.getScore() > 0.5) { logger.warn("Verification failed or bot score > 0.5 – possible automated request."); }
return ResponseEntity.ok(verificationResult); }}public class VerificationRequest {
private String verificationToken;
public String getVerificationToken() { return verificationToken; }
public void setVerificationToken(String verificationToken) { this.verificationToken = verificationToken; }}Next steps
Section titled “Next steps”Once you have integrated the TrustCaptcha widget into your frontend and the CAPTCHA result validation into your backend, you can use TrustCaptcha to its full extent. However, we still recommend the following additional technical and organizational measures:
Security rules: You can find many security settings for your CAPTCHA in the CAPTCHA settings. These include, for example, authorized websites, CAPTCHA bypass for specific IP addresses, bypass keys, IP based blocking, geoblocking, individual difficulty and duration of the CAPTCHA, and much more. Learn more about the security rules.
Privacy & GDPR compliance: Include a passage in your privacy policy that refers to the use of TrustCaptcha. We also recommend that you enter into a data processing agreement with us to stay GDPR-compliant. Learn more about data protection.
Accessibility & UX: Customize TrustCaptcha to your website so that your website is as accessible as possible and offers the best possible user experience. More about accessibility.
Failover behavior: Decide how your backend should behave when our service is temporarily unreachable. This is particularly important for high-availability flows where blocking real users during an outage is worse than letting through a small amount of unverified traffic. Learn more about failover behavior.
Testing: If you use automated testing, make sure that the CAPTCHA does not block it. Learn more about testing.