Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install quarkus-application-development@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin quarkus-application-development v1.0.0 follows the Agent Plugins spec.
gh skills-hub install quarkus-application-development Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/quarkus-application-development/ Extract the ZIP to .github/skills/ in your repo. The folder name must match quarkus-application-development for Copilot to auto-discover it.
Skill Files (7)
SKILL.md 4.5 KB
---
name: quarkus-application-development
description: 'Write Quarkus application code: REST with Quarkus REST, validation, exception mappers, OpenAPI, configuration, CDI (ArC), Hibernate ORM with Panache, Mutiny and virtual threads, Reactive Messaging with Kafka, OIDC security, health, metrics, OpenTelemetry, fault tolerance, REST Client, scheduler and cache. Use when implementing or changing features in an existing Quarkus project.'
---
# Quarkus Application Development
Scope: application code inside an existing Quarkus project. Project creation is `create-quarkus-project`; Dev Services and tests are `quarkus-dev-services-and-testing`; native and container images are `quarkus-native-and-container`; core JPA mapping and query design can use the optional `java-hibernate-jpa` skill if installed (otherwise see the Hibernate ORM guide, <https://quarkus.io/guides/hibernate-orm>, and the Jakarta Persistence docs).
## Agent rules
1. Detect first: read `pom.xml`/`build.gradle` for `quarkus.platform.version`, the Java release, and the extensions already present. Keep the version; use what the project already uses (for example `quarkus-resteasy*` stays if present).
2. Add extensions with `quarkus extension add <name>` or `./mvnw quarkus:add-extension -Dextensions=<name>`; never guess artifact ids or versions by hand (the platform BOM manages them). List candidates with `quarkus extension list --installable --search=<text>`.
3. Ask the user before adding Kafka, OIDC/Keycloak or any new infrastructure dependency (they start containers in dev/test and change deployment needs).
4. Never use the Spring compatibility extensions (`quarkus-spring-*`) unless the project already does.
5. Verify with dev mode (`./mvnw quarkus:dev`, then `/q/dev-ui`) and `./mvnw verify`; write a `@QuarkusTest` per feature. Do not claim something works without running it.
6. Use `jakarta.*` imports, records for DTOs, thin resources delegating to services.
7. Never hard-code secrets or add credentials to `application.properties`; see `references/config-cdi.md`.
## Quick decisions
| Need | Use | Details |
|---|---|---|
| JSON REST API | `quarkus-rest-jackson`, `quarkus-hibernate-validator`, `quarkus-smallrye-openapi` | `references/rest.md` |
| Typed config | `@ConfigMapping`; `@ConfigProperty` for single values | `references/config-cdi.md` |
| Beans | `@ApplicationScoped` (default), `@Singleton` only for plain stateless holders | `references/config-cdi.md` |
| Database | `quarkus-hibernate-orm-panache` + JDBC driver, repository pattern | `references/persistence.md` |
| Async / blocking | Imperative by default; `@RunOnVirtualThread` or `Uni` when needed | `references/reactive-messaging.md` |
| Messaging | `quarkus-messaging-kafka` (SmallRye Reactive Messaging) | `references/reactive-messaging.md` |
| AuthN/AuthZ | `quarkus-oidc`, `@RolesAllowed` | `references/security-oidc.md` |
| Ops | `quarkus-smallrye-health`, `quarkus-micrometer-registry-prometheus`, `quarkus-opentelemetry`, `quarkus-smallrye-fault-tolerance` | `references/observability-resilience.md` |
| Outbound HTTP, scheduling, caching | `quarkus-rest-client-jackson`, `quarkus-scheduler`, `quarkus-cache` | `references/observability-resilience.md` |
## Pitfalls that cost time
- Quarkus resolves CDI at build time: an unused bean may be removed. Beans only looked up programmatically need `@Unremovable`.
- Do not read or write public fields of a normal-scoped bean (`@ApplicationScoped`) from another bean or test: you hit the client proxy, not the instance (verified: a counter field read through the proxy returned 0). Use methods.
- Do not block on the event loop (`@NonBlocking` methods, `Uni`/`Multi` return types running on I/O threads). Remove any existing `@NonBlocking` from the method (combining it with `@Blocking` or `@RunOnVirtualThread` fails the build), then add `@Blocking` or `@RunOnVirtualThread` (see `references/reactive-messaging.md`).
- Changes to build-time properties need a rebuild; run-time properties can be overridden by env vars (`QUARKUS_DATASOURCE_JDBC_URL`).
- Do not configure URLs for databases/brokers/Keycloak in `%dev`/`%test`: that disables Dev Services.
- `drop-and-create` schema management is for dev/test only; use Flyway or Liquibase for production.
Verified on Quarkus 3.40.1 and 3.27.6 (Java 21 target, Maven) with a scaffolded app and `mvn verify` (15 tests: REST+validation+mapper, OpenAPI, config mapping, Panache on PostgreSQL Dev Services, Kafka Dev Service round trip, Keycloak Dev Service tokens, health, metrics, fault tolerance, cache, scheduler). Re-check names against the project's version.
config-cdi.md 5.5 KB
# Configuration and CDI (ArC)
## Configuration
Sources by precedence (high to low): system properties, environment variables, `.env` file in the working directory (loaded for packaged apps too, so do not ship it to production; put dev-only values under `%dev.`/`%test.` keys), `config/application.properties` next to the app, `application.properties` in the jar, MicroProfile defaults. Env var mapping: uppercase, non-alphanumerics become `_` (`greeting.max-length` -> `GREETING_MAX_LENGTH`).
### Profiles
`%dev.`, `%test.`, `%prod.` prefixes; `quarkus.profile=staging` or custom profiles work too. `quarkus:dev` is `dev`, tests are `test`, packaged apps are `prod`.
```properties
greeting.prefix=Hello
%dev.greeting.prefix=Dev hello
# Required in every profile (including custom ones such as staging): startup fails if API_KEY is missing
app.api-key=${API_KEY}
# Fallback only for dev and test
%dev.app.api-key=${API_KEY:dev-only-key}
%test.app.api-key=${API_KEY:dev-only-key}
```
Verified: with these settings a `@QuarkusTest` sees `Hello` (the `%dev` value is not applied in test) and `dev-only-key`.
### Secrets
Never commit real secrets. Supply them via env vars, Kubernetes secrets mounted as env/files, or a vault extension (`quarkus-vault`, `quarkus-kubernetes-config` with `quarkus.kubernetes-config.secrets`). Set no default in `%prod` so a missing secret fails fast. Property expressions that point at other keys are fine; keep credentials out of logs.
### `@ConfigMapping` vs `@ConfigProperty`
```java
@ConfigMapping(prefix = "greeting")
public interface GreetingConfig {
String prefix();
@WithDefault("10") int maxLength(); // greeting.max-length
Optional<String> suffix();
List<String> tags(); // greeting.tags=a,b
}
```
Verified: injected with `@Inject GreetingConfig config`, `maxLength()` returned the value from `greeting.max-length`, `suffix()` was empty, `tags()` was `[a, b]`. Nested groups are nested interfaces; `Map<String,...>` is supported. Add `@Valid`-style constraints with hibernate-validator on mapping methods when present; startup fails on violations.
- Use `@ConfigMapping` for any group of related properties (typed, validated at startup, documented in one place).
- Use `@ConfigProperty(name = "app.api-key") String key;` for a single value or when you need `defaultValue`. Also works on constructor params.
- Unknown properties under a mapped prefix can fail startup; keep that validation enabled to catch typos.
- Build-time vs run-time: `quarkus.*` build-time properties (marked in the config reference) are fixed at package time. Check the extension's guide before assuming an env var override works in the container.
## CDI with ArC
ArC is a build-time CDI Lite-style implementation, not full CDI: no portable extensions (use build-compatible extensions or Quarkus build steps), no decorators on all paths, and some features are different.
- **Build-time resolution**: injection points are validated at build; missing or ambiguous beans fail the build, not runtime.
- **Unused bean removal**: beans with no injection point, no observer, no producer use, and not annotated `@Unremovable` are removed. If you look them up with `Arc.container().instance(...)` or `CDI.current().select(...)` by dynamic type, add `@io.quarkus.arc.Unremovable`. Disable globally with `quarkus.arc.remove-unused-beans=none` only as a last resort.
- **Scopes**: `@ApplicationScoped` is lazy and proxied (supports interceptors, mocking, circular deps); default choice. `@Singleton` is not proxied (no client proxy, so no lazy init through the proxy and `@InjectMock` is not applicable): use it for stateless holders only. `@RequestScoped` per HTTP request; `@Dependent` is the default pseudo-scope (new instance per injection point).
- **No private injection**: use package-private fields or constructors. Quarkus recommends against private injected fields because they force reflection-based access. Prefer constructor injection (`@Inject` optional with a single constructor).
- **Proxy pitfalls (verified)**: `@ApplicationScoped` beans are called through a subclass proxy; reading a public field of such a bean from outside returns the proxy's own (default) value. Expose state with methods. Avoid `final` on bean classes and methods and private no-arg constructors on normal-scoped beans.
- **Startup logic**: `@Startup` on a bean, or `void onStart(@Observes StartupEvent e)`. Eager beans must not do slow blocking I/O on the main thread without care.
- **Interceptors**: define an `@InterceptorBinding` annotation and an `@Interceptor` with `@Priority`; ArC applies them at build time to bean classes only (not to arbitrary objects). ArC supports intercepted self-invocation, so a bean calling its own intercepted method (`@Transactional`, `@Retry`, `@CacheResult`) still triggers the interceptor.
- **Producers/events**: `@Produces` and `@Observes` work as usual. `@Priority` only orders synchronous `@Observes` methods; it does not make them async. Asynchronous observers use `@ObservesAsync` and are notified only by `Event.fireAsync(...)` (which returns a `CompletionStage`); `Event.fire(...)` notifies only synchronous observers.
- **Testing**: `@InjectMock` (`quarkus-junit-mockito`; `quarkus-junit5-mockito` on old versions) works for normal-scoped beans. See `quarkus-dev-services-and-testing`.
- **Debugging**: the Dev UI (`/q/dev-ui`) ArC page lists beans, removed beans and observers.
Logging: JBoss Logging (`org.jboss.logging.Logger`) or `@Inject Logger`, configured with `quarkus.log.*`; do not add Logback/Log4j directly.
observability-resilience.md 4.5 KB
# Observability, resilience, REST Client, scheduler, cache
All items below were exercised on Quarkus 3.40.1 and 3.27.6 unless marked "not verified".
## Health (`quarkus-smallrye-health`)
Endpoints: `/q/health`, `/q/health/live`, `/q/health/ready`, `/q/health/started`. Custom checks are CDI beans:
```java
@Readiness // or @Liveness / @Startup (org.eclipse.microprofile.health)
@ApplicationScoped
public class Ready implements HealthCheck {
public HealthCheckResponse call() { return HealthCheckResponse.up("demo"); }
}
```
Verified: `/q/health/ready` returned 200 with the check name. Extensions such as the JDBC datasource add their own readiness checks. Keep liveness trivial (no dependency checks, or the platform restarts pods during outages); put dependency checks in readiness.
## Metrics (`quarkus-micrometer-registry-prometheus`)
Prometheus scrape at `/q/metrics`. Inject `MeterRegistry` for custom meters (`registry.counter("demo.fallback").increment()` appeared as `demo_fallback_total`, verified). HTTP server and JVM meters are on by default. Use `@Counted`/`@Timed` (Micrometer annotations) where they are enough. Expose `/q/metrics` and `/q/health` only to the cluster/monitoring network (a separate management interface: `quarkus.management.enabled=true`, not verified here).
## OpenTelemetry (`quarkus-opentelemetry`)
Only traces are on by default. Metrics and logs are tech preview and disabled at build time: set `quarkus.otel.metrics.enabled=true` and `quarkus.otel.logs.enabled=true` to export them (checked against the Quarkus OpenTelemetry guide). HTTP, REST Client, JDBC (with `quarkus.datasource.jdbc.telemetry=true`) and messaging are instrumented. Point it at a collector with `quarkus.otel.exporter.otlp.endpoint=http://collector:4317` (verified only that without a collector the app logs "Failed to export ... Connection refused" to `localhost:4317` but works). Add custom spans with `@WithSpan` or inject `Tracer`. In dev mode, Quarkus Dev Services for observability (Grafana LGTM, `quarkus-observability-devservices-lgtm`) can supply a backend; not verified here. Do not set both Micrometer and OTel metrics export without a reason.
## Fault tolerance (`quarkus-smallrye-fault-tolerance`)
```java
@Retry(maxRetries = 2) @Fallback(fallbackMethod = "fb")
public String flaky() { throw new IllegalStateException(); }
String fb() { return "fallback"; }
```
Verified: the method executed 3 times (1 + 2 retries) and the fallback value was returned. Also `@Timeout`, `@CircuitBreaker`, `@Bulkhead`, `@RateLimit` (SmallRye extension). They are CDI interceptors on bean methods; ArC also intercepts self-invocation. Works with `Uni` return types (asynchronous, non-blocking). Always set a `@Timeout` on remote calls; do not retry non-idempotent operations.
## REST Client (`quarkus-rest-client-jackson`)
```java
@RegisterRestClient(configKey = "echo")
@Path("/greetings")
public interface EchoClient {
@GET @Path("/{n}") Greeting get(@PathParam("n") String n);
}
```
```properties
quarkus.rest-client.echo.url=${ECHO_URL:http://localhost:8081}
quarkus.rest-client.echo.read-timeout=5000
```
Inject with `@RestClient EchoClient echo;` (`org.eclipse.microprofile.rest.client.inject.RestClient`). Verified: bean injection and startup (the call itself was not exercised). Combine with `@Timeout`/`@Retry`; throw domain exceptions with `@ClientExceptionMapper`. In tests, stub the remote service with WireMock via a test resource (see `quarkus-dev-services-and-testing`).
## Scheduler (`quarkus-scheduler`)
`@Scheduled(every = "1s")` or `@Scheduled(cron = "{app.cron}")` on a bean method (verified: ticks incremented). Use `concurrentExecution = SKIP` to avoid overlaps. The scheduler is per instance; in a cluster use the `quarkus-quartz` extension with a shared JDBC store and `quarkus.quartz.clustered=true` (it defaults to `false`, so a JDBC store alone leaves schedulers uncoordinated), or a distributed lock, to run a job once. Scheduled methods run on a worker thread unless `@NonBlocking`/returns `Uni`; use `@RunOnVirtualThread` for blocking IO.
## Cache (`quarkus-cache`)
```java
@CacheResult(cacheName = "slow")
public String slow(String k) { ... }
```
Verified: two calls with the same key executed the method once. Configure with `quarkus.cache.caffeine."slow".maximum-size=10` and `expire-after-write=60S`. Also `@CacheInvalidate`, `@CacheInvalidateAll`, `@CacheKey`. Interceptor-based; ArC also intercepts self-invocation. Caches are per-instance in memory; use `quarkus-redis-cache` for shared caches (not verified here).
persistence.md 4.9 KB
# Persistence: Hibernate ORM with Panache
Core JPA mapping, associations, N+1 and query design: use the optional `java-hibernate-jpa` skill if it is installed; otherwise follow the Hibernate ORM guide (<https://quarkus.io/guides/hibernate-orm>). This file covers Quarkus specifics. Extensions: `quarkus-hibernate-orm-panache` + a JDBC driver such as `quarkus-jdbc-postgresql`.
## Config
```properties
# No URL/credentials in %dev/%test: PostgreSQL Dev Service starts automatically (Docker/Podman)
# Safe default for every profile (including custom ones such as staging); use Flyway/Liquibase for real schemas
quarkus.hibernate-orm.schema-management.strategy=none
# Recreate the schema only in dev and test
%dev.quarkus.hibernate-orm.schema-management.strategy=drop-and-create
%test.quarkus.hibernate-orm.schema-management.strategy=drop-and-create
%prod.quarkus.datasource.jdbc.url=${DB_URL}
%prod.quarkus.datasource.username=${DB_USER}
%prod.quarkus.datasource.password=${DB_PASSWORD}
```
`schema-management.strategy` verified on 3.40.1 and 3.27.6 (older docs use `quarkus.hibernate-orm.database.generation`; keep the project's form). Persistence units are configured in `application.properties`, not `persistence.xml`. Entities need no registration if they are in the application module.
## Active record vs repository (verified, PostgreSQL Dev Service)
```java
@Entity
public class Person extends PanacheEntity { // active record: id is generated, public fields
public String name;
public static Person findByName(String n) { return find("name", n).firstResult(); }
}
@Entity
public class Book { @Id @GeneratedValue public Long id; public String title; }
@ApplicationScoped
public class BookRepository implements PanacheRepository<Book> { // repository pattern
public List<Book> byTitle(String t) { return list("title", t); }
}
```
Prefer the repository pattern for non-trivial domains (testable, mockable with `@InjectMock`, keeps entities plain POJOs); use active record only for simple CRUD. For a non-`Long` id use `PanacheRepositoryBase<E, ID>` / `PanacheEntityBase`. Panache offers `find`, `list`, `stream`, `count`, `delete`, `update`, `persist`, `page(Page.of(i, size))` for pagination, `Sort`, and `project(Dto.class)` for projections. Panache queries accept shortened HQL (`"name"`, `"name = ?1"`, `"from Person where name = :n"` with `Parameters`).
## Transactions
```java
@ApplicationScoped
public class BookService {
@Inject BookRepository repo;
@Transactional // jakarta.transaction.Transactional
public Book add(String title) { Book b = new Book(); b.title = title; repo.persist(b); return b; }
}
```
- Put `@Transactional` on service (or resource) methods that write; ArC also intercepts self-calls, so a call to an annotated method on the same bean starts the transaction.
- Programmatic: `QuarkusTransaction.requiringNew().call(() -> ...)` (`io.quarkus.narayana.jta`), used in the verified tests to read back committed data.
- Reads outside a transaction work only inside an active CDI request context (e.g. an HTTP request) with `quarkus.hibernate-orm.request-scoped.enabled` left at its default `true`; in background tasks, scheduled jobs or messaging consumers wrap the read in a transaction (`@Transactional` or `QuarkusTransaction`); lazy associations must be fetched inside the transaction or via fetch joins/projections.
- Tests: `@TestTransaction` rolls back (see `quarkus-dev-services-and-testing`).
- Do not use `open-in-view`-style patterns; map to DTO records before returning from a resource.
## Panache Next / Quarkus Data (status)
`quarkus-data-hibernate` ("Quarkus Data Hibernate", Panache Next, Jakarta Data support) is tagged `status:experimental` on code.quarkus.io for 3.40.1 (checked via `https://code.quarkus.io/api/extensions`). Do not use it for production code or recommend a migration unless the user asks; stay on `quarkus-hibernate-orm-panache`. Re-check the tag before advising.
## Reactive (Hibernate Reactive) tradeoff
`quarkus-hibernate-reactive-panache` with `Uni`-based APIs and Vert.x SQL clients (`quarkus-reactive-pg-client`) fits fully reactive stacks, but: separate extension set from ORM (both can coexist, including on the default datasource with JDBC and reactive URLs, but they have separate persistence contexts, so keep each method on one stack), more limited feature set, harder debugging, no `@Transactional` blocking style (use `@WithTransaction`/`@WithSession`), and Java 21+ virtual threads give most of the scalability benefit with the simpler blocking ORM. Default to blocking ORM + `@RunOnVirtualThread` where concurrency matters; pick Hibernate Reactive only when the whole call chain is non-blocking. Not verified in this skill's build.
## REST Data Panache
`quarkus-hibernate-orm-rest-data-panache` generates CRUD resources from repository interfaces; fine for prototypes, but explicit resources give control of validation, security and DTOs. Not verified here.
reactive-messaging.md 4.2 KB
# Reactive vs blocking, Mutiny, messaging
## Threading model
Quarkus REST picks the execution thread from the method signature (verified on 3.40.1 with a thread-name check):
| Method | Runs on |
|---|---|
| returns plain type, no annotation (Quarkus REST default, imperative) | worker thread (`executor-thread-N`) |
| `@Blocking` | worker thread |
| `@NonBlocking` | event loop (`vert.x-eventloop-thread-N`) |
| returns `Uni`/`Multi`/`CompletionStage` | event loop |
| `@RunOnVirtualThread` | virtual thread (`Thread.currentThread().isVirtual()` is true) |
(Thread names contain `eventloop`, not `event-loop`.) Annotations: `io.smallrye.common.annotation.Blocking`, `NonBlocking`, `RunOnVirtualThread`. Behaviour of defaults differs across extensions (Reactive Messaging, gRPC, scheduler), so annotate explicitly when it matters.
**Event loop pitfalls**: never call blocking JDBC/Panache ORM, `Thread.sleep`, `Uni.await().indefinitely()` or file/HTTP blocking clients on the event loop; Vert.x logs "blocked thread" warnings and Quarkus throws `IllegalStateException` for blocking Panache calls on I/O threads. Move work with `@Blocking`, `@RunOnVirtualThread`, or `Uni...runSubscriptionOn(Infrastructure.getDefaultWorkerPool())`.
**Virtual threads**: `@RunOnVirtualThread` needs Java 21+. Beware of pinning (`synchronized` blocks around blocking calls) and thread-local reliance; use for blocking I/O heavy endpoints, not CPU work.
## Mutiny gotchas
- Nothing runs until subscribed; returning a `Uni` from a resource subscribes it. Avoid `await().indefinitely()` outside tests or `@Blocking` code.
- `Uni.createFrom().item(supplier)` runs the supplier on the subscribing thread (the event loop for REST), so keep it non-blocking (verified).
## SmallRye Reactive Messaging with Kafka
Extension: `quarkus-messaging-kafka`. Ask the user before adding it. Dev Services starts a Kafka broker in dev/test when `kafka.bootstrap.servers` is not set (verified on 3.40.1 and 3.27.6: a round trip worked with Docker).
```properties
mp.messaging.outgoing.words-out.topic=words
mp.messaging.incoming.words-in.topic=words
mp.messaging.incoming.words-in.auto.offset.reset=earliest
# prod
%prod.kafka.bootstrap.servers=${KAFKA_BOOTSTRAP_SERVERS}
```
```java
@ApplicationScoped
public class Words {
@Channel("words-out") Emitter<String> emitter;
void onStart(@Observes StartupEvent e) { emitter.send("hello"); }
@Incoming("words-in")
public void sink(String w) { /* process */ }
}
```
- Channel names link config (`mp.messaging.{incoming|outgoing}.<channel>.*`) to code. The connector ID is `smallrye-kafka`; it is inferred automatically only when it is the single messaging connector on the classpath (with AMQP or another connector also installed, set `mp.messaging.<direction>.<channel>.connector=smallrye-kafka` explicitly). Serializers are inferred for common types; set `value.serializer`/`value.deserializer` for custom classes, or use the JSON serde Quarkus generates for Jackson-serializable types (not verified here; test it).
- Default thread follows the method signature: a synchronous method such as `void sink(String)` already runs on a worker thread, while async signatures (`Uni`, `CompletionStage`, `Multi`) default to the event loop. `@Transactional` implies blocking. Add `@Blocking` to async-signature methods that do blocking work (JDBC, Panache), and `@NonBlocking` to force the event loop.
- Acknowledgement: payload methods are auto-acked on return; use `Message<T>` and `msg.ack()`/`nack()` for control. Add a dead-letter/failure strategy (`failure-strategy=dead-letter-queue`) for production.
- Different channel names mapped to the same `topic` go through Kafka (verified round trip). The same channel name used for `@Outgoing` and `@Incoming` in one app is an in-memory link and never reaches the broker.
- Verify in tests with `Awaitility` waiting on a collected list (verified); for broker-free tests add the test dependency `io.smallrye.reactive:smallrye-reactive-messaging-in-memory` and switch channels with `InMemoryConnector` (see the Quarkus Kafka/messaging guides; not verified here).
- AMQP: `quarkus-messaging-amqp` (`mp.messaging.*.connector=smallrye-amqp`); the AMQP Dev Service starts an ActiveMQ Artemis broker. Not verified here.
rest.md 2.8 KB
# REST, validation, exception mappers, OpenAPI
Extensions: `quarkus-rest-jackson` (Quarkus REST + Jackson), `quarkus-hibernate-validator`, `quarkus-smallrye-openapi`. Do not mix with `quarkus-resteasy*` (legacy) in new code.
## Resource, validation, exception mapper (verified 3.40.1 and 3.27.6)
```java
@Path("/greetings")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class GreetingResource {
public record GreetingRequest(@NotBlank @Size(max = 20) String name) {}
public record Greeting(String message) {}
public record ApiError(String code, String message) {}
public static class NotFound extends RuntimeException { public NotFound(String m) { super(m); } }
@Inject GreetingConfig config; // package-private injection, no private
@POST
@Operation(summary = "Create a greeting") // org.eclipse.microprofile.openapi.annotations
public Greeting create(@Valid @NotNull GreetingRequest req) { return new Greeting(config.prefix() + " " + req.name()); }
@GET @Path("/{name}")
public Greeting get(@PathParam("name") String name) {
if ("missing".equals(name)) throw new NotFound("no " + name);
return new Greeting(config.prefix() + " " + name);
}
@ServerExceptionMapper // org.jboss.resteasy.reactive.server
public RestResponse<ApiError> notFound(NotFound e) {
return RestResponse.status(Response.Status.NOT_FOUND, new ApiError("NOT_FOUND", e.getMessage()));
}
}
```
- Invalid bodies return 400 automatically with a violation report; `@NotNull` makes a JSON `null` body a 400 too, since `@Valid` skips null. Test: `given().contentType("application/json").body("{\"name\":\"\"}").post("/greetings")` returns 400.
- `@ServerExceptionMapper` methods live in the resource class (local) or in any CDI bean (global). A classic `ExceptionMapper<T>` provider with `@Provider` also works; prefer the annotation form.
## OpenAPI
`quarkus-smallrye-openapi` serves `/q/openapi` (add `?format=json`) and Swagger UI at `/q/swagger-ui` in dev (verified: the JSON contains the `/greetings` path). Configure with `quarkus.smallrye-openapi.info-title=...`. Annotate only where descriptions add value (`@Operation`, `@APIResponse`, `@Tag`); the schema is inferred from records and resource methods.
## Other points
- Content negotiation, multipart and SSE exist in Quarkus REST (`Multi<T>` with `@RestStreamElementType`); read the REST guide at https://quarkus.io/guides/rest before using them.
- Cross-cutting: `@ServerRequestFilter` / `@ServerResponseFilter` (static or CDI methods) instead of JAX-RS filters.
- CORS: `quarkus.http.cors.enabled=true` and explicit `quarkus.http.cors.origins`; do not use `*` in production.
- Do not run long blocking work in `Uni`-returning methods without `@Blocking`; see `reactive-messaging.md`.
security-oidc.md 3.1 KB
# Security: OIDC, roles, JWT
Extension: `quarkus-oidc` (bearer token for services, authorization code flow for web apps). Ask the user before adding it. Alternative for self-issued tokens: `quarkus-smallrye-jwt` (`mp.jwt.verify.publickey.location`, `mp.jwt.verify.issuer`).
## Keycloak Dev Service (verified on 3.40.1 and 3.27.6)
With `quarkus-oidc` and no `quarkus.oidc.auth-server-url`, dev/test mode starts Keycloak and imports a `quarkus` realm with users `alice` (admin, user) and `bob` (user), client `quarkus-app`. First start is slow (about 50 s with image pull). Customize roles:
```properties
quarkus.keycloak.devservices.roles.alice=admin,user
quarkus.keycloak.devservices.roles.bob=user
```
Dev UI (`/q/dev-ui`, OpenID Connect card) can log in and obtain tokens. For production set `%prod.quarkus.oidc.auth-server-url=${OIDC_URL}`, `%prod.quarkus.oidc.client-id`, and `credentials.secret` from env/secret store; never in git.
## Bearer (service) and web-app modes
- Default `quarkus.oidc.application-type=service`: expects `Authorization: Bearer <jwt>`.
- Browser app: `quarkus.oidc.application-type=web-app` (session cookie, redirect to IdP). Pair with `quarkus.http.auth.permission.*` for path rules.
## Authorization
```java
@Path("/secure")
public class SecuredResource {
@Inject SecurityIdentity identity;
@GET @Path("/me") @Authenticated
public String me() { return identity.getPrincipal().getName(); }
@GET @Path("/admin") @RolesAllowed("admin")
public String admin() { return "admin ok"; }
}
```
Verified results: no token gives 401; a token for `alice` gets 200 on `/secure/admin`; `bob` gets 403 there and 200 on `/secure/me`.
- Secure by default: `quarkus.security.jaxrs.deny-unannotated-endpoints=true` (not verified here).
- Fine-grained checks: `@PermissionsAllowed("read")` with a `SecurityIdentity` permission checker, or `@PermissionChecker` methods (`quarkus-security`); or inject `SecurityIdentity` and check `identity.hasRole(...)`. Not verified here.
- JWT claims: inject `org.eclipse.microprofile.jwt.JsonWebToken` (with `quarkus-oidc`, `@Inject JsonWebToken jwt; jwt.getClaim("email")`). Default role lookup: a `groups` claim wins if present; otherwise Keycloak's `realm_access/roles`, and `resource_access/<quarkus.oidc.client-id>/roles` when a client id is configured (a token with non-empty `groups` uses those even if realm roles exist). Override with `quarkus.oidc.roles.role-claim-path`.
- Calling downstream services with the user's token: `quarkus-rest-client-oidc-token-propagation`; with the service's own identity: `quarkus-rest-client-oidc-filter`. Not verified here.
## Testing
- Unit-style: `@TestSecurity(user = "u", roles = "admin")` with `quarkus-test-security` (verified: 200 for admin, 403 for another role).
- Real tokens against the Dev Service: `quarkus-test-keycloak-server` provides `io.quarkus.test.keycloak.client.KeycloakTestClient`; `given().auth().oauth2(new KeycloakTestClient().getAccessToken("alice"))` (verified). Also see `quarkus-dev-services-and-testing`.
- Keycloak container requires Docker; tests relying on it should be run where containers exist.
License (MIT)
View full license text
MIT License Copyright GitHub, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.