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

Fix a Vulnerable Java Patient Records API

An API can pass every test and still hand attackers its most sensitive data. In this guided Code Lab, you'll prove it by attacking a Java patient records API yourself: reading files it should never serve, forging a JSON Web Token that logs you in as someone else, and hiding a script in a patient's record. Then you'll switch sides and fix every flaw you exploited, along with weak password storage, unscanned dependencies, and the flaws an AI coding assistant slipped into a new endpoint. Each fix is proven by a test that attacks your code, so you'll leave with defenses you can trust and take back to your own Java services.

Lab platform
Lab Info
Level
Intermediate
Last updated
Dec 04, 2026
Duration
1h 15m

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

    Step 1: Meet the Patient Records API

    Fix the API before the audit

    Globomantics clinics use the Patient Records API to look up patients, read visit summaries, and download documents such as lab results. An external security audit is coming up, and an internal review just found classic flaws throughout the API. On top of that, a new AI-assisted visit summary feature was merged without a security review.

    You're the developer asked to fix everything before the auditors arrive. For each flaw, you'll see it in action, often by attacking the API yourself, and then fix the code. Tests that send malicious payloads prove each fix. ### What you will learn

    • Eliminate input and output handling flaws in a Java REST API: path traversal and cross-site scripting
    • Upgrade authentication and session handling: Argon2id password hashes, strict JSON Web Token (JWT) validation, and a logout that revokes the token
    • Secure the build and review AI-generated code: a dependency scan, a software bill of materials (SBOM), and fail-closed error handling with masked logs ### Before you begin

    The API is a Java 25 application built with Javalin and Maven. Run every command in the Terminal, from the workspace folder.

    To start the API, or to restart it after you change the code, run:

    ./run-api.sh
    

    The API runs in the background on port 7070 and writes its log to api.log. Most endpoints need a signed-in user. To sign in as the clinician nurse.joy and save the token in the TOKEN variable, run:

    TOKEN=$(curl -s -d '{"username":"nurse.joy","password":"Wint3r-Morning!"}' 
      http://localhost:7070/api/login | cut -d'"' -f4)
    

    Tokens last an hour and survive restarts of the API. If a request answers Sign in to continue., run the sign-in command again. To run one test class, run:

    ./mvnw test -Dtest=DocumentTraversalTest
    

    ./mvnw is the Maven Wrapper, which runs the Maven version the project pins. The lab has no internet access, so every library, and the vulnerability database for the dependency scan, is already downloaded.

    README.md lists the API's endpoints and the test accounts. The solution folder holds the solution for every task, in a folder named after the task, such as solution/task-2.3.

  2. Challenge

    Step 2: Close the path traversal hole in document downloads

    How the document endpoint finds files

    Clinicians download documents, such as lab-results-1001.txt, from GET /api/documents?file=<name>. The documents live in data/documents. Right next to that folder, data/private holds a nightly export of every patient, with insurance numbers.

    DocumentService.resolve, in src/main/java/com/globomantics/patients/DocumentService.java, tries to block path traversal by removing ../ from the name:

    String cleaned = fileName.replace("../", "");
    return baseDir.resolve(cleaned);
    

    Start the API, and sign in:

    ./run-api.sh
    TOKEN=$(curl -s -d '{"username":"nurse.joy","password":"Wint3r-Morning!"}' 
      http://localhost:7070/api/login | cut -d'"' -f4)
    ``` ### Why the filter failed
    
    > **Note:** The filter removes `../` in a single pass. In `....//`, it removes the `../` in the
    > middle, and the characters on either side join up into a new `../`. Filters that strip
    > bad input are easy to get around, so the fix in this step checks where the path ends up
    > instead.
    
    `DocumentTraversalTest` sends payloads to the document endpoint. Its only payload is one
    that the filter already blocks, so the test passes even though the API is vulnerable:
    
    ```java
    @ValueSource(strings = {
            "../private/patient-export.csv"
    })
    ``` ### Check where the path ends up
    
    Run the test:
    
    ```bash
    ./mvnw test -Dtest=DocumentTraversalTest
    

    The two new payloads fail, which proves that the test catches the attack.

    To fix path traversal, check where the path ends up, not what it contains:

    1. Resolve the name against the documents folder.
    2. Normalize the result, which removes every . and .. step.
    3. Reject the result unless it's still inside the documents folder.

    Resolving an absolute path such as /etc/passwd returns that path unchanged, so step 3 catches it too.

    Steps 1 and 2 canonicalize the path: they turn every way of writing it into one standard form, so you can compare it with the documents folder. If a folder can contain symbolic links, use Path.toRealPath() instead, which also follows links, so a link can't point outside the folder. It throws an exception for a file that doesn't exist. The documents folder has no links, so normalize() is enough here.

    Tip: Path.toAbsolutePath() makes a path absolute, Path.normalize() removes . and .. steps, and Path.startsWith(Path) compares whole folder names, not characters. Throw new HttpError(400, "That file name isn't allowed.") to reject a name. ### Confirm the fix

    Run the test again, and all three payloads pass:

    ./mvnw test -Dtest=DocumentTraversalTest
    

    To see the fix in the running API, restart it with ./run-api.sh, and then request the export with a plain ../:

    curl -H "Authorization: Bearer $TOKEN" "http://localhost:7070/api/documents?file=../private/patient-export.csv"
    

    The API answers That file name isn't allowed.

  3. Challenge

    Step 3: Stop stored cross-site scripting in patient notes

    How the summary page shows notes

    Clinicians write notes with PUT /api/patients/{id}/notes, and the summary page at /patients/{id}/summary shows them, both between tags and inside the value attribute of a text box. To block cross-site scripting (XSS), SummaryPage, in src/main/java/com/globomantics/patients/SummaryPage.java, removes script tags from the notes first:

    private static String removeScriptTags(String text) {
        return text.replace("<script>", "").replace("</script>", "");
    }
    

    A script doesn't need a <script> tag, though. An image with an onerror handler runs JavaScript too. ### Watch the script run

    To watch it run, save the summary page as a file:

    curl -s -H "Authorization: Bearer $TOKEN" http://localhost:7070/patients/1001/summary -o summary.html
    

    Open summary.html

    • {{localhost}}/summary.html
    • In the Web Browser tab, enterlocalhost:8080/summary.html

    A dialog box that says XSS appears: the browser ran the attacker's JavaScript, which could just as well have sent a clinician's data somewhere else.

    XssTest stores payloads as notes and checks that the summary page shows them only as text. Its only payload is a <script> tag, which the filter removes, so the test passes:

    @ValueSource(strings = {
            "<script>alert('xss')</script>"
    })
    ``` ### Encode for the context
    
    Run the test:
    
    ```bash
    ./mvnw test -Dtest=XssTest
    

    The two new payloads fail. Instead of hunting for dangerous tags, encode every value for the place it goes. Between tags, < must become &lt;; inside a quoted attribute, " must become &#34;. The OWASP Java Encoder, already in pom.xml, has an encoder for each context.

    Tip: Import org.owasp.encoder.Encode. Encode.forHtml(String) encodes a value that goes between tags, and Encode.forHtmlAttribute(String) encodes a value that goes inside a quoted attribute. Once every value is encoded, the script-tag filter has no job left, so delete it. ### Confirm the fix

    Run XssTest again, and every payload passes.

    ./mvnw test -Dtest=XssTest
    

    The reference check for this task also tries <scr<script>ipt>: the old filter would have removed the inner tag and rebuilt a working <script> from the pieces.

  4. Challenge

    Step 4: Migrate password hashes to Argon2id

    Why one round of SHA-256 isn't enough

    The API stores each password as one round of SHA-256, with no salt. Two users with the same password get the same hash, and an attacker who steals the hashes can test billions of guesses per second. Argon2id is a password hashing function that's slow and uses a lot of memory by design, and it gives every hash its own random salt.

    PasswordHasher, in src/main/java/com/globomantics/patients/auth/PasswordHasher.java, already has what you need, built on Bouncy Castle:

    • argon2id(password, salt, memoryKb, iterations, parallelism, hashLength) computes an Argon2id hash.
    • encode(salt, hash) stores the settings and the salt with the hash, as a string that starts with $argon2id$.
    • MEMORY_KB, ITERATIONS, and PARALLELISM hold the minimum settings that OWASP recommends, and verify already checks both formats.

    Only the method that creates hashes still uses the old format:

    public String hash(String password) {
        return legacyHash(password);
    }
    

    Tip: Create the salt with new byte[SALT_LENGTH], and fill it with RANDOM.nextBytes(salt), which uses a SecureRandom. Pass the same salt to argon2id and to encode. ### Upgrade old hashes as users sign in

    You can't convert the old hashes, because you don't know the passwords they came from. Instead, replace each old hash the next time its owner signs in with the right password. AuthService.login, in src/main/java/com/globomantics/patients/auth/AuthService.java, checks the password here:

    User user = users.find(username);
    if (user == null || !hasher.verify(password, user.passwordHash())) {
        throw new HttpError(401, "Wrong username or password.");
    }
    

    Right after this check is the only moment the API knows that the password is correct.

    Tip: hasher.isLegacy(String storedHash) returns true for an old SHA-256 hash, and users.updatePasswordHash(String username, String newHash) saves a new hash. ### Confirm the upgrade

    GET /api/admin/users reports the hash format of each account. Restart the API to run your changes, and then sign in as nurse.joy:

    ./run-api.sh
    TOKEN=$(curl -s -d '{"username":"nurse.joy","password":"Wint3r-Morning!"}' 
      http://localhost:7070/api/login | cut -d'"' -f4)
    

    The endpoint is for administrators only, so sign in as admin, and then list the accounts:

    ADMIN_TOKEN=$(curl -s -d '{"username":"admin","password":"Adm1n-Only-Secret"}' 
      http://localhost:7070/api/login | cut -d'"' -f4)
    curl -H "Authorization: Bearer $ADMIN_TOKEN" http://localhost:7070/api/admin/users
    

    nurse.joy and admin show argon2id, because each just signed in. dr.adams still shows legacy-sha256 until that user signs in.

  5. Challenge

    Step 5: Harden token validation and add logout

    How the API checks tokens

    When you sign in, the API returns a JSON Web Token (JWT) signed with its RSA private key, which is the RS256 algorithm. JwtVerifier.verify, in src/main/java/com/globomantics/patients/auth/JwtVerifier.java, uses the Nimbus JOSE + JWT library to check each token, and it lets the token's header decide how:

    JWT jwt = JWTParser.parse(token);
    
    // Check the signature with whichever algorithm the token's header names.
    if (jwt instanceof SignedJWT signed) {
        JWSAlgorithm algorithm = signed.getHeader().getAlgorithm();
        JWSVerifier verifier = JWSAlgorithm.Family.HMAC_SHA.contains(algorithm)
                ? new MACVerifier(publicKey.getEncoded())
                : new RSASSAVerifier(publicKey);
        ...
    } else if (!(jwt instanceof PlainJWT)) {
    

    The program attacks/ForgeToken.java forges two tokens for the real admin account, without its password or the API's private key, and calls the admin-only GET /api/admin/users endpoint with each one. ### Pin the algorithm and the key

    Note: The none token claims it needs no signature, and Nimbus parses it as a PlainJWT, which the verifier accepts. The confusion token claims HS256 and is signed with the API's public key, which anyone can download, as the secret. Both attacks work because the token chooses how it's checked.

    The fix is to pin both the algorithm and the key: this API only ever issues RS256 tokens signed with its own key, so it accepts nothing else. JwtValidationTest sends both forged tokens, plus a real token whose payload was changed after signing.

    Tip: SignedJWT.parse(token) accepts only signed tokens, so it throws a ParseException for a none token. Compare signed.getHeader().getAlgorithm() with JWSAlgorithm.RS256, and check the signature with signed.verify(new RSASSAVerifier(publicKey)). Throw new InvalidTokenException("...") to reject a token. ### Revoke tokens on the server

    The API has no way to log out, so a stolen token works until it expires an hour later. Because a JWT is valid on its own, logging out has to happen on the server: the API must remember which tokens it revoked.

    Each token carries a unique ID, its jti claim. AuthService.endSession(tokenId) records that the session is over, and AuthService.authenticate already rejects tokens from sessions that ended. All that's missing is the endpoint. PatientApi.register, in src/main/java/com/globomantics/patients/PatientApi.java, has a placeholder for it:

    // Task 5.3: add the logout endpoint here.
    

    Tip: Register the endpoint with routes.post("/api/logout", ctx -> { ... }). Inside it, auth.requireRole(ctx.header("Authorization"), CLINICIAN, ADMIN) returns the caller's Claims, and claims.tokenId() is the token's ID. Finish with ctx.status(204).

  6. Challenge

    Step 6: Add a dependency scan and an SBOM to the build

    Scan what you ship

    Your own code is only part of what you ship. A dependency scan checks every library the build uses against known vulnerabilities: OWASP Dependency-Check compares them with the National Vulnerability Database (NVD). A software bill of materials (SBOM) lists every library and its version, so when a new vulnerability is announced, you know at once whether you're affected. CycloneDX writes one during the build.

    The CI workflow in .github/workflows/ci.yml runs ./mvnw -B verify, so anything you add to the Maven build runs in CI too, and on any laptop. Both plugins are already pinned in the <pluginManagement> section of pom.xml, so you only need to switch them on in the <plugins> section:

    <plugins>
      <!-- Task 6.1: add the dependency scan and the SBOM plugins here. -->
    </plugins>
    

    Tip: Each plugin needs its groupId and artifactId (org.owasp and dependency-check-maven, org.cyclonedx and cyclonedx-maven-plugin), and an <executions> element with an <execution> that lists its goal under <goals>. Dependency-Check's goal is check, which runs in the verify phase by itself; give it a <configuration> with <formats> listing HTML and JSON, and <nvdApiKeyEnvironmentVariable>NVD_API_KEY</nvdApiKeyEnvironmentVariable> for CI. CycloneDX's goal is makeBom; set its <phase> to package. ### Read the reports

    Build the project the way CI does. The tests for steps 7 and 8 still fail, so skip the tests for now:

    ./mvnw verify -DskipTests
    

    The scan uses the copy of the NVD that was downloaded for this lab, so it takes a little while.

    Open target/dependency-check-report.html:

    • {{localhost}}/target/dependency-check-report.html
    • In the Web Browser tab, enter localhost:8080/target/dependency-check-report.html

    You'll see each library and any known vulnerabilities in it.

    Open target/bom.json in the file tree: each entry under components is a library, with its version and a package URL such as pkg:maven/io.javalin/[email protected]?type=jar.

    Note: In CI, the same build downloads fresh vulnerability data, using an NVD API key stored as the NVD_API_KEY repository secret. In this lab, the data is a snapshot, so a library can have vulnerabilities announced after the snapshot was taken.

  7. Challenge

    Step 7: Review the AI-generated visit summary endpoint

    Review the generated endpoint

    A teammate asked an AI coding assistant for an endpoint that summarizes a patient's latest visit, and merged the result without a review. MockModelClient stands in for the language model, so the lab works offline. Here's the generated AiVisitSummaryEndpoint.handle, in src/main/java/com/globomantics/patients/ai/AiVisitSummaryEndpoint.java:

    public void handle(Context ctx) {
        Patient patient = patients.find(ctx.pathParam("id"));
        ...
        String summary = model.complete("Summarize this patient's latest visit:\n" + patient.notes());
    
        switch (format) {
            case "text" -> ctx.result(summary);
            case "html" -> ctx.html("<h1>Visit summary</h1><p>" + Encode.forHtml(summary) + "</p>");
            default -> ctx.status(400).html("<h1>Unsupported format: " + format + "</h1>");
        }
    }
    

    Review it the way you'd review a teammate's code, starting with who can call it. Request a summary without a token:

    curl http://localhost:7070/api/patients/1001/visit-summary
    

    The API tells anyone about a patient's visit.

    Tip: Every other patient endpoint starts with auth.requireRole(ctx.header("Authorization"), CLINICIAN, ADMIN), which throws an HttpError with status 401 or 403 when the caller isn't allowed. The role constants are in AuthService. ### Find the reflected XSS

    The assistant encoded the model's reply in the html branch, but not the format value in the error response. Whatever a link puts in format comes back as markup. This is reflected XSS.

    Before Task 7.1, anyone could open this URL, so an attacker could send a clinician a link with a script in it. Encode the value anyway: if the API later signs users in with a cookie, or another client renders this error page, the script runs.

    Tip: Use Encode.forHtml from org.owasp.encoder.Encode, as in Step 3. Encode only the inserted value, not the page's own tags.

  8. Challenge

    Step 8: Fail closed with safe, masked logging

    Find the fail-open handler

    AuthService.requireRole, in src/main/java/com/globomantics/patients/auth/AuthService.java, decides whether a request may proceed. When the token check itself crashes, it logs the whole Authorization header and lets the request through:

    } catch (RuntimeException e) {
        // The token check itself crashed. Keep the clinic running and let the request through.
        LOG.warning("Token check crashed for header " + authorizationHeader + ": " + e);
        return new Claims("unverified", allowedRoles[0], "none", 0);
    }
    

    A header with the word Bearer and no token crashes the check. Send one to the admin endpoint:

    curl -H "Authorization: Bearer" http://localhost:7070/api/admin/users
    

    The API lists every account. This is failing open. Security checks must fail closed: when you can't tell whether a request is allowed, deny it. The log line is a second problem: for any other header, it records a complete token that anyone who reads the log could reuse.

    Tip: Throw new HttpError(401, "Sign in to continue."), the same generic response that an invalid token gets. In the log message, use Masker.mask(authorizationHeader), which keeps only the last four characters (import com.globomantics.patients.Masker), and e.getClass().getSimpleName(), which names the kind of error without its details. ### Run the whole build

    Run the whole build the way CI does:

    ./mvnw verify
    

    Every test passes, and the build scans your dependencies and writes a fresh SBOM.

  9. Challenge

    Step 9: Review what you fixed

    What you fixed

    You attacked the Patient Records API the way an attacker would, and then closed every hole you found, before the auditors could. Each fix follows a principle that applies to any Java service: check where input ends up instead of filtering it, encode output for the place it goes, store passwords with a slow, salted hash, let the server decide how tokens are checked, revoke tokens on the server, scan what your build ships, treat AI-generated code as untrusted, fail closed, and keep secrets out of logs.

    Note: The tests you ran are now part of the build. Keep them there, so that a later change that reopens one of these holes fails the build before it reaches production. ### Going further

    • Make the build fail on serious findings: add <failBuildOnCVSS>7</failBuildOnCVSS> to Dependency-Check's configuration, and see what it takes to get the build passing again.
    • Add more payloads to DocumentTraversalTest and XssTest, such as a backslash in a file name or an <iframe> in the notes, and check that your fixes still hold.
    • Fix the header parsing in AuthService.bearerToken, which accepts Bearer without a space. Failing closed made the crash harmless, but it's still a bug.
    • Read the OWASP Password Storage Cheat Sheet, the OWASP JSON Web Token Cheat Sheet, and the OWASP Cross Site Scripting Prevention Cheat Sheet.
    • Continue the path with the Secure Coding in Spring Framework course and the Harden a Spring Boot Banking Admin App lab, which apply these defenses in Spring.
About the author

Roman Canlas is an experienced Application Security Engineer who built a global AppSec program for a Fortune 500 company from the ground up. He holds GWAPT, CSSLP, and CASE.NET certifications and authored the ASP.NET 5 Secure Coding Cookbook.

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