Micronaut CAPTCHA Integration
This recipe shows how to integrate TrustCaptcha into a Micronaut application. The frontend setup is the same as for any other JVM application — this page focuses on the server-side validation.
The setup section gets you to a working integration in three small steps using a controller method directly. Below it, an optional refactor section shows the more reusable Micronaut-idiomatic approach (a Bean Validation annotation backed by a @Singleton validator).
Preparation
Section titled “Preparation”You should have already completed the following steps before you wire TrustCaptcha into your Micronaut application.
Read Get-Started: Get a quick overview of the concepts behind TrustCaptcha and the integration process in get started.
Existing CAPTCHA: If you don’t have a CAPTCHA yet, sign in or create a new user account. Then create a new CAPTCHA.
1. Embed the frontend widget
Section titled “1. Embed the frontend widget”First, add the TrustCaptcha script to your page (see the JavaScript Guide for version pinning and self-hosting options).
Then place the <trustcaptcha-component> element inside your form. The widget appends a hidden tc-verification-token field on submit, which your Micronaut controller receives like any other form input.
<script type="module" src="https://cdn.trustcomponent.com/trustcaptcha/3.0.x/trustcaptcha.esm.min.js"></script>
<form method="post" action="/contact" enctype="application/x-www-form-urlencoded"> <label>Email</label> <input type="email" name="email" required>
<trustcaptcha-component sitekey="<your_site_key>"></trustcaptcha-component>
<button type="submit">Send</button></form>See the Widget Overview for the full property reference.
2. Install the JVM SDK
Section titled “2. Install the JVM SDK”dependencies { implementation 'com.trustcomponent:trustcaptcha:3.0.0'}3. Validate the token in your controller
Section titled “3. Validate the token in your controller”package com.example.contact;
import com.trustcomponent.trustcaptcha.TrustCaptcha;import com.trustcomponent.trustcaptcha.exception.CaptchaFailureException;import com.trustcomponent.trustcaptcha.model.VerificationResult;
import io.micronaut.http.HttpResponse;import io.micronaut.http.MediaType;import io.micronaut.http.annotation.Body;import io.micronaut.http.annotation.Controller;import io.micronaut.http.annotation.Consumes;import io.micronaut.http.annotation.Post;
import java.util.Map;
@Controller("/contact")public class ContactController {
@Post @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public HttpResponse<String> submit(@Body Map<String, String> form) { // In production, load from configuration: @Value("${trustcaptcha.api-key}") String apiKey = "<your_api_key>"; String token = form.getOrDefault("tc-verification-token", "");
VerificationResult result; try { result = TrustCaptcha.getVerificationResult(apiKey, token); } catch (CaptchaFailureException e) { return HttpResponse.badRequest("CAPTCHA verification failed."); }
if (!result.isVerificationPassed() || result.getScore() > 0.5) { return HttpResponse.badRequest("CAPTCHA verification failed."); }
// CAPTCHA passed — request data is safe to use. // ... your business logic ...
return HttpResponse.ok("Thanks!"); }}That’s it — the form is now protected. For real deployments, move the API key out of the source code (see the comment) and consider explicit failover handling — see Failover Behavior for the reasoning and a code template.
Refactor: extract to a Bean Validation annotation
Section titled “Refactor: extract to a Bean Validation annotation”If you protect more than one endpoint, the most idiomatic Micronaut approach is a custom Bean Validation annotation. The verification call then runs automatically whenever a controller parameter is annotated with @Valid.
Configure the API key
Section titled “Configure the API key”trustcaptcha: api-key: ${TRUSTCAPTCHA_API_KEY}Add the validation dependency:
dependencies { implementation 'io.micronaut.validation:micronaut-validation' annotationProcessor 'io.micronaut.validation:micronaut-validation-processor'}Create the annotation and validator
Section titled “Create the annotation and validator”package com.example.captcha;
import jakarta.validation.Constraint;import jakarta.validation.Payload;import java.lang.annotation.*;
@Documented@Constraint(validatedBy = {})@Target({ElementType.FIELD, ElementType.PARAMETER})@Retention(RetentionPolicy.RUNTIME)public @interface TrustCaptchaToken { String message() default "CAPTCHA verification failed."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {};}package com.example.captcha;
import com.trustcomponent.trustcaptcha.TrustCaptcha;import com.trustcomponent.trustcaptcha.exception.CaptchaFailureException;import com.trustcomponent.trustcaptcha.model.VerificationResult;
import io.micronaut.context.annotation.Value;import io.micronaut.core.annotation.AnnotationValue;import io.micronaut.validation.validator.constraints.ConstraintValidator;import io.micronaut.validation.validator.constraints.ConstraintValidatorContext;
import jakarta.inject.Singleton;
@Singletonpublic class TrustCaptchaTokenValidator implements ConstraintValidator<TrustCaptchaToken, String> {
@Value("${trustcaptcha.api-key}") String apiKey;
@Override public boolean isValid(String value, AnnotationValue<TrustCaptchaToken> annotationMetadata, ConstraintValidatorContext context) { if (value == null || value.isBlank()) return false; try { VerificationResult result = TrustCaptcha.getVerificationResult(apiKey, value); return result.isVerificationPassed() && result.getScore() <= 0.5; } catch (CaptchaFailureException e) { return false; } }}Use the annotation on a DTO
Section titled “Use the annotation on a DTO”package com.example.contact;
import com.example.captcha.TrustCaptchaToken;import io.micronaut.core.annotation.Introspected;import io.micronaut.serde.annotation.Serdeable;import jakarta.validation.constraints.Email;import jakarta.validation.constraints.NotBlank;
@Introspected@Serdeablepublic class ContactForm {
@NotBlank @Email private String email;
@TrustCaptchaToken private String tcVerificationToken;
// getters and setters}Java identifiers can’t contain dashes, so the DTO field is tcVerificationToken while the widget posts tc-verification-token. The simplest fix is to align the names by setting token-field-name="tcVerificationToken" on the widget.
@Post@Consumes(MediaType.APPLICATION_FORM_URLENCODED)public HttpResponse<String> submit(@Body @Valid ContactForm form) { // CAPTCHA already validated by the @TrustCaptchaToken annotation. return HttpResponse.ok("Thanks!");}Adding @Valid on the @Body parameter triggers all Bean Validation constraints on ContactForm, including @TrustCaptchaToken. Validation failures are surfaced as ConstraintViolationException, which Micronaut maps to a 400 Bad Request response by default.
Bean Validation processor. Micronaut’s validation is compile-time wired through the micronaut-validation-processor. Make sure the processor is on your annotationProcessor configuration; otherwise the @TrustCaptchaToken constraint silently doesn’t run.
Reactive endpoints. The JVM SDK is blocking. If your controller method returns Mono<...> or Flux<...>, perform the verification on a non-event-loop scheduler — e.g. Mono.fromCallable(() -> TrustCaptcha.getVerificationResult(...)).subscribeOn(Schedulers.boundedElastic()).
Singleton SDK instance. For configured usage (custom timeouts, proxy, custom API host), declare a @Factory-produced @Singleton TrustCaptcha bean built via TrustCaptcha.builder(apiKey)... and inject it into the validator instead of using the static shortcut. See the JVM Guide for the builder API.
Next steps
Section titled “Next steps”Once you have wired TrustCaptcha into your Micronaut application, 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.