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.
- quickstartThe smallest setup and a first
@Protectable - protectableFour ways to use
@Protectable - legacy-systemAdding Contexa to a system whose application owns sign-in
- identity-*When Contexa owns sign-in: authentication DSL, MFA, OAuth2
| Example | Port | Who owns sign-in | What it shows |
|---|---|---|---|
contexa-example-quickstart | 8081 | Contexa | @EnableAISecurity with form login, a first @Protectable |
contexa-example-protectable | 8082 | Contexa | Four ways to use @Protectable (asynchronous, owner check, sync, both) |
contexa-example-identity-dsl | 8083 | Contexa | Form login and REST (JSON) login together with the authentication DSL |
contexa-example-identity-mfa | 8087 | Contexa | MFA (one-time token, passkey) with custom login and MFA pages |
contexa-example-identity-mfa-multi | 8088 | Contexa | Two MFA flows on different paths (/admin, /user) |
contexa-example-identity-oauth2 | 8089 | Contexa | OAuth2 stateless authentication that issues a JWT after form login |
contexa-example-legacy-system | 9090 | The application | Adding 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.gradleaddsai.ctxa:spring-boot-starter-contexa:0.1.0to 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
vectorextension. Every example keeps Contexa's data in a dedicated database, by defaultjdbc:postgresql://localhost:5432/contexawith the user and passwordcontexa. To use another database, setCONTEXA_DB_URL,CONTEXA_DB_USERNAMEandCONTEXA_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, orOLLAMA_BASE_URL) withqwen3:8bfor decisions andmxbai-embed-largefor past decision records; get them withollama 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.
| Value | In the examples | For anything beyond a local run |
|---|---|---|
| Sample accounts | admin, manager, developer, user, finance with the password 1111 (contexa.iam.seed.accounts.enabled: true) | Leave the setting off |
| Evidence signing key | A fixed example key | Set CONTEXA_EVIDENCE_KEY (Base64, 32 bytes or more) |
| Token signing keys | example-jwk.p12 in the resources | Set CONTEXA_JWK_KEY_STORE and CONTEXA_JWK_KEY_STORE_PASSWORD |
| OAuth2 client secret (identity-oauth2) | example-local-client-secret | Set CONTEXA_OAUTH2_CLIENT_SECRET |
Each example
Sign in with admin / 1111 unless noted.
quickstart (8081): the smallest setup
- What it shows:
@EnableAISecurityon the main class and a form login built with the authentication DSL (/login→/test/quickstart). Only/api/hellocarries@Protectable, so only it is decided on. The enforcement mode isSHADOW: Contexa decides and records without blocking (Enforcement modes). - Try: sign in, then call
/api/hellofrom the test page/test/quickstart. The decision is recorded in the Contexa database.
protectable (8082): four ways to use @Protectable
| API | Protection | Behavior |
|---|---|---|
GET /api/orders | @Protectable | Answers 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.sqlinserts 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
PlatformConfigwith 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, orPOST /api/loginwith{"username":"admin","password":"1111"}and thenGET /api/profilewith 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 usingcontexa-mfa-sdk.js. - Try: sign in at
/customLogin; the page posts the password to/mfa/loginand 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
adminflow usesurlPrefix("/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. Theuserflow usesurlPrefix("/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/loginand/user/mfa/login, and success goes to/admin/dashboardor/user/dashboard. - Try: sign in at
/user/mfa/loginasuser/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 aBearertoken. The tokens are kept in the browser's localStorage (contexa.auth.token-persistence: localstorage), where the test page/test/tokenreads them to callPOST /api/token-test/refresh,GET /api/token-test/validateandGET /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), anX-Auth-Tokenheader or a remember-me cookie, and a@LegacyRoleinterceptor checks roles. After a successful sign-in the filter hands the user, roles, department and login method to Contexa withContexaAuthBridge.handoff(...)and keeps the user object in the session attributelegacyUser. 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) andGET /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
@Protectableneeds 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-*.ymlfiles 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). Thefake-chatprofile 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