Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Spring Boot
  • Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
  • A Plain Spring Project, No Boot: Your First Bean With spring-context
  • Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
  • Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
  • Spring Autowiring: Spring Fills the Constructor, and When @Autowired Is Needed
  • Two Beans, One Type: Spring @Primary and @Qualifier
  • Spring Bean Scopes: Singleton vs Prototype, One Shared Object or a Fresh One
  • Spring Stereotypes: @Service, @Repository and @Controller Are @Component With a Job Name
  • The Spring Bean Lifecycle: @PostConstruct and @PreDestroy
  • The Mini Blog Wired by Spring: Plain Java vs Spring, Side by Side
  • Spring MVC and SQLite Without Spring Boot: the Mini Blog in the Browser
  • Your First Spring Boot 4 Project: Create It in IntelliJ, Run It, and the Four Files That Matter
  • What Is Spring Boot? Spring Framework 7 With the Decisions Already Made
  • The Project Context File: AGENTS.md and CLAUDE.md for a Spring Boot Project
  • Plan Before Code: a Five-Part Brief, Plan Mode and /goal for a Spring Boot Feature
  • From Design Frames to Thymeleaf Pages: Briefing an AI Agent for a Spring Boot Blog
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Profile Page and Photo Upload in Spring Boot: Check the File, Shrink It, Keep Your Own Name
  • Building a Feature With an AI Agent, End to End: Comments on a Spring Boot Blog
  • Containerising Spring Boot: a Layered Dockerfile vs Buildpacks
  • GraalVM Native Image and Spring AOT: When It Pays, and What It Costs
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Scheduled Jobs in Spring Boot: fixedRate, fixedDelay, cron, and ShedLock for Many Instances
  • Redis in Spring Boot: a Cache, a Rate-Limit Counter and a Job Status Hash
  • Actuator and Micrometer in Spring Boot: Health, Your Own Metrics, and the Four Numbers That Matter
  • Structured Logging and Correlation IDs in Spring Boot: JSON Lines, a Filter and the MDC
  • Dashboards and Alerts for a Spring Boot App: Prometheus, Grafana and One Real Incident
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • A GitHub Actions Workflow for a Maven Project: Cache, a Java Matrix and Test Reports That Survive a Red Run
  • The AWS SDK for Java v2 in Spring Boot: Clients as Beans, the Default Credentials Chain and No Keys in Code
  • Attachments in S3 from Spring Boot: Pre-signed Uploads, a 302 to a Pre-signed Download, and Links That Expire
  • CloudWatch for a Spring Boot App: JSON Logs, Micrometer Metrics From Your Own Code, and an Alarm That Reaches a Person
  • Automated Deploy, Smoke Test and Rollback for a Spring Boot App: Green Tests Are Not a Working Deploy
  • Environments, Secrets and Approvals in GitHub Actions: One Image From Staging to Production
  • Distributed Tracing Across Spring Boot Services and Kafka: One Trace ID From the Gateway to the Last Reader, Even Through an Outbox
  • Thymeleaf and htmx in Spring Boot: Live Search and One-Row Updates From Server-Rendered Fragments, With No JavaScript Framework
  • Rate Limiting, Backpressure and Load Shedding in Spring Boot: Bucket4j in Redis, a Bounded Worker Pool and Dropping Low-Priority Work
  • Resilience4j in Spring Boot: A Timeout, One Retry, a Circuit Breaker, a Bulkhead and a Fallback, Measured Against a Slow Dependency
  • Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
  • Entities and H2 in Spring Boot: a Post Class Becomes a Table
  • Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
  • Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
  • Connect Spring Boot to PostgreSQL: Driver, application.yml and the Hikari Pool
  • JPA Entity Mapping: Ids, Enums and Dates, From a Java Class to a Table
  • Spring Data Query Methods: Derived Queries, @Query and Projections
  • The N+1 Problem in JPA: Fetch Types, Join Fetch and Entity Graphs
  • Spring @Transactional: All or Nothing, the Proxy, and the Self-Call Trap
  • Flyway Migrations in Spring Boot: Numbered SQL Files, Seed Data and the History Table
  • Spring Data JPA Auditing and Soft Deletes: Who Changed It, When, and Hiding Instead of Deleting
  • Optimistic Locking with @Version: Two Agents, One Ticket, No Lost Update
  • Finding a Slow Spring Boot Endpoint: Actuator Timers, EXPLAIN ANALYZE and One Index
  • Caching With Spring and Redis: Cache-Aside, a TTL per Kind of Data, Eviction on Edit and Stopping the Stampede
  • A PostgreSQL Read Replica in Spring Boot: Route readOnly Transactions, Size the Pool, Find the Index, Read Your Own Writes
  • A Registration Form With Bean Validation in Spring Boot: @Valid, BindingResult and th:errors
  • Spring Security 7 Form Login, BCrypt and a UserDetailsService on the Account Table
  • Roles and Authorities at Login in Spring Security: From a ROLE Column to hasRole("ADMIN")
  • Menus per Role With Thymeleaf Security Tags: sec:authorize, sec:authentication and an Edit Button for the Author
  • Fixing the Access Bugs: a Rule per Role and an Ownership Check in Spring Security
  • Add, Edit and Delete Posts With a Rich-Text Editor in Spring Boot: Quill, jsoup and th:utext
  • Remember Me and Forgot Password by Email in Spring Boot: a Signed Cookie and a One-Time Link
  • Spring Boot Security Defaults: What One Dependency Gives You for Free
  • The Spring Security Filter Chain and Your Own Rules: 401, 403 and Rule Order
  • Stateless JWT Authentication in Spring Security: Sign Once, Check Every Request
  • Users in the Database with Spring Security: Register, BCrypt and Log In
  • Method Security in Spring: @PreAuthorize, Roles and Who Owns This Ticket
  • CORS and CSRF in Spring Security: Why the Browser Blocks Your SPA, and When CSRF Can Be Off
  • Reviewing AI-Written Spring Code for Security: Four Questions for Every Diff
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • An API Gateway With Spring Cloud Gateway: Check the JWT Once at the Edge, Pass the Caller Inward, and Know What the Network Now Trusts
  • Unit Tests With AI for a Spring Boot Service: Mockito Mocks, Given-When-Then and a Green Run
  • Docker for a Spring Boot App: Run the Tests in the Image Build, or Skip Them on Purpose
  • The Test Pyramid in Spring Boot: Unit, Slice and Whole-App Tests
  • Mockito and Test Doubles: Stubs, Mocks and Fakes for One Java Class
  • Spring Boot Test Slices: @WebMvcTest with MockMvc and @DataJpaTest
  • Integration Tests with Testcontainers: A Real PostgreSQL for Every Spring Boot Test Run
  • Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser
  • Test-First with a Coding Agent: Spec, Red Tests, Then the Code
  • Quality and Security Gates for a Maven Project: JaCoCo Coverage, PMD, an SBOM and a Trivy Scan
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • What Spring AI 2 Is, and Why a Java Team Wants It
  • Spring AI ChatClient: One API for Any Model, and the Model Is a Property
  • Spring AI Prompt Templates: Placeholders, Few-Shot Messages and Versioned Prompt Files
  • Spring AI Structured Output: From Model JSON to a Java Record, and a Real Ticket Triage Feature
  • Streaming Spring AI Answers to the Browser: stream(), a Flux of Server-Sent Events and the Cancel
  • Local Models With Ollama in Spring AI: Profiles, Per-Call Options and What a Smaller Model Costs
  • Testing Spring AI Features: a Stub ChatModel, Must-Cite and Must-Refuse Tests, and One Tagged Model Test
  • Embeddings and pgvector in Spring AI: EmbeddingModel, VectorStore, Distance Operators and the HNSW Index
  • RAG Ingestion in Spring AI: Parse Markdown, Chunk by Section, Embed Into pgvector With Stable Ids
  • Tuning Retrieval in Spring AI: Top-k, a Minimum Score, a Tenant Filter Inside the Query, Hybrid Search and a Reranker
  • Tool Calling in Spring AI 2: @Tool Methods, the ToolCallingAdvisor Loop and a Tool-Call Limit
  • Chat Memory in Spring AI: MessageChatMemoryAdvisor, a Conversation Id, a Window, a Summary and Where the State Lives
  • Building an MCP Server in Java With Spring AI: @McpTool, Stateless Streamable HTTP and Least-Privilege Tools
  • Consuming MCP Servers From Spring AI: a stdio Child Process and a Remote Streamable HTTP Server, Compared
  • A Supervisor and Specialist Agents in Spring AI: Own Prompts, Own Tools, Explicit State and a Menu Checked in Code
  • Choosing a JVM Agent Framework: the Same Two-Step Triage in Spring AI, LangChain4j Agentic and Embabel
  • Observability for Spring AI Calls: a Span per Feature, Token and Spend Counters, Jaeger Traces and Two Prometheus Alerts
  • Evals and Cost Control for a Java Subtitle Service: A Golden Set Scored by Word Error Rate in CI, and the Cost of One Hour of Audio From Micrometer Meters
  1. Blog
  2. /
  3. Spring Boot
  4. /
  5. Security

Reviewing AI-Written Spring Code for Security: Four Questions for Every Diff

An agent writes a CSV export for Relay in two minutes. It compiles and works, and it has four holes: no owner check, glued SQL that returns all 50 tickets, a token in the log with a key in the config, and two e-mail columns nobody asked for. Find them with four questions and prove every fix.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Security

What you will learn

  • Review a diff with four questions: access, parameters, secrets, output
  • Prove a missing owner check and a SQL injection with real requests
  • Fix glued SQL with a typed parameter and a repository method
  • Use an AI as a hostile second reviewer without handing it the decision

Before you start

  • Method Security in Spring: @PreAuthorize and Ownership
  • Spring Data Query Methods

We asked an AI agent for one feature: a signed CSV export of tickets by status, for logged-in users only. Two minutes later it's done. It compiles, it runs, and Liam (an agent) gets his file:

HTTP/1.1 200
Content-Type: text/csv
X-Export-Signature: ...

id,subject,status,priority,customer_email,agent_email
3,How do I export my data to CSV?,OPEN,MEDIUM,olivia.bennett@example.com,
5,App crashes when I upload a photo,OPEN,HIGH,james.walker@example.com,sophia.reed@relay.example
7,How do I add a team member?,OPEN,HIGH,olivia.bennett@example.com,
...

Twenty open tickets. It all looks right, and that's exactly when a review pays off. Here's the agent's controller and the heart of its service:

@GetMapping("/api/tickets/export")
public ResponseEntity<String> export(@RequestParam String status,
        @RequestHeader("Authorization") String auth)
        throws GeneralSecurityException {
    log.info("Export {} requested, Authorization: {}", status, auth);
    String csv = export.csv(status);
    return ResponseEntity.ok()
            .header("Content-Type", "text/csv")
            .header("X-Export-Signature", export.sign(csv))
            .body(csv);
}
public String csv(String status) {
    String sql = "select t.id, t.subject, t.status, t.priority, "
            + "c.email as customer_email, a.email as agent_email "
            + "from ticket t join customer c on c.id = t.customer_id "
            + "left join agent a on a.id = t.assignee_id "
            + "where t.status = '" + status + "' order by t.id";
    // ... each row becomes a CSV line
}

And two lines it added to application.yaml: relay.export.secret: relay-export-key-..., a signing key in plain text.

Four questions, asked of every diff

Four review questions: 1 access, who may call and see this data; 2 parameters, is SQL built by gluing text; 3 secrets, any key or token in code, config or log; 4 output, a small record or the whole row. 1. AccessWho may call this?May they seethis data? 2. ParametersIs any SQL builtby gluing text? 3. SecretsA key or token incode, config or log? 4. OutputA small record,or the whole row? About five minutes per diff. No security degree needed.
Walk the request through every layer with these four questions in hand.

1. Access: nobody asks whose tickets these are

Olivia is a customer. Her token is valid, so the chain lets her in. She calls the same export:

id,subject,status,priority,customer_email,agent_email
3,How do I export my data to CSV?,OPEN,MEDIUM,olivia.bennett@example.com,
5,App crashes when I upload a photo,OPEN,HIGH,james.walker@example.com,sophia.reed@relay.example
7,How do I add a team member?,OPEN,HIGH,olivia.bennett@example.com,
8,Email notifications arrive late,OPEN,LOW,noah.carter@example.com,
...

Twenty rows from five different customers. Noah's tickets are in her file. The controller never asks who is calling. "Logged-in users only" was in the prompt, and the agent did exactly that, nothing more. It never learned that customers see only their own tickets, so we have to tell it.

2. Parameters: the status text becomes part of the SQL

Look at + status +. The user writes part of our query. Olivia sends status=OPEN' or '1'='1 (URL-encoded):

curl -i "http://localhost:8080/api/tickets/export?status=OPEN%27%20or%20%271%27=%271" -H "Authorization: Bearer <Olivia's accessToken>"

200, and 50 tickets of every status. The where clause became "status is OPEN, or one equals one", which is always true. That's SQL injection, and it's the oldest hole in the book.

3. Secrets: a token in the log, a key in the file

The agent helpfully logs the whole Authorization header:

INFO  ExportController : Export OPEN requested, Authorization: Bearer eyJ...

The real line carries Olivia's full token. Anyone who can read the logs can now act as Olivia until it expires. And the signing key sits in application.yaml, so anyone with the repository can sign fake exports.

4. Output: the whole row goes out

The select asks for c.email as customer_email, a.email as agent_email. Every line of the file carries two e-mail addresses that nobody asked for. Send only what the caller needs.

The fixes

The controller takes a typed Status and the Authentication the chain made, logs only the name, and decides the owner:

@GetMapping("/api/tickets/export")
public ResponseEntity<String> export(@RequestParam Status status,
        Authentication login) throws GeneralSecurityException {
    log.info("Export {} requested by {}", status, login.getName());
    boolean customer = login.getAuthorities().stream()
            .anyMatch(a -> a.getAuthority().equals("ROLE_CUSTOMER"));
    String csv = export.csv(status, customer ? login.getName() : null);
    return ResponseEntity.ok()
            .header("Content-Type", "text/csv")
            .header("X-Export-Signature", export.sign(csv))
            .body(csv);
}

The service uses two repository methods (no glued text) and a small record:

List<Ticket> findByStatusOrderById(Status status);
List<Ticket> findByStatusAndCustomerEmailOrderById(Status status, String email);
public String csv(Status status, String owner) {
    List<Ticket> found = owner == null
            ? tickets.findByStatusOrderById(status)
            : tickets.findByStatusAndCustomerEmailOrderById(status, owner);
    StringBuilder csv = new StringBuilder("id,subject,status,priority\n");
    for (Ticket t : found) {
        csv.append(ExportRow.of(t).line());
    }
    return csv.toString();
}
public record ExportRow(Long id, String subject,
        Status status, Priority priority) {
    static ExportRow of(Ticket t) {
        return new ExportRow(t.getId(), t.getSubject(), t.getStatus(), t.getPriority());
    }
    String line() {
        return id + "," + subject + "," + status + "," + priority + "\n";
    }
}

And the key comes from the environment: relay.export.secret: ${EXPORT_SECRET}.

Prove every fix

A fix you haven't proven is a guess. Run the same requests again:

Olivia  OPEN      -> 200, 6 tickets, all hers (columns: id,subject,status,priority)
Noah    OPEN      -> 200, 6 tickets, none of them Olivia's
Liam    OPEN      -> 200, 20 tickets (staff see all)
Olivia  status=OPEN' or '1'='1  -> 400 Failed to convert 'status' with value: 'OPEN' or '1'='1'
no token          -> 401

The injection now dies before any SQL exists: Spring can't turn that text into a Status enum, so it's a 400. The log line is Export OPEN requested by [email protected]. A name, never a token.

Let the AI attack its own work

A useful second pass: give the diff back to an AI with a prompt that makes it a hostile auditor, walking the same four questions and answering pass or fail for each. It's fast at spotting glued SQL, a missing owner check, secrets and fields that shouldn't go out. But it doesn't know your business rules. You decide who should see which tickets, and you run the proving requests again yourself.

Common mistakes

  • "The tests pass" as a review. The agent's tests check what it built, not what it forgot.
  • String parameters for fixed values. A typed enum rejects anything else for free.
  • Logging headers "for debugging". Log the user name and the action. Never a token.
  • Accepting a fix without the request that proves it.

Try it yourself

In the finished project, the last line of ExportService is a commented // BREAK IT: query with the glued where t.status = '" + status + "'. Put it back, run the injection call, count the rows, and undo it. Which of the four questions would have caught it?

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Spring Boot · 69 of 99

Previous
CORS and CSRF in Spring Security: Why the Browser Blocks Your SPA, and When CSRF Can Be Off
Next post
Testing Secured Endpoints in Spring Boot: 401, 403 and 200 with @WithMockUser

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

A Registration Form With Bean Validation in Spring Boot: @Valid, BindingResult and th:errors

A RegisterForm record with three annotations checks the name, email and password at the door. Bad data goes back to the form with a message under each field; good data becomes an Account row. And the password is still stored as plain text, which the next step fixes.

Spring Security 7 Form Login, BCrypt and a UserDetailsService on the Account Table

A guard at the gate and a hash in the table. A SecurityFilterChain lists the open pages and sends everything else to /login, a BCrypt PasswordEncoder bean hashes every password, and a UserDetailsService answers 'who is this email?' from the ACCOUNT table.

Roles and Authorities at Login in Spring Security: From a ROLE Column to hasRole("ADMIN")

Until now every login got .roles("USER") typed into the code. A Role enum on Account, one changed line in the UserDetailsService and one hasRole rule let Chaand open /admin while Emma gets a 403 and a visitor is sent to log in.

Menus per Role With Thymeleaf Security Tags: sec:authorize, sec:authentication and an Edit Button for the Author

One header file, three menus: a visitor sees Register and Login, Emma sees her email and Logout, Chaand also gets Admin. Then each post knows its author through @ManyToOne, and the Edit button shows only for the author or an admin.

On this page

  • Four questions, asked of every diff
  • 1. Access: nobody asks whose tickets these are
  • 2. Parameters: the status text becomes part of the SQL
  • 3. Secrets: a token in the log, a key in the file
  • 4. Output: the whole row goes out
  • The fixes
  • Prove every fix
  • Let the AI attack its own work
  • Common mistakes
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.