DEV Community

Cover image for How to Scan with OWASP ZAP: A Developer's Field Guide to Finding Web Vulns Before Anyone Else Does
Mango Developer
Mango Developer

Posted on Originally published at mangodeveloper.com

How to Scan with OWASP ZAP: A Developer's Field Guide to Finding Web Vulns Before Anyone Else Does

The first time I ran OWASP ZAP against a side project, it found a SQL injection in a search endpoint I'd written six months earlier and forgotten about. The fix was two lines of code. The embarrassment lasted longer. If you've never run a real web scanner against your own app, you're flying blind-and that's exactly the problem ZAP exists to solve.

ZAP (Zed Attack Proxy) is the free, open-source web application security scanner from OWASP. It's not as polished as Burp Suite Pro, and it's not as focused as nuclei. What it is, is the tool you reach for when you want to actually find vulnerabilities in your app without paying $400/user/year, when you need to slot a scan into CI without a license negotiation, and when you want to teach junior devs what real attacks look like. The trick is using it right. ZAP will happily tell you nothing useful if you point it at the wrong target, scope it badly, or skip authentication.

This is the article I wish I'd had when I first installed ZAP and got 800 low-confidence alerts on a hello-world app.

What ZAP Actually Is (and What It Isn't)

ZAP is a man-in-the-middle proxy that sits between your browser and your app, recording traffic, spidering URLs, and actively fuzzing parameters. It's two tools in one: a passive scanner that watches the traffic you generate and flags issues (missing security headers, weak cookies, info disclosure), and an active scanner that sends payloads to find injection, XSS, path traversal, and friends.

What it's not: a one-click "find all my bugs" button. Active scans take time and miss things. Passive scans miss things if you don't exercise the app. ZAP doesn't replace a pentester, code review, or SAST tools like Semgrep. It replaces the manual fuzzing you'd otherwise do by hand in Burp Community, and it gives you a repeatable CI pipeline you can run on every PR.

Tool License Strength Weakness Best for
OWASP ZAP Free, Apache 2 CI integration, automation, scripting UX rougher than Burp, fewer advanced manual tools Dev teams, CI pipelines
Burp Suite Pro ~$475/user/yr Best-in-class manual tools, extensions Cost, per-user license Pentesters, dedicated sec teams
nuclei Free, Apache 2 Template-based, fast, huge community Templates only, not a spider/fuzzer Known-vuln checks, bug bounty
arachni Unmaintained Ruby, scriptable Dead project Historical interest
Acunetix / Nessus Commercial Big signature DB, polished reports Expensive, opaque Enterprise compliance

I keep ZAP in my standard toolkit because it's the one I can run in CI without thinking, the one I can hand to a junior dev who's never done security work, and the one that produces a report I can attach to a Jira ticket without anyone asking "is this legal to use?"

Prerequisites

  • An app to scan. Staging or local-never production unless you own it and have written permission. Active scans send attack payloads; running them against someone else's app is a crime in most jurisdictions.
  • Java 17+ for the desktop GUI. ZAP is Java, sorry.
  • Docker, for headless/CI usage. The ghcr.io/zaproxy/zaproxy images are the supported path.
  • A target that's reachable. If your app is on localhost:3000, ZAP needs to reach localhost:3000 from wherever it runs.
  • Basic HTTP knowledge. If you've never looked at a Set-Cookie header, you'll want to skim the OWASP Cookie Security Sheet first.
  • A dedicated test user account on the target. ZAP needs a real account if your app is behind login, and you want to avoid using your own credentials because the scan will produce noise in your audit logs that's hard to untangle from real activity.

How ZAP Fits Together

ZAP runs as a local HTTP(S) proxy. You point your browser at it, browse your app, and ZAP records everything. From that traffic it builds a site tree, runs passive checks, and lets you launch an active scan against any URL in the tree.

CodeCopy

Enter fullscreen mode Exit fullscreen mode

┌────────────┐ HTTP ┌─────────────┐ HTTP ┌──────────────┐
│ Browser │ ─────────> │ ZAP proxy │ ─────────> │ Your app │
│ (Firefox │ <───────── │ (passive │ <───────── │ (staging) │
│ + cert) │ │ scanner) │ │ │
└────────────┘ └─────┬───────┘ └──────────────┘
│
│ active scan (attack payloads)
▼
┌─────────────┐
│ Scan engine │
│ (rules, │
│ scripts) │
└─────────────┘

Enter fullscreen mode Exit fullscreen mode

The desktop UI is a thin layer over the same engine you get in headless mode. Every GUI action has an API equivalent, which is what makes ZAP scriptable end-to-end. Once you understand that split-GUI for exploration, API for repeatable runs-the rest is just learning the verbs.

Installation

Three honest paths. Pick the one matching your workflow.

Desktop GUI (Mac, Linux, Windows): Download the installer from zaproxy.org, or brew install --cask zap on macOS, or sudo apt install zaproxy on Debian-based distros. The brew cask is usually the freshest.

Docker, headless: This is the path you want for CI. Pull the image:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
docker pull ghcr.io/zaproxy/zaproxy:stable

Verify it runs

docker run --rm ghcr.io/zaproxy/zaproxy:stable zap.sh -version

Enter fullscreen mode Exit fullscreen mode


markdown

Python API client: For scripting from Python, install the official client:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
pip install zapv2

Enter fullscreen mode Exit fullscreen mode


markdown

I do 90% of my scanning in Docker now. The desktop GUI is great for exploration and learning, but for anything you'll run more than once, the Docker image is reproducible, doesn't depend on your local Java, and is what you'll use in CI anyway.

One important note on HTTPS: ZAP needs to decrypt TLS traffic to inspect it, which means it generates a root CA you have to trust in your browser. The desktop GUI offers to do this for you. For Docker, you mount the CA cert into the container and accept it in your test browser. Never trust the ZAP root CA on a browser you use for real traffic.

Your First Scan: the GUI Path

Open the ZAP desktop. You'll see a Quick Start tab with two big buttons: "Automated Scan" and "Manual Explore". Both have their place.

Automated Scan is the right starting point for a quick first look at an app you don't know. You give it a URL, it spiders the site, runs passive checks on the spidered traffic, then launches an active scan against everything it found. For a 20-route app this finishes in 10-20 minutes and produces a baseline of issues. Don't trust the count-ZAP will report "Cookie without SameSite attribute" 30 times because there are 30 endpoints setting the same cookie. Group by alert type when you read the report.

Manual Explore is what you want once the app is behind authentication or has flows that need a human to drive. You point ZAP at the target URL, click "Launch Browser", and ZAP opens a Firefox instance pre-configured to use it as a proxy. You log in, click through the flows you care about, and ZAP records everything. The site tree populates as you go. When you've exercised what matters, right-click a folder in the Sites tree and choose "Active Scan" to attack just that subtree.

The mistake I see repeatedly: people hit Automated Scan against an auth-protected app, get back a report saying "no issues found" plus 40 "Authentication Required" responses, and conclude ZAP doesn't work. What actually happened is the spider never got past the login page, so it scanned nothing. Use Manual Explore for anything behind auth.

Contexts, Sessions, and Authentication

A context is ZAP's name for "a logical app." You define one by right-clicking a folder in the Sites tree and choosing "Include in Context." Contexts let you scope spiders and scans to specific URL prefixes, define users, set up authentication, and configure session management. Without a context, ZAP scans whatever you point it at. With a context, ZAP knows which URLs are in-scope, which user to log in as, and how to maintain that session.

Authentication in ZAP is the part most people get wrong, and it's the difference between a useless scan and a useful one. ZAP supports four auth schemes: form-based, HTTP/NTLM, script-based, and JSON-based. For a modern SPA hitting /api/login and storing a JWT, you want JSON-based authentication:

  1. Right-click your context → Authentication → "JSON-based Authentication".
  2. Set the login URL (e.g., https://app.test/api/login).
  3. Set the login request body (e.g., {"email":"zap@test","password":"..."}).
  4. Set the logged-in indicator (a string or regex present in responses when authenticated-e.g., "token" in a Set-Cookie header, or a user_id field in the JSON body).
  5. Set the logged-out indicator (a string that appears when the session has expired-e.g., "error":"unauthorized").

Then define a User in the context (email + password), and ZAP will log in automatically before each spider or scan, detect when the session expires, and re-authenticate. This is the only way active scans work properly against protected apps.

For session management, the "Cookie-based Session Management" mode handles 90% of cases. If your app uses Bearer tokens in headers, you'll need a script-based session management scheme that injects Authorization: Bearer <token> into each request. There's an example script in ZAP's script library under authentication/ - copy it, adapt the regex, and you're done in 15 minutes.

Spider vs AJAX Spider

ZAP has two spiders, and you usually need both.

The traditional Spider is a fast HTML parser. It fetches a page, extracts <a href> and <form action> URLs, follows them, and repeats. It's fast, doesn't run JavaScript, and finds every URL that appears literally in your HTML. For server-rendered apps (Rails, Django templates, plain PHP), it's all you need.

The AJAX Spider is a headless browser (Selenium-driven Chrome/Firefox) that actually executes JavaScript. It clicks links, waits for XHR, scrolls, and triggers event handlers. For any SPA (React, Vue, Svelte, Angular), the traditional spider will find three URLs and the AJAX spider will find thirty. It's slower-a full crawl can take 10-20 minutes vs. seconds for the traditional spider-but it's the only way to discover routes that only exist client-side.

Rule of thumb: if your app has a <div id="root"> and a single <script> tag, use the AJAX Spider. If your server renders HTML, the traditional spider is enough. Run both if you're not sure.

Both spiders respect the context scope and authentication. Without a context, they'll spider whatever's reachable, including third-party CDNs if you're not careful. Always set the scope first.

Active Scan Policies

Active scans run a set of scan rules, each testing for a specific vulnerability class: SQL injection, XSS, path traversal, command injection, XXE, SSRF, and so on. ZAP ships with ~150 rules split across categories, and you can tune which run via scan policies.

A scan policy is a saved configuration of "which rules, at what strength, with what threshold." The defaults are usually fine for a first pass, but two knobs matter:

  • Attack Strength (Low / Medium / High / Insane): how many payloads per parameter. Low sends 1-2, Insane sends dozens. Higher = more thorough + much slower. Medium is the sane default.
  • Alert Threshold (Low / Medium / High): how suspicious a response has to be to flag. Low = flag everything (false positives). High = only flag obvious hits (false negatives). Medium is the default; drop to Low when you're paranoid, raise to High when you're drowning in noise.

You can also disable rules entirely. I disable two by default:

  • TimestampManipulation - high false positive rate, low signal.
  • User Agent Fuzzer - it changes the User-Agent header on every request, which triggers WAF rules and CDN rate limits for no real benefit.

For CI scans, save your policy as a named policy file (Tools → Options → Active Scan → Save Policy), and reference it in the Automation Framework. Don't change policies between runs-consistent scans produce comparable results, which is what makes regression tracking work.

Going Headless: Docker and the Automation Framework

For anything you'll run more than once, use the Automation Framework. It's a YAML-driven way to run ZAP that's been the officially supported automation path since 2.11. The GUI generates the YAML for you (or you write it by hand), and then zap.sh -cmd -autorun config.yaml runs the whole pipeline: spider, passive scan, active scan, report.

Here's a minimal zap-config.yaml for an authenticated scan against a staging app:

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml
env:
contexts:

jobs:

  • type: spider parameters: context: staging user: zap-user maxDuration: 10
  • type: spiderAjax parameters: context: staging user: zap-user maxDuration: 30
  • type: passiveScan-wait parameters: maxDuration: 5
  • type: activeScan parameters: context: staging user: zap-user policy: staging-policy
  • type: report parameters: template: traditional-html reportDir: /zap/wrk reportFile: zap-report.html
Enter fullscreen mode Exit fullscreen mode


plaintext

Run it with:

BashCopy

Enter fullscreen mode Exit fullscreen mode


shell
docker run --rm \
-v $(pwd)/zap-config.yaml:/zap/wrk/zap-config.yaml:ro \
-v $(pwd)/reports:/zap/wrk \
-e ZAP_USER_PASSWORD="$ZAP_USER_PASSWORD" \
ghcr.io/zaproxy/zaproxy:stable \
zap.sh -cmd -autorun /zap/wrk/zap-config.yaml

Enter fullscreen mode Exit fullscreen mode


markdown

Two things to notice. First, secrets come from env vars, not the YAML. Second, passiveScan-wait is a job that just blocks until the passive scanner catches up on the spidered traffic. Without it, your report will be missing passive findings because the active scan started before passive finished processing.

Driving ZAP from Python

Sometimes YAML isn't flexible enough. You want conditional logic, dynamic targets, or integration with a custom reporting pipeline. The zapv2 Python client talks to ZAP's JSON-RPC API over HTTP.

PythonCopy

Enter fullscreen mode Exit fullscreen mode


python
import time
from collections import Counter
from zapv2 import ZAPv2

zap = ZAPv2(proxies={"http": "http://127.0.0.1:8080", "https": "http://127.0.0.1:8080"})

target = "https://staging.example.test"
context_name = "staging"

Spider

print(f"Spidering {target}...")
scan_id = zap.spider.scan(target, contextname=context_name)
while int(zap.spider.status(scan_id)) < 100:
print(f" spider progress: {zap.spider.status(scan_id)}%")
time.sleep(2)

Wait for passive scan to drain

while int(zap.pscan.records_to_scan) > 0:
print(f" passive scan backlog: {zap.pscan.records_to_scan}")
time.sleep(2)

Active scan

print("Active scanning...")
ascan_id = zap.ascan.scan(target, recurse=True, contextname=context_name)
while int(zap.ascan.status(ascan_id)) < 100:
print(f" active scan progress: {zap.ascan.status(ascan_id)}%")
time.sleep(5)

Pull results

alerts = zap.core.alerts(baseurl=target)
for alert in alerts:
print(f" [{alert['risk']}] {alert['pluginid']} {alert['alert']} @ {alert['url']}")

print(f"\nTotal alerts: {len(alerts)}")
print("By risk:")
for risk, count in Counter(a["risk"] for a in alerts).most_common():
print(f" {risk}: {count}")

Enter fullscreen mode Exit fullscreen mode


plaintext

This runs against a ZAP instance you've started separately (zap.sh -daemon -port 8080), which means you can also poke at it interactively from the desktop UI while your script runs. I use this pattern when I want to chain ZAP with other tools-fetch the alerts, deduplicate against a known-issue tracker, post new ones to Slack.

One gotcha: the API has no built-in auth, so bind ZAP to 127.0.0.1 only. If you run the daemon in Docker and need to access the API from the host, use 127.0.0.1:8080 mapping, never 0.0.0.0. There's a network config option in ZAP's options XML to set an API key-use it.

Putting It in CI: GitHub Actions

Here's the workflow I use for running a baseline ZAP scan on every PR. It uses the ZAP baseline scan, which is passive-only (no attack payloads) and finishes in 2-5 minutes. Fast enough to gate merges.

YAMLCopy

Enter fullscreen mode Exit fullscreen mode


yaml

.github/workflows/zap-baseline.yml

name: ZAP Baseline Scan
on:
pull_request:
branches: [main]
schedule:

  • cron: "0 3 * * 1" # weekly full scan on Monday 3am UTC

jobs:
zap-baseline:
runs-on: ubuntu-latest
steps:

  • uses: actions/checkout@v4

  • name: Start staging app
    run: |
    docker compose -f docker-compose.staging.yml up -d
    ./scripts/wait-for-http.sh http://localhost:3000/health

  • name: ZAP baseline scan
    uses: zaproxy/action-baseline@v0.13.0
    with:
    target: "http://localhost:3000/"
    cmd_options: "-a -j -J zap-baseline.json"
    issue_title: "ZAP Security Findings"

  • name: Upload report
    if: always()
    uses: actions/upload-artifact@v4
    with:
    name: zap-report
    path: zap-baseline.json

Enter fullscreen mode Exit fullscreen mode

The -a flag includes all rules (not just the default subset), -j enables the AJAX spider, -J outputs a JSON report. The zaproxy/action-baseline action automatically opens a GitHub issue with the findings if any are above the configured threshold.

For the weekly scheduled run, swap action-baseline for action-full to run active scans. Active scans take much longer (30-90 minutes) and shouldn't gate merges, but they catch things passive scans miss.

Production Considerations

Scope carefully. ZAP will spider and scan anything reachable from the target URL, including third-party CDNs, analytics endpoints, and federated auth providers. Set includePaths to your app only and excludePaths for static assets, logout endpoints, and anything that mutates state in ways you don't want scanned (like password reset endpoints that email real users).

Rate-limit the scanner. ZAP can hammer a target. Default is no concurrency limit, which means 10-20 simultaneous requests per second per rule, multiplied by 50+ active rules = a couple hundred RPS. Most staging environments can't take that, and your WAF will block the source IP after a few minutes. Set threadPerHost in the active scan config to 2-4 for staging, 1 for anything shared. The Automation Framework accepts threadPerHost under the activeScan job parameters.

Don't scan production. I'll say it again. Active scans send attack payloads. Even on apps you own, an active scan in production can: trigger real alerts in your SIEM, pollute analytics, hit rate limits that affect real users, break sessions by sending malformed inputs, and trigger your WAF to block legitimate traffic. Use staging. If you have no staging, set up a feature-flagged read-only replica.

Triage alerts by risk and confidence. ZAP's alert format includes risk (Informational / Low / Medium / High) and confidence (False Positive / Low / Medium / High / Confirmed). Sort by risk desc, confidence desc, then work down. Anything with confidence "Low" or "False Positive" should be reviewed but not acted on without manual verification. The ZAP community maintains a "false positive" tag-use it.

Version your policy and config. Commit zap-config.yaml, your saved scan policies, and the threshold baseline (zap-baseline.json) to git. When a scan finds a new alert, the diff against the baseline tells you immediately whether it's a regression or a pre-existing issue. Without a baseline, you'll re-triage the same 30 low-severity findings every week.

Archive reports. Save the HTML and JSON reports as build artifacts in your CI system, and copy them to a long-term storage bucket with 1-year retention. Compliance frameworks (SOC 2, ISO 27001) want evidence of recurring scans; the saved reports are that evidence.

Common Mistakes

Scanning without authentication. The most common mistake, and the most silent. ZAP will happily report "0 vulnerabilities found" on a login-protected app because it scanned the login page. Always check the spidered URL count-if it's 5 URLs and you have 50 routes, you didn't auth.

Scanning production. Yes, really. People do this. Don't. If you must scan production, use passive-only mode (baseline scan), set threadPerHost=1, and never run active scan rules.

Trusting alert counts. ZAP reports the same alert multiple times if it appears on multiple URLs. A "Missing X-Content-Type-Options" alert on 40 endpoints counts as 40 alerts but is one fix. Group by pluginid to get the real picture.

Ignoring Informational alerts. They look like noise ("User Agent Fuzzer found no anomalies"), but Informational alerts include things like "Cookie set without HttpOnly flag" and "Authentication Submitted" which are real findings. Read them once; you'll learn which to ignore.

Setting attack strength to Insane. It sounds fun. It takes 10x longer, generates 10x the traffic, and the marginal findings over High strength are usually false positives. Use High at most; Medium is the sane default.

Not excluding logout/password-reset endpoints. The scanner will hit them. Logout will end your auth session and every subsequent request will be unauthenticated, scanning nothing. Password reset will send real emails to your test user's inbox, possibly rate-limiting your email provider.

Forgetting the AJAX spider on SPAs. The traditional spider on a React app finds three URLs and concludes the app has no surface area. Run the AJAX spider.

Troubleshooting

"0 alerts found" but you expected issues. Check the spidered URL count. If it's under 10 on a real app, authentication failed. Verify the logged-in regex matches your actual response-open the URL in a browser, copy the response body, and check the regex against it. A common bug: setting loggedInRegex to "userId" but the JSON has "user_id". Regex is case-sensitive by default.

Active scan is incredibly slow. Two usual causes. First, threadPerHost is too low-bump to 2-4 for staging. Second, the app is slow-ZAP waits for responses. Check your staging environment's response times; if it's hitting a real DB with no caching, fix that first. Third possibility: AJAX spider with maxDuration: 0 (unlimited) on a large SPA. Always set a max.

Lots of "Authentication Required" responses in the Sites tree. ZAP's session expired mid-scan and didn't re-auth. Verify your logged-out indicator regex isn't matching responses that are actually authenticated (e.g., a regex that matches a common error string). Increase maxDuration on the auth session or set up periodic re-auth.

Scan reports a CSRF token as a vulnerability ("Anti-CSRF Tokens Check"). This is a real but minor finding-ZAP detected your form has a CSRF token, which is good, but the scanner couldn't verify the token is actually validated server-side. Manually confirm with a request that omits the token; if the server rejects it, the alert is a false positive.

Docker container can't reach localhost. Classic. The container's localhost is the container, not the host. Use host.docker.internal on Docker Desktop, or --network=host on Linux (with appropriate security considerations). For cloud CI runners, run the app in the same Docker network as ZAP and reference it by container name.

"Connection refused" to staging. Your CI runner is in a different network/VPC than staging. Use a self-hosted runner inside the staging VPC, or expose staging over a VPN, or run ZAP in a container deployed next to staging. Don't expose staging to the public internet just for scans.

The JSON report is huge. A 50-route app with active scan can produce a 5MB JSON file. Most CI systems handle that fine, but if you're posting to a GitHub issue or Slack, you'll hit size limits. Use zaproxy/action-baseline's built-in summarizer or filter to High/Medium risk only before uploading.

Cost Considerations and Alternatives

ZAP itself is free, Apache 2 licensed, no per-user or per-scan costs. The real costs are:

  • Compute: a CI runner for 5-90 minutes per scan. GitHub Actions free tier covers most small teams. Larger setups want a self-hosted runner.
  • Staging environment: if you don't have one, you need one. This is the real cost of doing security scanning properly-most teams spend more on staging infra than on the scanner.
  • Time to triage: non-zero. A 50-alert report takes 1-2 hours to triage the first time, 15 minutes once you have a baseline.
Alternative Cost When to choose
Burp Suite Pro $475/user/yr You have a dedicated security person doing manual pentests
Snyk / Veracode $5k-50k/yr You need SCA + SAST + DAST integrated and have budget
GitLab DAST Bundled in Ultimate tier Already on GitLab Ultimate
AWS Inspector Per-scan, pay-as-you-go All-AWS shop, scanning AWS-hosted apps
nuclei (free) Free Known-vuln scanning, bug-bounty-style
Manual pentest $20k-100k per engagement Annual/quarterly deep dive

For most dev teams, the combo "ZAP in CI + annual third-party pentest" is the sweet spot. ZAP catches regressions continuously; the pentest catches the things ZAP can't.

Real-World Use Cases

The PR-regression scan. A fintech startup runs ZAP baseline scan on every PR. New alerts block merge. After two months of grumbling about "this is slowing me down," the team stopped shipping XSS and SQLi to staging. The signal-to-noise ratio is high once you have a baseline.

The weekly full scan. A SaaS company runs active scans every Monday at 3am against staging. The team reviews the report at Monday standup. Anything new gets a Jira ticket. This catches dependency regressions (when a library bump reintroduces an old vuln) and config drift (when someone removes a security header).

The pre-launch pentest companion. Before a product launch, the team runs ZAP, then a third-party pentester runs Burp. The pentester finds 1-2 things ZAP missed; ZAP found 8 things the pentester would have caught. Net result: pentester's time spent on the hard issues, ZAP caught the easy ones. The pentester's bill is lower because they didn't waste time on missing security headers.

The legacy app audit. "We have this 10-year-old PHP app, can you tell us if it's safe?" Run ZAP, get a 200-alert report. Triage by High/Medium risk. The High alerts are the priority list for the rewrite. This is exactly the use case ZAP was built for.

Conclusion

OWASP ZAP is the tool that should be in every web developer's CI pipeline, not because it's perfect, but because it's free, scriptable, and catches the 80% of vulnerabilities that are trivially findable but embarrassingly common. The first scan you run against your own app will be humbling. That's the point. The second scan, with the issues fixed, will be quieter. By the tenth scan, you'll have a baseline and the only alerts will be regressions-which is exactly what you want.

The work isn't running ZAP. The work is setting up authentication correctly, scoping the scan to your actual app, defining a baseline, and triaging alerts consistently. Get that right once, and every subsequent scan is a five-minute review. Get it wrong, and you'll either drown in noise or miss real issues because you didn't auth properly. Use the GUI to learn, use Docker + Automation Framework for everything else, and never-ever-scan production.


Originally published on Mango Developer.

Top comments (0)