Quarkus OIDC Keycloak Setup for Secure REST Endpoints
Secure a Quarkus service with OIDC and Keycloak: bearer token mode, Dev Services for Keycloak, role based access with annotations and testing with tokens.

A resource server in OpenID Connect trusts tokens that an identity provider signed. Quarkus does the verifying, and Keycloak issues the tokens, so securing a service is mostly configuration plus a few annotations. This post sets up bearer token mode on Quarkus 3 with Keycloak 26. It covers the dependency and settings, protecting endpoints with annotations, the Dev Services container that makes local development painless, tests that need no server, and the TLS error you meet when Keycloak runs behind a private certificate authority.
Dependency and configuration
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-oidc</artifactId>
</dependency>quarkus.oidc.auth-server-url=https://keycloak.example.com/realms/shop
quarkus.oidc.client-id=orders-api
quarkus.oidc.application-type=service
%dev.quarkus.keycloak.devservices.realm-path=shop-realm.jsonapplication-type=service selects bearer token mode: there is no login page, and the service reads the Authorization: Bearer ... header on each request. The URL is the realm's issuer address. From it Quarkus discovers the signing keys and endpoints when the service starts, so a wrong URL fails early, at startup, instead of on the first request.
The issuer is also compared with the iss claim in every token. If a token was issued under a different host name than the one in this URL, for instance because Keycloak sees itself as localhost behind a proxy, the signature is fine and validation still fails. It is the most common source of 401 responses that look like they should work. Compare the iss value in a decoded token with the property, character by character.
Protect the endpoints
@Path("/orders")
@Authenticated
public class OrderResource {
@Inject
SecurityIdentity identity;
@GET
public List<Order> mine() {
return orders.forUser(identity.getPrincipal().getName());
}
@DELETE
@Path("/{id}")
@RolesAllowed("admin")
public void delete(@PathParam("id") long id) {
orders.delete(id);
}
}@Authenticated requires any valid token. @RolesAllowed also requires a role, which Quarkus reads from the token's realm_access.roles claim by default. If your roles are client roles, point at the claim with quarkus.oidc.roles.role-claim-path. A request without a token gets 401, and a request with a valid token but without the role gets 403. The difference matters for clients, because a 401 says "authenticate" and a 403 says "you cannot", and the Spring view of the same split is in 401 and 403.
Annotations protect individual resources. For whole path trees, declare rules in configuration:
quarkus.http.auth.permission.api.paths=/orders/*
quarkus.http.auth.permission.api.policy=authenticatedUse both. A configuration rule is a safety net for a new resource class somebody forgot to annotate, and annotations document intent beside the code.
Dev Services for local work
If you leave auth-server-url unset in dev and test modes, Quarkus starts a Keycloak container, imports a default realm or the one named in realm-path, and sets the URL for you. You write no Docker Compose file and keep no local Keycloak running. The Dev UI has an OIDC page where you can sign in as the sample users alice and bob, and copy a token to paste into curl. The general idea of containers started for you is described in Dev Services.
The container needs Docker or Podman. On a machine without a container runtime, set the real URL, or the service fails to start with a message about Dev Services.
Tests that need no token
@QuarkusTest
class OrderResourceTest {
@Test
@TestSecurity(user = "alice", roles = "admin")
void adminCanDelete() {
given().when().delete("/orders/1").then().statusCode(204);
}
@Test
void anonymousIsRejected() {
given().when().get("/orders").then().statusCode(401);
}
}@TestSecurity from quarkus-test-security injects an identity without issuing a token, so the test checks authorization rules and runs fast. It does not check that the service validates real tokens. Keep one integration test that gets a token from the test Keycloak and calls the endpoint with it, because issuer and key configuration are only exercised by a real token. A suite with only @TestSecurity can pass while production rejects every request.
Reading claims and propagating identity
Beyond roles, the token carries claims you can use directly. Inject a JsonWebToken to read any claim, such as email or a custom tenant_id, or call identity.getAttribute(...). Filter data by the caller in the query, not in the controller, so an authorization mistake cannot leak rows. When your service calls another protected service on behalf of the user, pass the incoming token along with a REST client header factory, or exchange it for a token with narrower scope. Forwarding a broad token to every downstream service means that a compromise of any one of them exposes the user everywhere.
Token lifetime and clock skew
Tokens expire, and a service whose clock is a few minutes off rejects valid ones as expired or not yet valid. Keep servers on network time. Quarkus tolerates a small skew through quarkus.oidc.token.lifespan-grace, which is better set to a handful of seconds than to cover a broken clock. If tokens last an hour in Keycloak and users complain about being signed out after five minutes, the setting is in the realm, not in the service.
Failing the right way
A misconfigured service should fail loudly. Check these in order when requests return 401: the token is present and not expired, the issuer matches, the audience matches client-id when Keycloak includes one, and the service can reach the realm's key endpoint. Turn on quarkus.log.category."io.quarkus.oidc".level=DEBUG temporarily, which prints the reason a token was rejected. Remove it afterwards, because the log can include token details.
Certificates and private authorities
When Keycloak uses a certificate from a private authority, the service cannot fetch the discovery document and fails at startup with a TLS error. Add the authority to a truststore and point Quarkus at it. The error and the fix are described in PKIX path building failed. Disabling verification would make the error vanish and leave the token endpoint open to interception, so do not.
Map Keycloak roles to the roles your code checks
Keycloak puts realm roles in the token under realm_access.roles and client roles under resource_access, and @RolesAllowed looks at whatever Quarkus reads as roles. Tell Quarkus where to look:
quarkus.oidc.roles.role-claim-path=realm_access/rolesFor client-specific roles the path includes the client id, for example resource_access/orders-api/roles. With the claim path set, the annotation works as written:
@Path("/admin/orders")
public class AdminOrderResource {
@DELETE
@Path("/{id}")
@RolesAllowed("order-admin")
public void delete(@PathParam("id") long id) {
orders.delete(id);
}
}Apply coarse rules in configuration as a safety net behind the annotations, so a new resource is protected until somebody opens it on purpose:
quarkus.http.auth.permission.default.paths=/*
quarkus.http.auth.permission.default.policy=authenticated
quarkus.http.auth.permission.public.paths=/q/health/*
quarkus.http.auth.permission.public.policy=permitIf a role you gave a user in Keycloak does not take effect, decode the access token and read its claims before changing any code. The usual causes are a role mapped on the wrong level (realm instead of client), a client scope that does not include roles in the token, and a token cached from before the change.
Opaque tokens and the browser flow
Everything above assumes JWT access tokens that the service verifies with the realm's public keys, with no call to Keycloak per request. If your provider issues opaque tokens, Quarkus can use introspection instead, which costs a network call per request unless you cache. For a browser application where users sign in through the service itself, switch to application-type=web-app, which handles the redirect flow and issues a session cookie. General guidance for the surrounding decisions is in Java security basics. The reference is the Quarkus OIDC bearer token guide, and the Keycloak documentation covers realms, clients and roles.


