contexa-examples

Examples

How to get and run the 7 examples in the GitHub repository contexa73/contexa-examples, what each one shows and what to try. They start and run as they are.

At a glance

Each example is a Spring Boot application that runs on its own. If you are new, this order is the easiest.

Suggested orderStart from the smallest setup, then method decisions, then adding Contexa to an existing login, then letting Contexa own sign-in.
  1. quickstartThe smallest setup and a first @Protectable
  2. protectableFour ways to use @Protectable
  3. legacy-systemAdding Contexa to a system whose application owns sign-in
  4. identity-*When Contexa owns sign-in: authentication DSL, MFA, OAuth2
ExamplePortWho owns sign-inWhat it shows
contexa-example-quickstart8081Contexa@EnableAISecurity with form login, a first @Protectable
contexa-example-protectable8082ContexaFour ways to use @Protectable (asynchronous, owner check, sync, both)
contexa-example-identity-dsl8083ContexaForm login and REST (JSON) login together with the authentication DSL
contexa-example-identity-mfa8087ContexaMFA (one-time token, passkey) with custom login and MFA pages
contexa-example-identity-mfa-multi8088ContexaTwo MFA flows on different paths (/admin, /user)
contexa-example-identity-oauth28089ContexaOAuth2 stateless authentication that issues a JWT after form login
contexa-example-legacy-system9090The applicationAdding Contexa to a legacy application with its own login and no Spring Security

The six examples in which Contexa owns sign-in put @EnableAISecurity(mode = SecurityMode.FULL) on the main class; legacy-system keeps its own login with SecurityMode.SANDBOX. The two ownership modes are compared in Add to an Existing Spring Security Application.

Getting and running them

git clone https://github.com/contexa73/contexa-examples.git
cd contexa-examples
./gradlew :contexa-example-quickstart:bootRun
  • Java 21. The example build uses a Java 21 toolchain. Spring Boot is 3.5.11, Spring AI 1.1.8.
  • The Contexa dependency. The root build.gradle adds ai.ctxa:spring-boot-starter-contexa:0.1.0 to every example and looks for it in the local Maven repository first, then Maven Central. If the build cannot find it, publish it from the Contexa repository with ./gradlew publishToMavenLocal.
  • PostgreSQL with the vector extension. Every example keeps Contexa's data in a dedicated database, by default jdbc:postgresql://localhost:5432/contexa with the user and password contexa. To use another database, set CONTEXA_DB_URL, CONTEXA_DB_USERNAME and CONTEXA_DB_PASSWORD. On the first start Contexa creates its tables and default data there; give each example its own database if you run several.
  • AI models. The examples use a local Ollama (http://localhost:11434, or OLLAMA_BASE_URL) with qwen3:8b for decisions and mxbai-embed-large for past decision records; get them with ollama pull. Contexa sends one Ollama server two calls at a time and switches its model only when the running calls are done (How many calls a model server takes). A local model answers slower than a hosted one, so the examples give the Layer 2 analysis 120 seconds (contexa.security.tiered.layer2.timeout-ms, 30 seconds by default).
CREATE USER contexa WITH PASSWORD 'contexa';
CREATE DATABASE contexa OWNER contexa;
\c contexa
CREATE EXTENSION IF NOT EXISTS vector;

Values for a local run only

So that the examples start as they are, their application.yml carries values that must never reach a deployment.

ValueIn the examplesFor anything beyond a local run
Sample accountsadmin, manager, developer, user, finance with the password 1111 (contexa.iam.seed.accounts.enabled: true)Leave the setting off
Evidence signing keyA fixed example keySet CONTEXA_EVIDENCE_KEY (Base64, 32 bytes or more)
Token signing keysexample-jwk.p12 in the resourcesSet CONTEXA_JWK_KEY_STORE and CONTEXA_JWK_KEY_STORE_PASSWORD
OAuth2 client secret (identity-oauth2)example-local-client-secretSet CONTEXA_OAUTH2_CLIENT_SECRET

Each example

Sign in with admin / 1111 unless noted.

quickstart (8081): the smallest setup

  • What it shows: @EnableAISecurity on the main class and a form login built with the authentication DSL (/login → /test/quickstart). Only /api/hello carries @Protectable, so only it is decided on. The enforcement mode is SHADOW: Contexa decides and records without blocking (Enforcement modes).
  • Try: sign in, then call /api/hello from the test page /test/quickstart. The decision is recorded in the Contexa database.

protectable (8082): four ways to use @Protectable

APIProtectionBehavior
GET /api/orders@ProtectableAnswers at once and decides in the background (asynchronous)
GET /api/orders/customer/{customerId}@Protectable(ownerField = "customerId")When a policy condition uses hasPermission(...), compares the target's customerId with the signed-in user's name. Without such a policy it has no effect
POST /api/orders@Protectable(sync = true)Waits for the decision, then runs
DELETE /api/orders/{orderId}?customerId=@Protectable(ownerField = "customerId", sync = true)Waits for the decision and compares the owner as above
  • Try: sign in, then call the four APIs from the test page /test/protectable. data.sql inserts sample orders at start-up; the application's tables share the Contexa database, since Contexa owns the application.
  • Read with: sync, ownerField, responses

identity-dsl (8083): the authentication DSL

  • What it shows: one PlatformConfig with REST (JSON) login (POST /api/login → /api/profile) and form login (/login → /) together. The REST flow takes only /api/** (rawHttp(http -> http.securityMatcher("/api/**"))) and is ordered first (order(50)); the form flow takes every other request. Two flows that both take every request would leave the second one unreachable (Authentication DSL).
  • Try: the form at /login, or POST /api/login with {"username":"admin","password":"1111"} and then GET /api/profile with the same session.
  • Read with: Authentication DSL, Authentication

identity-mfa (8087): MFA with custom pages

  • What it shows: the first factor is form login on a custom login page (/customLogin), the second a one-time token (OTT) or a passkey. mfaPage(...) sets the second-factor page addresses: token request /custom/mfa/ott/request-code-ui, token entry /custom/mfa/challenge/ott, passkey /custom/challenge/passkey. The pages are Thymeleaf templates using contexa-mfa-sdk.js.
  • Try: sign in at /customLogin; the page posts the password to /mfa/login and opens the one-time code page that follows.
  • Read with: Custom MFA pages, SDK

identity-mfa-multi (8088): two MFA flows

  • What it shows: two named MFA flows. The admin flow uses urlPrefix("/admin") with a passkey and a one-time token (order 60): a passkey is registered only after MFA completes, so an administrator without one verifies by email first. The user flow uses urlPrefix("/user") with a one-time token (order 70). Each prefix goes in front of the login page address, so the home page / leads to /admin/mfa/login and /user/mfa/login, and success goes to /admin/dashboard or /user/dashboard.
  • Try: sign in at /user/mfa/login as user / 1111; the one-time code page follows.
  • Read with: Several MFA flows

identity-oauth2 (8089): OAuth2 stateless authentication

  • What it shows: with .form().oauth2() the user gets a JWT after form login and calls the next APIs with a Bearer token. The tokens are kept in the browser's localStorage (contexa.auth.token-persistence: localstorage), where the test page /test/token reads them to call POST /api/token-test/refresh, GET /api/token-test/validate and GET /api/token-test/userinfo. The signing keys are published at /oauth2/jwks.
  • Try: sign in at /login; you land on /test/token.
  • Read with: OAuth2 state, Issuing tokens to a signed-in user

legacy-system (9090): adding Contexa to a legacy login

  • What it shows: an application that signs users in with its own filter (LegacyAuthFilter), with Contexa added through @EnableAISecurity(mode = SecurityMode.SANDBOX): the application owns sign-in. Sign-in works by form (/legacy/login), an X-Auth-Token header or a remember-me cookie, and a @LegacyRole interceptor checks roles. After a successful sign-in the filter hands the user, roles, department and login method to Contexa with ContexaAuthBridge.handoff(...) and keeps the user object in the session attribute legacyUser. The application's data stays in its own (in-memory H2) database; Contexa's data goes to the dedicated Contexa database.
  • Protected APIs: GET /api/customers (@Protectable, asynchronous) and GET /api/customers/export (@Protectable(sync = true)).
  • Example users: admin/admin123 (ADMIN, MANAGER), kim_manager/manager123, park_dev/dev123, lee_analyst/analyst123.
  • The application's chain: when the application owns sign-in, Contexa builds no chain, and @Protectable needs an authenticated user in the SecurityContext. So the example declares a chain that keeps the existing access rules (LegacySecurityConfig) and a filter that puts the legacy session's user into the SecurityContext (LegacySessionAuthenticationFilter):
@Bean
SecurityFilterChain legacyChain(HttpSecurity http) throws Exception {
    return http.csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
            .addFilterBefore(new LegacySessionAuthenticationFilter(), AnonymousAuthenticationFilter.class)
            .build();
}

// Puts the user the legacy login left in the session into the SecurityContext on every request
class LegacySessionAuthenticationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session != null
                && session.getAttribute(LegacyAuthFilter.SESSION_USER_KEY) instanceof LegacyUserSession user) {
            List<SimpleGrantedAuthority> roles = user.getRoles().stream()
                    .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
                    .toList();
            SecurityContextHolder.getContext().setAuthentication(
                    UsernamePasswordAuthenticationToken.authenticated(user.getUserId(), null, roles));
        }
        chain.doFilter(request, response);
    }
}
  • Scenario profiles: 10 application-scenario-*.yml files test start-up with different database setups (dedicated H2, a shared database allowed for a PoC or refused in production, no dedicated database, bridge off, a context path behind a proxy and more, ports 19081 to 19091). The fake-chat profile uses a test model that always answers allow (PERMIT) and an empty vector store.
  • Read with: What the application must do, Direct handoff, Finding the user in the session