- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Harden a Spring Boot Banking Admin App
This code lab will teach you how to harden a Spring Boot application with Spring Security and Spring AI against the weaknesses that penetration tests find most often. You’ll test for access control gaps with failing MockMvc tests and solve them with denied permissions by default, a correct role hierarchy, and method security. Then, you’ll migrate legacy password hashes, add HTTPS and one-time-token login, lock down Actuator, move secrets out of source configuration, and protect an AI assistant’s tools with OAuth2 scopes. By the end of this lab, you’ll have practical experience applying layered, test-proven security controls that you can adapt to your own Spring applications.
Lab Info
Table of Contents
-
Challenge
Introduction
Welcome to the lab, Harden a Spring Boot Banking Admin App.
Broken access control is the most common critical weakness in web applications. However, it rarely comes alone: weak password storage, plain HTTP, open management endpoints, secrets in configuration files, and error messages that reveal too much often accompany it. Applications that call AI models add a new risk: the model decides which tools to call and with which arguments, so a single instruction that an attacker hides in your data can make the model act on the attacker's behalf.
In this lab, you'll harden the Globomantics Bank Admin Console, an internal Spring Boot application that branch staff use to look up accounts, freeze them, approve transfers, export reports, and ask an AI assistant for help. A recent penetration test found serious problems, and you'll fix them one by one. By the time you finish, the application will:
- Deny every request that no authorization rule allows, and check access to individual accounts and transfers with method security.
- Prove every fix with MockMvc tests, including a parameterized test that checks every role against every protected endpoint.
- Upgrade legacy password hashes when staff members sign in, offer one-time-token (magic link) login, and redirect every HTTP request to HTTPS.
- Expose only safe Actuator endpoints, and read its secrets from outside the source configuration.
- Authorize each Spring AI tool call with OAuth2 scopes, log security events, and fail closed when something goes wrong. ---
The application structure
The application uses Spring Boot, Spring Security, and Spring AI. Unless the text says otherwise, Java paths in this lab are relative to
src/main/java/com/globomantics/bankadmin.You don't need to change the following parts of the application:
BankAdminApplication.java: The main class.accounts,transfers,reports,staff,ledger: In these packages, you can find the banking features: REST controllers, services, and repositories that use an in-memory H2 database, whichschema.sqlanddata.sqlcreate and fill.accounts/AccountAccessPolicy.java: Object-level authorization rules, for example "this account belongs to the caller's branch". Security expressions can call these rules through theaccountAccessbean.assistant: This package contains the code for the AI assistant. The lab environment has no internet access, soScriptedBankingChatModelstands in for a real large language model. It answers the same way every time, and it's deliberately easy to manipulate.src/test/java/.../support: In this package, you'll find test helpers:SecurityTestSupport(a base class with a ready-to-useMockMvcinstance),TestPrincipals(the staff members in the database),TestRole, andProtectedEndpoint.
Files you will work with
src/test/java/.../AccessControlRegressionTest.javaandAccessMatrixTest.java: Security tests that you'll write.security/SecurityConfig.java: The two security filter chains (the admin console and the AI assistant API).security/AuthorizationConfig.java: The role hierarchy, method security, and authorization events.accounts/AccountService.java: Method security annotations for accounts.security/PasswordConfig.javaandstaff/BankUserDetailsService.java: Password encoding and hash upgrades.security/MagicLinkSuccessHandler.java: Delivery of one-time-token login links.assistant/BankingAssistantTools.java: The tools that the AI assistant can call.security/SecurityEventLogger.javaandweb/ApiExceptionHandler.java: Security logging and error handling.src/main/resources/application.yml: TLS, Actuator, secrets, and Spring AI settings.
Every place you need to change has a
TODO [Task x.y]comment. The application compiles and runs from the start, so you can see each problem before you fix it. ---Staff accounts
The database contains the following staff members. Their passwords follow the pattern
Demo-<username>, for exampleDemo-tina.| Username | Role | Branch | Permissions | |---|---|---|---| |
tina|TELLER|NORTH| View accounts of the NORTH branch | |sam|TELLER|SOUTH| View accounts of the SOUTH branch | |marco|MANAGER|NORTH| Everything a teller can do, plus freeze accounts and approve transfers of the NORTH branch | |priya|AUDITOR|HQ| View (never change) accounts of every branch, and export reports | |david|ADMIN|HQ| Manage staff users (no access to customer data) | |otto|OPS|HQ| Use the Actuator management endpoints |Running the application
To start the application, either click the Run button in the bottom-right corner of the screen, or run the following command in the Terminal:
mvn spring-boot:runThe application listens on two ports,
8081and8443. Until you turn on TLS in Step 3, both ports serve plain HTTP. To open the application in a new browser tab, click the following link: {{localhost:8081}}. Then, sign in as one of the staff members.The console has a single page with shortcut links and an assistant box. Each shortcut calls a REST endpoint, so your browser shows a JSON response instead of a formatted page. When the signed-in staff member isn't allowed to open a page, your browser shows Spring Boot's default error page, which says
This application has no explicit mapping for /error. This is expected: the last line of the page shows the status, for exampletype=Forbidden, status=403.To stop the application, press
Ctrl+Cin the Terminal.Note: In Step 3, you'll turn on HTTPS. From then on, port
8443serves HTTPS with a self-signed development certificate, and port8081redirects every request tohttps://localhost:8443. The lab's browser reaches the application through a proxy: the browser talks HTTPS to the proxy, but the proxy forwards plain HTTP to the application. So after that step, every request reaches the application over HTTP and gets redirected again, and the browser tab shows a redirect error instead of the application. You can still check the application withcurlin the Terminal usinglocalhostand with the-koption for HTTPS URLs. The last step of the lab explains how to run the final application with HTTPS on your own machine.Get started
Begin by examining
security/SecurityConfig.java,security/AuthorizationConfig.java, andapplication.yml. Together, they hold most of the application's security configuration (the two filter chains, the role hierarchy, and the TLS, Actuator, secrets, and Spring AI settings), and you'll change them in most tasks. Also review theTODOcomments that guide each task. If you need it, thesolutiondirectory contains the completed files for each task. -
Challenge
Closing access control gaps
The penetration test report starts with two findings:
- Forced browsing: The home page marks the accounts report link as a page for auditors, but anyone who knows the URL
/reports/exportcan download a CSV file with every account of every branch. A label on a link doesn't control access. - Insecure direct object reference (IDOR): A NORTH teller can read a SOUTH account by changing the account id in the URL from
ACC-N-1001toACC-S-2001. The application checks who the caller is, but not whether the account belongs to the caller's branch.
Spring Security gives you two layers to fix problems like these:
- The security filter chain (
SecurityFilterChain) authorizes HTTP requests by URL, before any controller runs. - Method security (
@PreAuthorize,@PostAuthorize) authorizes calls to service methods, where you can also inspect the arguments and the returned objects.
But before you fix anything, you'll write tests to prove the vulnerabilities exist. A security test that fails today and passes after the fix is the best evidence that the fix works, and it stops the same mistake from coming back.
Testing security with MockMvc
MockMvcsends requests to the application without starting a web server. When you build it withspringSecurity(), every request goes through the real security filter chain. TheSecurityTestSupportbase class insrc/test/java/.../supportalready does this for you and exposes amockMvcfield.To send a request as a specific user, add the
user(...)request post-processor fromSecurityMockMvcRequestPostProcessors. TheTestPrincipalsclass contains the staff members of the database:mockMvc.perform(get("/admin/staff").with(user(TestPrincipals.SAM))) .andExpect(status().isForbidden());Always assert the exact status you expect. A test that only checks "not
200" also passes when the endpoint fails with a500error.The admin console also protects requests that change data, such as
POST /api/accounts/{id}/freeze, against cross-site request forgery (CSRF). If a test sends such a request without a CSRF token, Spring Security answers403 Forbiddenbefore it checks any authorization rule. A test that expects403then passes for the wrong reason, and a test that expects200fails. To add the token, use thecsrf()post-processor:mockMvc.perform(post("/api/accounts/{id}/freeze", "ACC-S-2001").with(user(TestPrincipals.MARCO)).with(csrf())) .andExpect(status().isForbidden());For more options, such as sending the token in a header, see Testing with CSRF Protection in the Spring Security reference documentation.
In the next task, your tests must fail, because the application is still vulnerable: each test expects
403 Forbidden, and the application answers200 OK. The check for the task passes when your tests detect both gaps this way, and the same tests pass after you fix the application in the following tasks. The test class already contains the imports you need. ---After you complete the task, you can run your tests with the following command in the Terminal:
mvn -o test -Dtest=AccessControlRegressionTestWhile the application is still vulnerable, both tests fail with
Status expected:<403> but was:<200>. ---Deny by default
In
security/SecurityConfig.java, you can see that theadminConsolefilter chain authorizes requests with a list of rules:http.authorizeHttpRequests(auth -> auth .requestMatchers("/admin/**").hasRole("ADMIN") .requestMatchers("/api/**").hasAnyRole("TELLER", "AUDITOR") // ... .anyRequest().permitAll());Spring Security evaluates the rules in order, and the first rule that matches the request wins. The last rule,
anyRequest().permitAll(), allows every request that no other rule matched. That's why/reports/exportis open: nobody wrote a rule for it. The same goes for/internal/diagnostics, a troubleshooting endpoint left over from development.The safe approach is deny by default: end the list with
anyRequest().denyAll(), so that every new endpoint stays closed until someone adds a rule for it on purpose.Role hierarchies
The
security/AuthorizationConfigclass declares aRoleHierarchybean that defines which roles include other roles:RoleHierarchyImpl.withDefaultRolePrefix() .role("MANAGER").implies("TELLER") // ... .build();With this hierarchy,
hasRole("TELLER")also grants access to managers. Spring Security uses the sameRoleHierarchybean for URL rules and for method security, so a mistake here grants extra permissions everywhere. A developer added.role("AUDITOR").implies("MANAGER")so that auditors could see everything managers see. But managers can also change data, and auditors must stay strictly read-only (segregation of duties). ---Method security
URL rules can't fix the IDOR finding: every teller may call
/api/accounts/{id}. The question is whether a specific account belongs to the teller's branch, and only the code that loads the account can answer it. Method security lets you put that rule on the service method:| Annotation | When it runs | Typical use | |---|---|---| |
@PreAuthorize("...")| Before the method | Check roles and arguments (#accountId). Use it for methods that change data. | |@PostAuthorize("...")| After the method, before the result reaches the caller | Check the returned object (returnObject). Use it only for methods that read data: when the check fails, the method has already run, including any change it made. |The expressions use SpEL. Besides
hasRole(...)andauthentication, they can call Spring beans with@beanName.method(...), which keeps complex rules in plain, testable Java.This application provides the
accountAccessbean (accounts/AccountAccessPolicy.java) with theisSameBranch(authentication, account)andisInBranch(authentication, accountId)methods. Argument names such as#accountIdwork because Spring Boot compiles the code with the-parametersoption.However, there's a catch: these annotations do nothing until you enable method security with
@EnableMethodSecurityon a configuration class.The
TransferService.approvemethod already has a@PreAuthorizeannotation:@PreAuthorize("hasRole('MANAGER') and @accountAccess.isTransferInBranch(authentication, #transferId)") public Transfer approve(String transferId) { ... }But right now, any teller can approve transfers. ---
After you complete the task, you can run your regression tests again with the following command in the Terminal:
mvn -o test -Dtest=AccessControlRegressionTestBoth of your tests pass now, so the command finishes without errors.
Note: A
403response confirms that the account exists. Astina, you get403forACC-S-2001, but404for an id that doesn't exist, such asACC-S-9999. An attacker can use this difference to find valid account ids (id enumeration). To prevent it, many teams answer404 Not Foundin both cases, for example with a query that only finds accounts of the caller's branch. This lab keeps403, so that your tests can tell a denied request from a missing account. ---Testing every role against every endpoint
These two regression tests prove two fixes, but to be confident that the whole access policy is right, and that it stays right as the application changes, you have to test every role against every protected endpoint. The
ProtectedEndpointenum insrc/test/java/.../supportdescribes the access matrix: each endpoint knows which roles may call it, andexpectedStatusFor(role)returns the status that a role must get (200;401or302for anonymous callers; or403).TestRolelists every kind of caller, including an anonymous one, and itsprincipal()method returns the matching request post-processor.Also,
ProtectedEndpoint.request()adds a CSRF token to every request that isn't aGET, so thePOSTcases test the authorization rules, not the CSRF protection.A JUnit parameterized test runs the same test method once for each set of arguments. Here's an example that passes
1and2(as numbers and words) to theconvertsNumbersmethod:static Stream<Arguments> numbers() { return Stream.of(Arguments.of(1, "one"), Arguments.of(2, "two")); } @ParameterizedTest(name = "{0} is {1}") @MethodSource("numbers") void convertsNumbers(int number, String word) { ... }To combine every endpoint with every role (6 x 6 = 36 cases), you can stream the endpoints and use
flatMapto turn each endpoint into a stream of(endpoint, role)pairs. Thenameattribute gives each case a readable name in the test report.SecurityTestSupportruns every test in a transaction and rolls it back afterward, so cases that change data (freezing an account, approving a transfer) don't affect each other. ---After you complete the task, you can run the access matrix test with the following command in the Terminal:
mvn -o test -Dtest=AccessMatrixTestWhen all 36 cases pass, the command finishes without errors.
- Forced browsing: The home page marks the accounts report link as a page for auditors, but anyone who knows the URL
-
Challenge
Strengthening credentials and transport security
The next findings concern how staff members prove who they are and how their credentials travel over the network:
- The application stores passwords as unsalted SHA-256 hashes, a format that the bank's previous system used.
- Staff members asked for a way to sign in without typing a password on shared branch computers.
- The application accepts plain HTTP, so anyone on the network can read passwords and session cookies.
Password storage with
DelegatingPasswordEncoderSHA-256 is a fast algorithm by design: an attacker with a stolen database can test billions of guesses per second, and without a salt, identical passwords produce identical hashes. Password hashes must be slow and salted, which is what algorithms such as bcrypt, scrypt, and Argon2 provide.
Spring Security's
DelegatingPasswordEncoderlets you change algorithms without breaking existing accounts. It stores the algorithm id in front of each hash:{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BGencode(...)always uses the current algorithm (bcrypt, by default).matches(...)reads the{id}prefix and delegates to the matching encoder. When a hash has no prefix, like the legacy ones in this database, it throws anIllegalArgumentException, so the sign-in fails with an error instead of a "bad credentials" message.setDefaultPasswordEncoderForMatches(...)sets the encoder thatmatches(...)uses for hashes without a prefix. Legacy hashes must not start with{, because the encoder would read that part as an id.
You create the encoder with
PasswordEncoderFactories.createDelegatingPasswordEncoder(), which returns aPasswordEncoder. To callsetDefaultPasswordEncoderForMatches(...), cast the result toDelegatingPasswordEncoder. ThelegacySha256()method inPasswordConfigreturns an encoder for the legacy hashes.Upgrading hashes on login
You can't hash the stored passwords again yourself, because you don't know them. At sign-in, however, the user sends the password in clear text. After a successful login, Spring Security's
DaoAuthenticationProvidercallspasswordEncoder.upgradeEncoding(storedHash). If it returnstrue(for example, because the hash has no prefix or uses an old algorithm), the provider encodes the password again and calls theupdatePassword(user, newPassword)method of yourUserDetailsPasswordService.BankUserDetailsServicealready implements that interface, but itsupdatePasswordmethod saves nothing and returns the user unchanged. Two details matter when you complete it:- The
newPasswordargument isn't the clear-text password: the provider already encoded it with the current algorithm. Save it as it is. If you encode it again, the database stores a hash of the hash, and the staff member can't sign in anymore. - The provider builds the signed-in user from the object that
updatePasswordreturns, so return the user with the new hash, not the original object.BankUserDetails.withPassword(...)returns a copy of the user with a different password. ---
After you complete the task, you can start (or restart) the application and sign in as any staff member, for example
tina. The Terminal that runs the application showsPassword hash upgraded for user=tina (scheme=bcrypt). If you sign in as the same staff member again, no new line appears, because the stored hash already uses bcrypt. ---TLS with SSL bundles
Spring Boot configures TLS with SSL bundles: named sets of key material (certificates, private keys, and trust stores) that the web server and HTTP clients can share. A PEM bundle points to the certificate and private key files:
spring: ssl: bundle: pem: mybundle: keystore: certificate: "file:path/to/server.crt" private-key: "file:path/to/server.key" server: ssl: bundle: mybundleThe
file:prefix reads the files from the file system, so the key material stays outside the application JAR, and each environment can replace or rotate it. Theconfig/tlsdirectory contains a development certificate forlocalhost.Redirecting HTTP to HTTPS
The server listens on port
8443(server.port), andsecurity/HttpConnectorConfig.javaadds a plain HTTP connector on port8081(banking.http-port), so that users who typehttp://...still reach the application. Spring Security'sredirectToHttps(...)makes sure they don't stay on HTTP: it answers every plain HTTP request with a redirect to the HTTPS URL. To choose the HTTPS port, it uses a port mapping. The default mapping only knows80to443and8080to8443, soHttpConnectorConfigalso provides a mapping from8081to8443.Over HTTPS, Spring Security also adds the
Strict-Transport-Security(HSTS) header, which tells browsers to use HTTPS for this site from now on. ---After you complete the task, you can restart the application, and in a new Terminal tab, check the redirect with the following command:
curl -i http://localhost:8081/dashboardThe response is
302with the headerLocation: https://localhost:8443/dashboard.From now on, the browser tab of the application shows a redirect error. The lab's proxy forwards the browser's requests as plain HTTP, so the application redirects each of them to HTTPS again. The last step of the lab explains how to try the final application in a browser on your own machine. ---
One-time-token login
One-time-token (OTT) login, often called magic link login, lets users sign in without a password. Spring Security implements the following flow when you add
.oneTimeTokenLogin(Customizer.withDefaults())to a filter chain:- The user enters their username in the one-time-token form of the login page, which sends
POST /ott/generate. - Spring Security creates a random token that works once and expires after 5 minutes, and calls your
OneTimeTokenGenerationSuccessHandlerbean. - Your handler delivers a link like
https://.../login/ott?token=...through a channel that only the user controls (email, in a real bank), and shows a "check your inbox" page. - The user opens the link and submits the token to
POST /login/ott, which signs them in.
The handler decides whether this feature is safe. A teammate's first version in
security/MagicLinkSuccessHandler.javawrites the link into the HTTP response "to make testing easier". As a result, anyone who knows a username can sign in as that staff member. The handler must send the link throughMagicLinkOutboxinstead, and the response must only redirect. The lab provides the following helpers:MagicLinkOutboxwrites the link totarget/dev-mailbox/<username>.txtinstead of sending an email.MagicLinkSuccessHandleralready has anoutboxfield, and aredirectToSentPagefield: aRedirectOneTimeTokenGenerationSuccessHandlerthat redirects the browser to the "check your inbox" page,/ott/sent.token.getUsername()returns the username that the token belongs to.
Also notice that
MagicLinksbuilds the link from the configuredbanking.public-base-url, never from the request'sHostheader. Otherwise, an attacker could make the application send victims links that point to the attacker's server. -
Challenge
Securing operations
The application is safer for staff members now, but the penetration testers found two more open doors on the operations side:
- The application exposes every Spring Boot Actuator endpoint to anyone, including
/actuator/env,/actuator/configprops, and/actuator/heapdump. application.ymlcontains the database password and the API key of the core banking ledger, so both secrets are in the Git history, in every JAR, and, through/actuator/env, on the network.
You can see both problems at once: while the application runs, execute
curl -k https://localhost:8443/actuator/envin the Terminal, without signing in. The response shows the value ofbanking.core-ledger.api-key.Exposure and access are two different controls
Actuator has two independent settings that you need:
- Exposure: The
management.endpoints.web.exposure.includeproperty decides which endpoints exist over HTTP at all. By default, Spring Boot exposes onlyhealth. The value"*"exposes everything; replace it with a list of the endpoints you need. - Access: Your security filter chain decides who can call the exposed endpoints.
EndpointRequestprovides request matchers for Actuator endpoints that follow the configured base path:
.requestMatchers(EndpointRequest.to("health")).permitAll() .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ENDPOINT_ADMIN")As always, the first rule that matches wins, so put the specific rule before the general one.
The
healthendpoint usually stays public, because load balancers and orchestrators call it without credentials. Its details, however, describe your infrastructure (database type, disk space, and certificates). Withmanagement.endpoint.health.show-details: when-authorized, only users with one of the roles inmanagement.endpoint.health.rolessee them. Finally,management.endpoint.env.show-values: alwaysturns off the masking of configuration values: never use it outside a local experiment. ---Moving secrets out of source configuration
A secret in
application.ymlis a secret in every copy of the repository, every build artifact, and every container image. The configuration should only name the secrets it needs, and each environment should provide the values.Spring Boot gives you two common ways to do that:
- Environment variables and property placeholders:
password: ${BANK_DB_PASSWORD}reads the value from an environment variable (or any other property source) namedBANK_DB_PASSWORD. Without a default value, the application refuses to start when the secret is missing, which is exactly what you want. - Configuration trees: Kubernetes and Docker mount secrets as files, one file per secret. With
spring.config.import: "optional:configtree:/run/secrets/", Spring Boot turns each file in that directory into a property: the file name becomes the property name, and the file content becomes the value.
In this lab, the
config/secretsdirectory contains the secrets in theBANK_DB_PASSWORDandCORE_LEDGER_API_KEYfiles. The directory is outside the classpath, and Git ignores it. The expression${SECRETS_DIR:config/secrets}lets each environment choose a different directory with theSECRETS_DIRvariable. Environment variables take precedence over the configuration tree, so you can also override any secret without changing the files.Also notice the
@Validatedand@NotBlankannotations inledger/CoreLedgerProperties.java: if a secret resolves to an empty value, the application fails at startup instead of failing later, in the middle of a customer request.Note: Treat any secret that someone ever committed as leaked. Removing it from the file doesn't remove it from the Git history, so you must also rotate it.
- The application exposes every Spring Boot Actuator endpoint to anyone, including
-
Challenge
Securing the AI assistant and failing closed
The last part of the report covers the newest feature: an AI assistant that staff members use from the admin console. A staff member enters a request such as
Summarize account ACC-N-1001, and the assistant answers with the help of tools that read accounts and reverse transactions.How tool calling works in Spring AI
The application builds the assistant with Spring AI 2.1:
assistant/BankingAssistantTools.javadeclares the tools: public methods with the@Toolannotation. Spring AI describes them to the model (name, description, and parameters).assistant/AssistantController.javasends the user's message withChatClient, and passes the tools with.tools(tools)on each request.- The model never runs code. It answers with a tool call: a tool name and JSON arguments. Spring AI's
ToolCallingAdvisor, whichChatClientregisters automatically, executes the method and sends the result back to the model, until the model answers with text.
AssistantControllercalls the model with the blockingcall()method, so Spring AI runs the tools in the same thread as the HTTP request. As a result, the caller'sSecurityContextis available inside the tools, and Spring Security enforces method security annotations on them, just like on any other Spring bean. This doesn't happen automatically in every application: withstream(), Spring AI runs the tools on a Reactor worker thread, where theSecurityContextis empty unless you propagate it.The model is an untrusted caller
The model decides which tool to call and with which arguments, and anything the model reads can influence that decision, including text that attackers write. For example, open
src/main/resources/data.sqland look at the notes of accountACC-N-1001: they contain an instruction to reverse transactionTX-9002. Security teams call this attack indirect prompt injection.ScriptedBankingChatModelbehaves like a model that falls for it: when it summarizes the account, it also reverses the transaction. The system prompt inAssistantControllersays "Only managers may reverse transactions", but a prompt doesn't control access.The right fix is to authorize each tool with the narrowest permission it needs, no matter what the model asks for. OWASP calls the underlying risk excessive agency.
Scoped authorization with OAuth2
The assistant API (
/api/assistant/**) has its own stateless filter chain,assistantApi, which works as an OAuth2 resource server. Clients send a JWT access token, and Spring Security turns each scope in the token into an authority with theSCOPE_prefix. In this lab,GET /assistant/tokenissues tokens for staff members who signed in:| Role | Scopes | |---|---| |
TELLER,AUDITOR|assistant.chat accounts.read| |MANAGER|assistant.chat accounts.read payments.reverse|Right now, the chain accepts any valid token (
anyRequest().authenticated()), and the tools don't check any scope. ---Security event logging
When an attacker probes the application, the security team needs to know which requests the application denied, who sent them, what they targeted, and when. Spring Security publishes application events for this purpose:
- Authentication events: A Spring Boot application publishes
AuthenticationSuccessEventand the subclasses ofAbstractAuthenticationFailureEventautomatically. - Authorization events: The filter chain and method security publish
AuthorizationDeniedEvent, but only after you register anAuthorizationEventPublisherbean:
@Bean AuthorizationEventPublisher authorizationEventPublisher(ApplicationEventPublisher publisher) { return new SpringAuthorizationEventPublisher(publisher); }By default, this publisher reports only denied decisions, otherwise, granted ones would flood the logs. Any bean can receive the events with
@EventListenermethods, like the ones insecurity/SecurityEventLogger.java.When logging security events:
- Record the event type, the principal, the target (the URL or the secured method), and the time. The provided
securityEvent(type, principal, target)method writes all of them as one line to the dedicatedSECURITYlogger. It also replaces line breaks, so that a crafted username can't forge extra log lines. - Don't record passwords, tokens, one-time-token values, or session ids.
And when reading the events, keep in mind that:
AuthorizationDeniedEvent.getAuthentication()returns aSupplier<Authentication>: callget(), and thengetName(), to read the name of the principal.- The provided
describe(Object)method turns the secured object of an authorization event (event.getObject()) into a readable target, such asGET /admin/stafforTransferService#approve. ---
Failing closed
When something unexpected happens, a secure application fails closed: it denies the operation, reveals nothing about its internals, and never pretends that the operation succeeded. Right now, two parts of the application fail open.
First, the error handler leaks internals.
web/ApiExceptionHandler.javaturns unexpected exceptions into a problem detail (RFC 9457) that includes the exception message, the class name, and the stack trace. When you request/api/accounts/ACC-N-1001/statementastina, the response shows the internal host of the core ledger and the beginning of its API key. A fail-closed handler records the details on the server under an incident id, and returns only a generic message with that id, which support staff can use to find the log entry. The providedIncidentLogrecords the details and returns the id:String incidentId = incidents.record(exception);Second, the application sends tool errors back to the model. When a tool throws an exception (for example,
AuthorizationDeniedExceptionfrom@PreAuthorize), Spring AI sends the exception message back to the model as the tool result by default, and lets the model continue. An over-confident model, like the scripted one, then tells the user that it reversed the transaction. Thespring.ai.tools.throw-exception-on-error: trueproperty makes tool errors end the request instead.There's one more detail. Spring AI wraps the exception of the tool in a
ToolExecutionException, and the@ExceptionHandler(Exception.class)method catches the wrapper, so the dedicatedAccessDeniedExceptionhandler never sees the original exception. The handler must recognize security exceptions anywhere in the cause chain with the providedSecurityExceptions.isSecurityException(exception)method, and rethrow them. Spring Security'sExceptionTranslationFilterthen answers with the right status:401for callers who aren't authenticated, or403for authenticated ones. -
Challenge
Conclusion
Congratulations on successfully completing this Code Lab!
To run the complete test suite, including your own security tests, run the following command in the Terminal:
mvn -o testTrying the final application on your machine
In the lab, the browser reaches the application through a proxy that forwards plain HTTP, so the redirect to HTTPS never ends there. To try the final application in a browser, run it on your own machine. You need Java 25 and Maven:
- In the lab, open Settings, find the Download section, and click Download ZIP to download the complete project, including your changes.
- Extract the ZIP file. In a terminal on your machine, go to the extracted project directory and execute
mvn -o spring-boot:run. If you have internet access, you can leave out the-o(offline) option. - Open
http://localhost:8081in your browser. The application redirects you tohttps://localhost:8443, which uses a self-signed development certificate, so accept the browser warning.
Note: Over HTTPS, the application sends the Strict-Transport-Security (HSTS) header, which tells your browser to use only HTTPS for
localhost, on every port, for one year. Browsers ignore the header while they show a certificate warning. But if you make your browser trust the certificate, other local servers that use plain HTTP stop working in that browser. To avoid this, use a private window.Then, try the following:
- Sign in as
tinawith the passwordDemo-tina. Or sign in asmarcowith a magic link: on the login page, entermarcounder Request a One-Time Token, click Send Token, and open the link intarget/dev-mailbox/marco.txt. - As
tina, open Account ACC-S-2001 (SOUTH), Accounts report (auditors), and Actuator metrics (operations team). For each page, your browser shows the error page withstatus=403on its last line. - In the assistant box, ask
Summarize account ACC-N-1001astina: the application denies the injected instruction with403. Then, sign in asmarcoand askReverse transaction TX-9001. If you ask again, the application answers409, because the transaction is already reversed. The application keeps its data in memory, so restart it to start over. - As
marco, askSummarize account ACC-N-1001: the assistant reversesTX-9002. The injected instruction in the account notes still works for staff members who have thepayments.reversescope: scopes limit what an injection can do, but they don't stop it. The second idea under Extending the application addresses this. - Open Statement of account ACC-N-1001. The response only shows
Request failed. Incident <id>. In the terminal that runs the application, the lineIncident <id>: unexpected errorhas the same id, and the full error with its stack trace follows it. - Sign in with a wrong password, or open a page that the signed-in staff member isn't allowed to see. The terminal that runs the application shows a
security_eventline for each attempt.
Using your own certificate
The private key in
config/tls/server.keycomes with the lab download, so you didn't create it and can't know who else has a copy. If you'd rather not trust it, create your own self-signed certificate. Stop the application, and run the following command in the project directory. You need OpenSSL, which Git Bash includes on Windows:openssl req -x509 -newkey rsa:2048 -nodes -days 825 -subj "/CN=localhost" -addext "subjectAltName=DNS:localhost,IP:127.0.0.1" -keyout config/tls/server.key -out config/tls/server.crtThe command creates a new private key and a certificate for
localhostthat's valid for 825 days, and it replaces the two files that thewebSSL bundle reads. In Git Bash, write-subj "//CN=localhost"instead, because Git Bash turns/CN=localhostinto a Windows path.To check the details of the certificate, such as its owner, its validity dates, and its SHA-256 fingerprint, run the following command (
keytoolcomes with the JDK):keytool -printcert -file config/tls/server.crtWhen you start the application again, the certificate that your browser shows for
https://localhost:8443will have the same SHA-256 fingerprint. ---Extending the application
Here are some ideas to keep hardening the console:
- Passkeys: Add
.webAuthn(...)to theadminConsolechain so staff members can register a passkey, and require two factors for managers with@EnableMultiFactorAuthentication. - Human approval for risky tools: Mark
reverseTransactionwith@Tool(requiresConfirmation = true), available since Spring AI 2.1, so that a person must confirm the call before it runs. Scopes keep tellers from reversing transactions, but when a manager asks for a summary ofACC-N-1001, the injected instruction still reversesTX-9002. With a confirmation step, the manager sees the call that the model wants to make and can reject it. - Secret management: Read the secrets from a vault with Spring Cloud Vault instead of a directory, and rotate the API key that
application.ymlused to contain.
By implementing these enhancements, you'll gain a deeper understanding of how Spring Security and Spring AI work together to protect real-world applications.
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.