Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 36 ยท Testing and Deployment

Security with JWT and OpenID Connect

Secure a Quarkus API: protect endpoints with @RolesAllowed and permission rules, validate JWT bearer tokens with SmallRye JWT or OIDC, and test with Keycloak Dev Services.

An API that anyone can call is a demo, not a service. Security has two separate questions. Authentication asks "who are you?". Authorization asks "what may you do?". Quarkus answers the first with extensions such as quarkus-oidc (OpenID Connect), quarkus-smallrye-jwt (validate JWTs yourself) and basic or form auth, and the second with annotations and HTTP permission rules that work the same regardless of how the user logged in.

This lesson covers the model: the identity, the annotations, bearer tokens, what a JWT contains and how it is verified, the OIDC setup with Keycloak, and testing. For general ideas see the Spring Security tutorial (different framework, same concepts) and REST API authentication. Quarkus and a real identity provider cannot run here, so framework code is read-only, and the TryIts implement a real HS256 JWT check and an annotation-driven role check using only the JDK.

Authorization annotations

Once any authentication mechanism is installed, protect methods or classes with the standard Jakarta annotations:

Java
import jakarta.annotation.security.*;
import io.quarkus.security.Authenticated;

@Path("/books")
public class BookResource {

    @GET
    @PermitAll                              // anyone, even anonymous
    public List<Book> list() { ... }

    @POST
    @RolesAllowed({"editor", "admin"})      // authenticated with one of these roles
    public Response create(Book b) { ... }

    @DELETE @Path("/{id}")
    @RolesAllowed("admin")
    public void delete(@PathParam("id") long id) { ... }

    @GET @Path("/me")
    @Authenticated                          // any logged-in user
    public String me(@Context SecurityContext ctx) { return ctx.getUserPrincipal().getName(); }
}

Failures are mapped for you: 401 Unauthorized when there is no valid identity and 403 Forbidden when the identity lacks the role. Two traps:

  • Without any annotation an endpoint is open unless you configure otherwise. A safe default is to deny: quarkus.security.jaxrs.deny-unannotated-endpoints=true, so forgetting an annotation closes the endpoint instead of leaving it open.
  • Role names are plain strings, so a typo ("Admin" versus "admin") silently denies everyone. Put them in constants or an enum-backed constant class.

You can also write rules in configuration without touching code, useful for whole paths:

PROPERTIES
quarkus.http.auth.permission.admin-area.paths=/admin/*
quarkus.http.auth.permission.admin-area.policy=authenticated

quarkus.http.auth.policy.editors.roles-allowed=editor,admin
quarkus.http.auth.permission.write.paths=/books/*
quarkus.http.auth.permission.write.methods=POST,PUT,DELETE
quarkus.http.auth.permission.write.policy=editors

Inside code, inject SecurityIdentity to see who is calling: identity.getPrincipal().getName(), identity.hasRole("admin"), identity.isAnonymous(), and identity.getAttribute("email").

Java Stand-in: annotation-driven role checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

What is in a JWT

A JSON Web Token is three Base64URL parts separated by dots: header.payload.signature. The header names the signing algorithm and key id; the payload holds claims; the signature proves nobody changed them.

TEXT
{"alg":"RS256","kid":"key-1"}
{"iss":"https://auth.example.com/realms/shop","sub":"7f3a...","aud":"shop-api",
 "exp":1893456000,"iat":1893452400,"upn":"[email protected]","groups":["editor"]}

Important claims: iss (who issued it), sub (the user id), aud (who it is meant for), exp (expiry), and a role claim (groups in MicroProfile JWT, realm_access.roles in Keycloak). A resource server must check the signature, issuer, audience and expiry. It never trusts a token just because it decodes.

Production tokens are signed with asymmetric keys (RS256 or ES256): the identity provider keeps the private key, and your API only needs the public key, downloaded from the provider's JWKS endpoint. The TryIt below uses HS256 (a shared secret) because it needs only the JDK; the verification steps are identical.

Java Stand-in: create and verify an HS256 JWT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Bearer tokens with SmallRye JWT

If you only need to validate tokens that some other system issues, quarkus-smallrye-jwt is the lightest option:

PROPERTIES
mp.jwt.verify.publickey.location=https://auth.example.com/.well-known/jwks.json
mp.jwt.verify.issuer=https://auth.example.com
mp.jwt.verify.audiences=shop-api
smallrye.jwt.path.groups=realm_access/roles

Clients send Authorization: Bearer <token>. Quarkus checks signature, issuer, audience and expiry; the groups claim feeds @RolesAllowed. You can inject the token with JsonWebToken to read custom claims.

OpenID Connect with quarkus-oidc

quarkus-oidc is the full-featured choice. It can be a service (validates bearer tokens, the default) or a web-app (redirects browsers through the authorization code flow, keeps a session cookie), and it works with Keycloak, Auth0, Okta, Entra ID and others through discovery:

PROPERTIES
quarkus.oidc.auth-server-url=https://auth.example.com/realms/shop
quarkus.oidc.client-id=shop-api
quarkus.oidc.application-type=service
%prod.quarkus.oidc.credentials.secret=${OIDC_SECRET}

Discovery downloads the keys and endpoints from .../.well-known/openid-configuration, and keys are refreshed on rotation. Calling another secured service uses quarkus-oidc-client (client-credentials or token propagation).

Dev Services for Keycloak: with quarkus-oidc and no auth-server-url configured, dev mode starts a Keycloak container with a quarkus realm and users alice (roles admin and user) and bob (role user). The Dev UI has a login page that gets a token for you, so you can try secured endpoints at once. Tests get the same Keycloak, and KeycloakTestClient fetches tokens for real end-to-end checks.

A bearer token request

Client Sends Authorization: Bearer.
Verify Signature, issuer, audience, expiry.
Identity Roles from the token claims.
Authorize @RolesAllowed decides: 401 or 403.

Never trust a token you did not verify.

1 / 2

Testing secured endpoints

For fast tests, skip the identity provider:

Java
@QuarkusTest
class BookResourceSecurityTest {

    @Test
    @TestSecurity(user = "alice", roles = {"editor"})
    void editorCanCreate() {
        given().contentType("application/json").body("{\"title\":\"x\"}")
          .when().post("/books").then().statusCode(201);
    }

    @Test
    @TestSecurity(user = "bob", roles = {"reader"})
    void readerCannotDelete() {
        given().when().delete("/books/1").then().statusCode(403);
    }

    @Test
    void anonymousGets401() {
        given().when().delete("/books/1").then().statusCode(401);
    }
}

With OIDC, add @OidcSecurity for claims. Keep a few end-to-end tests that use a real Keycloak token, so the configuration itself (issuer, audience, role claim path) is also verified.

Good practices

  • Deny by default, then open endpoints deliberately.
  • Keep access tokens short-lived (minutes); use refresh tokens in the client, not in the API.
  • Validate aud, not just iss, or a token meant for another API is accepted.
  • Use HTTPS everywhere; a bearer token is a password in transit.
  • Do not put sensitive data in JWT payloads: they are encoded, not encrypted.
  • Hash stored passwords with Quarkus's BcryptUtil or an identity provider; never store them in plain text.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What HTTP status does Quarkus return for a request without a valid token to a @RolesAllowed endpoint?

    No valid identity means 401 Unauthorized. 403 Forbidden is for an authenticated user lacking the role.
  2. 2. Which checks must a resource server perform on a JWT?

    Decoding proves nothing; the signature and the other claims establish trust.
  3. 3. What does quarkus.security.jaxrs.deny-unannotated-endpoints=true do?

    It turns a forgotten annotation into a closed door instead of an open one.
  4. 4. Why are RS256 tokens preferred over HS256 in distributed systems?

    With asymmetric keys, only the identity provider holds the private signing key.

Summary

  • @PermitAll, @Authenticated and @RolesAllowed authorize; no identity gives 401, missing role gives 403.
  • A JWT is header.payload.signature; verify signature, issuer, audience and expiry.
  • quarkus-smallrye-jwt validates tokens; quarkus-oidc adds full OpenID Connect and Dev Services for Keycloak.
  • Test with @TestSecurity, plus a few real-token tests; deny unannotated endpoints by default.

Next: Containers and Kubernetes