Featured resource
2026 Tech Forecast
2026 Tech Forecast

1,500+ tech insiders, business leaders, and Pluralsight Authors share their predictions on what’s shifting fastest and how to stay ahead.

Download the forecast
  • Lab
    • Libraries: If you want this lab, consider one of these libraries.
    • Core Tech
Labs

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 platform
Lab Info
Level
Intermediate
Last updated
Nov 30, 2026
Duration
1h 30m

Contact sales

By clicking submit, you agree to our Privacy Policy and Terms of Use, and consent to receive marketing emails from Pluralsight.
Table of Contents
  1. 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, which schema.sql and data.sql create 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 the accountAccess bean.
    • assistant: This package contains the code for the AI assistant. The lab environment has no internet access, so ScriptedBankingChatModel stands 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-use MockMvc instance), TestPrincipals (the staff members in the database), TestRole, and ProtectedEndpoint.

    Files you will work with

    • src/test/java/.../AccessControlRegressionTest.java and AccessMatrixTest.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.java and staff/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.java and web/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 example Demo-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:run
    

    The application listens on two ports, 8081 and 8443. 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 example type=Forbidden, status=403.

    To stop the application, press Ctrl+C in the Terminal.

    Note: In Step 3, you'll turn on HTTPS. From then on, port 8443 serves HTTPS with a self-signed development certificate, and port 8081 redirects every request to https://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 with curl in the Terminal using localhost and with the -k option 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, and application.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 the TODO comments that guide each task. If you need it, the solution directory contains the completed files for each task.

  2. 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/export can 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-1001 to ACC-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

    MockMvc sends requests to the application without starting a web server. When you build it with springSecurity(), every request goes through the real security filter chain. The SecurityTestSupport base class in src/test/java/.../support already does this for you and exposes a mockMvc field.

    To send a request as a specific user, add the user(...) request post-processor from SecurityMockMvcRequestPostProcessors. The TestPrincipals class 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 a 500 error.

    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 answers 403 Forbidden before it checks any authorization rule. A test that expects 403 then passes for the wrong reason, and a test that expects 200 fails. To add the token, use the csrf() 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 answers 200 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=AccessControlRegressionTest
    

    While 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 the adminConsole filter 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/export is 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/AuthorizationConfig class declares a RoleHierarchy bean 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 same RoleHierarchy bean 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(...) and authentication, they can call Spring beans with @beanName.method(...), which keeps complex rules in plain, testable Java.

    This application provides the accountAccess bean (accounts/AccountAccessPolicy.java) with the isSameBranch(authentication, account) and isInBranch(authentication, accountId) methods. Argument names such as #accountId work because Spring Boot compiles the code with the -parameters option.

    However, there's a catch: these annotations do nothing until you enable method security with @EnableMethodSecurity on a configuration class.

    The TransferService.approve method already has a @PreAuthorize annotation:

    @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=AccessControlRegressionTest
    

    Both of your tests pass now, so the command finishes without errors.

    Note: A 403 response confirms that the account exists. As tina, you get 403 for ACC-S-2001, but 404 for an id that doesn't exist, such as ACC-S-9999. An attacker can use this difference to find valid account ids (id enumeration). To prevent it, many teams answer 404 Not Found in both cases, for example with a query that only finds accounts of the caller's branch. This lab keeps 403, 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 ProtectedEndpoint enum in src/test/java/.../support describes the access matrix: each endpoint knows which roles may call it, and expectedStatusFor(role) returns the status that a role must get (200; 401 or 302 for anonymous callers; or 403). TestRole lists every kind of caller, including an anonymous one, and its principal() method returns the matching request post-processor.

    Also, ProtectedEndpoint.request() adds a CSRF token to every request that isn't a GET, so the POST cases 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 1 and 2 (as numbers and words) to the convertsNumbers method:

    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 flatMap to turn each endpoint into a stream of (endpoint, role) pairs. The name attribute gives each case a readable name in the test report.

    SecurityTestSupport runs 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=AccessMatrixTest
    

    When all 36 cases pass, the command finishes without errors.

  3. 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 DelegatingPasswordEncoder

    SHA-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 DelegatingPasswordEncoder lets you change algorithms without breaking existing accounts. It stores the algorithm id in front of each hash:

    {bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG
    
    • encode(...) 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 an IllegalArgumentException, so the sign-in fails with an error instead of a "bad credentials" message.
    • setDefaultPasswordEncoderForMatches(...) sets the encoder that matches(...) 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 a PasswordEncoder. To call setDefaultPasswordEncoderForMatches(...), cast the result to DelegatingPasswordEncoder. The legacySha256() method in PasswordConfig returns 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 DaoAuthenticationProvider calls passwordEncoder.upgradeEncoding(storedHash). If it returns true (for example, because the hash has no prefix or uses an old algorithm), the provider encodes the password again and calls the updatePassword(user, newPassword) method of your UserDetailsPasswordService.

    BankUserDetailsService already implements that interface, but its updatePassword method saves nothing and returns the user unchanged. Two details matter when you complete it:

    • The newPassword argument 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 updatePassword returns, 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 shows Password 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: mybundle
    

    The 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. The config/tls directory contains a development certificate for localhost.

    Redirecting HTTP to HTTPS

    The server listens on port 8443 (server.port), and security/HttpConnectorConfig.java adds a plain HTTP connector on port 8081 (banking.http-port), so that users who type http://... still reach the application. Spring Security's redirectToHttps(...) 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 knows 80 to 443 and 8080 to 8443, so HttpConnectorConfig also provides a mapping from 8081 to 8443.

    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/dashboard
    

    The response is 302 with the header Location: 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:

    1. The user enters their username in the one-time-token form of the login page, which sends POST /ott/generate.
    2. Spring Security creates a random token that works once and expires after 5 minutes, and calls your OneTimeTokenGenerationSuccessHandler bean.
    3. 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.
    4. 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.java writes 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 through MagicLinkOutbox instead, and the response must only redirect. The lab provides the following helpers:

    • MagicLinkOutbox writes the link to target/dev-mailbox/<username>.txt instead of sending an email.
    • MagicLinkSuccessHandler already has an outbox field, and a redirectToSentPage field: a RedirectOneTimeTokenGenerationSuccessHandler that redirects the browser to the "check your inbox" page, /ott/sent.
    • token.getUsername() returns the username that the token belongs to.

    Also notice that MagicLinks builds the link from the configured banking.public-base-url, never from the request's Host header. Otherwise, an attacker could make the application send victims links that point to the attacker's server.

  4. 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.yml contains 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/env in the Terminal, without signing in. The response shows the value of banking.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.include property decides which endpoints exist over HTTP at all. By default, Spring Boot exposes only health. 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. EndpointRequest provides 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 health endpoint usually stays public, because load balancers and orchestrators call it without credentials. Its details, however, describe your infrastructure (database type, disk space, and certificates). With management.endpoint.health.show-details: when-authorized, only users with one of the roles in management.endpoint.health.roles see them. Finally, management.endpoint.env.show-values: always turns off the masking of configuration values: never use it outside a local experiment. ---

    Moving secrets out of source configuration

    A secret in application.yml is 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) named BANK_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/secrets directory contains the secrets in the BANK_DB_PASSWORD and CORE_LEDGER_API_KEY files. The directory is outside the classpath, and Git ignores it. The expression ${SECRETS_DIR:config/secrets} lets each environment choose a different directory with the SECRETS_DIR variable. Environment variables take precedence over the configuration tree, so you can also override any secret without changing the files.

    Also notice the @Validated and @NotBlank annotations in ledger/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.

  5. 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.java declares the tools: public methods with the @Tool annotation. Spring AI describes them to the model (name, description, and parameters).
    • assistant/AssistantController.java sends the user's message with ChatClient, 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, which ChatClient registers automatically, executes the method and sends the result back to the model, until the model answers with text.

    AssistantController calls the model with the blocking call() method, so Spring AI runs the tools in the same thread as the HTTP request. As a result, the caller's SecurityContext is 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: with stream(), Spring AI runs the tools on a Reactor worker thread, where the SecurityContext is 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.sql and look at the notes of account ACC-N-1001: they contain an instruction to reverse transaction TX-9002. Security teams call this attack indirect prompt injection. ScriptedBankingChatModel behaves like a model that falls for it: when it summarizes the account, it also reverses the transaction. The system prompt in AssistantController says "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 the SCOPE_ prefix. In this lab, GET /assistant/token issues 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 AuthenticationSuccessEvent and the subclasses of AbstractAuthenticationFailureEvent automatically.
    • Authorization events: The filter chain and method security publish AuthorizationDeniedEvent, but only after you register an AuthorizationEventPublisher bean:
    @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 @EventListener methods, like the ones in security/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 dedicated SECURITY logger. 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 a Supplier<Authentication>: call get(), and then getName(), 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 as GET /admin/staff or TransferService#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.java turns 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/statement as tina, 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 provided IncidentLog records 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, AuthorizationDeniedException from @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. The spring.ai.tools.throw-exception-on-error: true property 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 dedicated AccessDeniedException handler never sees the original exception. The handler must recognize security exceptions anywhere in the cause chain with the provided SecurityExceptions.isSecurityException(exception) method, and rethrow them. Spring Security's ExceptionTranslationFilter then answers with the right status: 401 for callers who aren't authenticated, or 403 for authenticated ones.

  6. 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 test
    

    Trying 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:

    1. In the lab, open Settings, find the Download section, and click Download ZIP to download the complete project, including your changes.
    2. 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.
    3. Open http://localhost:8081 in your browser. The application redirects you to https://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 tina with the password Demo-tina. Or sign in as marco with a magic link: on the login page, enter marco under Request a One-Time Token, click Send Token, and open the link in target/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 with status=403 on its last line.
    • In the assistant box, ask Summarize account ACC-N-1001 as tina: the application denies the injected instruction with 403. Then, sign in as marco and ask Reverse transaction TX-9001. If you ask again, the application answers 409, because the transaction is already reversed. The application keeps its data in memory, so restart it to start over.
    • As marco, ask Summarize account ACC-N-1001: the assistant reverses TX-9002. The injected instruction in the account notes still works for staff members who have the payments.reverse scope: 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 line Incident <id>: unexpected error has 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_event line for each attempt.

    Using your own certificate

    The private key in config/tls/server.key comes 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.crt
    

    The command creates a new private key and a certificate for localhost that's valid for 825 days, and it replaces the two files that the web SSL bundle reads. In Git Bash, write -subj "//CN=localhost" instead, because Git Bash turns /CN=localhost into 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 (keytool comes with the JDK):

    keytool -printcert -file config/tls/server.crt
    

    When you start the application again, the certificate that your browser shows for https://localhost:8443 will have the same SHA-256 fingerprint. ---

    Extending the application

    Here are some ideas to keep hardening the console:

    1. Passkeys: Add .webAuthn(...) to the adminConsole chain so staff members can register a passkey, and require two factors for managers with @EnableMultiFactorAuthentication.
    2. Human approval for risky tools: Mark reverseTransaction with @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 of ACC-N-1001, the injected instruction still reverses TX-9002. With a confirmation step, the manager sees the call that the model wants to make and can reject it.
    3. Secret management: Read the secrets from a vault with Spring Cloud Vault instead of a directory, and rotate the API key that application.yml used 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

Esteban Herrera has more than twelve years of experience in the software development industry. Having worked in many roles and projects, he has found his passion in programming with Java and JavaScript. Nowadays, he spends all his time learning new things, writing articles, teaching programming, and enjoying his kids.

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.

Get started with Pluralsight