Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 119 ยท Web Fundamentals

Web Security Basics

Learn web security essentials in Java - authentication vs authorization, sessions and tokens, PBKDF2 password hashing, HTTPS, XSS, CORS, CSRF and the OWASP Top 10.

The moment your API is reachable from the internet, someone will try to break it. Not because your application is special, but because automated scanners try every public server, every day: guessing passwords, probing for SQL injection, reading other users' data by changing an id in the URL. Most successful attacks don't use clever exploits. They use simple mistakes that developers make again and again.

This lesson covers the security knowledge every backend Java developer needs before writing a login form or a public endpoint: the difference between authentication and authorization, sessions versus tokens, how to store passwords (with a runnable PBKDF2 implementation using only the JDK), HTTPS, cross-site scripting, CORS and CSRF, and the OWASP Top 10 as a checklist. Later lessons apply it with frameworks in Spring Security and JWT and OAuth 2.

Authentication and authorization

Two words that sound alike and mean different things:

  • Authentication (authn) answers who are you? The user proves an identity with a password, a passkey, a one-time code, a certificate or a token issued by an identity provider.
  • Authorization (authz) answers what may you do? Given the identity, may this user read order 42, delete this comment, or call this admin endpoint?

The HTTP status codes mirror the split: 401 Unauthorized means authentication is missing or failed (the name is a historical accident), and 403 Forbidden means the user is known but not allowed.

Authorization failures are the most common serious vulnerability on the web. The classic form is an IDOR (insecure direct object reference): GET /invoices/1001 returns the invoice to anyone who is logged in, so a user changes the number to 1002 and reads someone else's invoice. Logging in is not permission. Every request for a specific resource must check that this user may access this resource:

Java
Invoice invoice = invoices.findById(id).orElseThrow(NotFoundException::new);
if (!invoice.ownerId().equals(currentUser.id()) && !currentUser.hasRole("ACCOUNTANT")) {
    throw new NotFoundException();   // 404 rather than 403: don't reveal that invoice 1002 exists
}

Deny by default, check on the server for every request, and never trust a hidden form field or a client-side check to enforce permissions.

Storing passwords

If your user table leaks (and breaches happen to careful companies too), the attacker gets every stored password hash. What happens next depends entirely on how you hashed them.

  • Plain text or encryption: game over. Encryption is reversible by anyone who gets the key.
  • A fast hash like SHA-256: almost as bad. A modern GPU computes billions of SHA-256 hashes per second, so common passwords fall in seconds. Without a salt, identical passwords even have identical hashes, and precomputed tables crack them instantly.
  • A slow, salted password hashing function: each guess costs real time and memory, and each user's unique salt forces the attacker to attack every hash separately.

The recommended algorithms, in OWASP's current order of preference, are Argon2id, scrypt, bcrypt, and PBKDF2 (the choice when FIPS-140 compliance is required). Libraries such as Spring Security provide all of them. The JDK includes PBKDF2 out of the box, so the next example implements complete password storage with nothing but javax.crypto.

The stored string contains everything needed to verify later: algorithm, iteration count, salt and hash. That lets you raise the iteration count over time and rehash users when they next log in.

Java Password hashing with PBKDF2

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the output carefully:

  • Alice and Bob chose the same password but have different hashes, because each got a random salt. An attacker can't tell they match, and can't use precomputed tables.
  • Verification recomputes the hash with the stored salt and iteration count, and compares with MessageDigest.isEqual, which takes the same time whether the first byte or the last byte differs. A normal Arrays.equals returns early at the first difference, and that timing difference can leak information.
  • The cost difference is the whole point: an attacker can try 50,000 plain SHA-256 guesses in less time than one PBKDF2 hash takes, even with the reduced demo setting. At 600,000 iterations, each guess becomes about 30 times more expensive again. Tune the work factor so one hash takes roughly a quarter to half a second on your production hardware.

More rules for passwords:

  • Use char[], not String, where the API allows it, and clear it after use (PBEKeySpec.clearPassword). Strings are immutable and may linger in memory dumps.
  • Never log passwords, not even failed ones (users often type the password into the username field).
  • Rate-limit login attempts per account and per IP, and consider checking new passwords against lists of breached passwords.
  • Prefer passkeys or an identity provider when you can. The safest password is the one you never store.

Sessions and tokens

After a successful login, the user shouldn't send the password with every request. The server issues a credential that proves "this request comes from the user who logged in". There are two main designs.

Server-side sessions. The server creates a random session id (at least 128 bits from SecureRandom), stores the session data (user id, roles, expiry) in memory, a database or Redis, and sends the id in a cookie. Every request looks the id up. Logging out or blocking a user deletes the session, effective immediately. This is the default in servlet containers and Spring Security, and the right choice for most browser-based applications. Sessions and Cookies shows the details.

Self-contained tokens. The server signs a small document with the user id, roles and an expiry, and the client sends it in the Authorization: Bearer ... header. Any server holding the key can verify the signature without a database lookup, which suits APIs, mobile apps and microservices. The standard format is the JWT (JSON Web Token). The catch: a valid token can't easily be revoked before it expires, so keep access tokens short-lived (minutes) and pair them with refresh tokens.

The next example builds a minimal signed token with HMAC-SHA256 to show the core idea behind JWTs: the payload is readable by anyone, but it can't be changed without the server's secret key.

Java A signed token with HMAC-SHA256

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The real JWT format adds a header (alg, typ) and has more claims, and you should use a well-tested library rather than this sketch. But the security properties are exactly these: integrity (tampering breaks the signature), expiry, and no confidentiality (never put secrets in the payload). Always verify the signature with a fixed, expected algorithm, and keep the signing key in a secret store, not in source code.

HTTPS everywhere

Without TLS, everything you send over HTTP, including passwords, session cookies and tokens, can be read and changed by anyone on the network path: public Wi-Fi, a compromised router, an ISP. HTTPS (HTTP over TLS) encrypts the connection and proves the server's identity with a certificate.

  • Serve everything over HTTPS, not only the login page. A session cookie sent once over plain HTTP is stolen.
  • Redirect http:// to https://, and send Strict-Transport-Security: max-age=31536000; includeSubDomains (HSTS) so browsers never try plain HTTP again.
  • In production, TLS often ends at a load balancer or reverse proxy (nginx, a cloud load balancer, Cloudflare). Encrypt the hop to your Java service too when the network isn't fully trusted.
  • Certificates are free and automated with Let's Encrypt and the ACME protocol. There is no cost reason to skip TLS.

Cross-site scripting (XSS)

XSS happens when an attacker's text ends up in your page as HTML or JavaScript. If a comment containing <script> is shown to other users without escaping, the script runs in their browser, inside your site, with access to their session. It can read the page, act as the user and send data elsewhere.

The fix is output encoding: whenever you put untrusted text into HTML, escape the characters that have meaning in HTML. Template engines (Thymeleaf, JSTL's <c:out>, Jakarta Faces) do this by default; trouble starts when you build HTML with string concatenation, as servlets sometimes do.

Java Escaping untrusted text in HTML

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Escaping must match the context: HTML text and attribute values need the escaping above, but text inside a <script> block, a URL or CSS needs different rules. That is why you should rely on a template engine or an encoder library (such as the OWASP Java Encoder) rather than hand-written code. As a second line of defense, send a Content-Security-Policy header (for example default-src 'self'), which tells the browser to refuse inline scripts and scripts from other origins, and set session cookies to HttpOnly so scripts can't read them.

CORS: who may call your API from a browser

Browsers enforce the same-origin policy: JavaScript on https://shop.example.com may send requests to https://api.example.com, but it may not read the responses, because the origin (scheme + host + port) differs. CORS (Cross-Origin Resource Sharing) is how a server relaxes that rule for origins it trusts.

For simple requests, the browser sends an Origin header and only lets the page read the response if it contains a matching Access-Control-Allow-Origin. For anything else (methods like PUT or DELETE, JSON content types, custom headers), the browser first sends a preflight OPTIONS request asking for permission. This server answers preflights with an allow-list:

Java Answering CORS preflight requests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Two things are easy to misunderstand about CORS:

  • CORS is enforced by browsers only. curl, Postman, mobile apps and other servers ignore it completely. It protects users' browsers from malicious pages; it is not authentication for your API.
  • CORS relaxes security, it never adds any. Don't reflect any Origin back blindly, and never combine Access-Control-Allow-Origin: * with credentials (browsers refuse it anyway). Use an explicit allow-list.

CSRF: requests the user didn't mean to send

Cross-site request forgery abuses the fact that browsers attach cookies automatically. If a user is logged in to bank.example with a session cookie, a malicious page can contain a hidden form that posts to https://bank.example/transfer. The browser sends the user's cookie along, and the bank sees a perfectly authenticated request the user never intended.

Defenses, usually combined:

  • SameSite cookies. SameSite=Lax (Chromium-based browsers treat a missing attribute as Lax, but other browsers may not) stops cookies on cross-site POSTs; SameSite=Strict stops them on all cross-site requests. Set it explicitly on session cookies.
  • CSRF tokens. The server puts a random token into each form (or a readable cookie) and requires it back in a form field or header on every state-changing request. A foreign site can't read the token, so it can't forge the request. Spring Security does this by default for session-based apps.
  • Check Origin / Sec-Fetch-Site headers on state-changing requests and reject cross-site ones.
  • Never change state on GET. Links and image tags trigger GETs from anywhere.

APIs that authenticate only with an Authorization: Bearer header (not cookies) are not vulnerable to classic CSRF, because browsers don't attach that header automatically. That's why many APIs disable CSRF protection, and why doing so is wrong the moment you switch to cookie-based authentication.

Security headers

A few response headers switch on browser protections at almost no cost:

Header Example value Protects against
Strict-Transport-Security max-age=31536000; includeSubDomains Downgrade to plain HTTP
Content-Security-Policy default-src 'self'; frame-ancestors 'none' XSS impact, clickjacking
X-Content-Type-Options nosniff Browsers guessing a script out of an upload
Referrer-Policy strict-origin-when-cross-origin Leaking full URLs to other sites
Cache-Control no-store (on private data) Sensitive pages stored in shared caches

Session cookies should carry Secure; HttpOnly; SameSite=Lax (or Strict).

The OWASP Top 10

The OWASP Top 10 is a widely used awareness list of the most critical web application security risks, maintained by the Open Worldwide Application Security Project. The current edition is OWASP Top 10:2025. Many older audits and tools still reference the 2021 list, so you will see both numbering schemes in the wild.

# Risk (2025) In one sentence Java example of the defense
A01 Broken Access Control Users act outside their permissions (IDOR, missing checks, and now also server-side request forgery) Check ownership on every request; deny by default; allow-list target hosts for server-side fetches
A02 Security Misconfiguration Default passwords, verbose errors, open admin consoles Hardened configs, no stack traces to clients
A03 Software Supply Chain Failures Compromised or vulnerable dependencies, build systems and distribution channels Dependency scanning (OWASP Dependency-Check, Dependabot), locked versions, signed artifacts
A04 Cryptographic Failures Sensitive data unprotected in transit or at rest HTTPS, PBKDF2/bcrypt/Argon2 for passwords, no home-made crypto
A05 Injection Untrusted data interpreted as code: SQL, OS commands, LDAP, also XSS PreparedStatement, output encoding
A06 Insecure Design Security missing from the design itself Threat modeling, rate limits, safe defaults
A07 Authentication Failures Weak login, session handling, credential stuffing Rate limiting, MFA, secure session cookies
A08 Software or Data Integrity Failures Untrusted updates, insecure deserialization Signed artifacts, no Java deserialization of untrusted data
A09 Security Logging & Alerting Failures Attacks go unnoticed, or nobody is told Log logins and access denials, and alert on anomalies
A10 Mishandling of Exceptional Conditions Poor error handling, logic errors and systems that "fail open" Fail closed, catch specific exceptions, test the error paths

Compared with the 2021 list, access control stays at number one and now absorbs server-side request forgery (SSRF), which had its own entry. Security misconfiguration moved up from fifth to second place. "Vulnerable and Outdated Components" became the wider software supply chain failures, which covers the whole path from dependency to build to deployment. Two names changed ("Authentication Failures" and "Logging & Alerting Failures"), and mishandling of exceptional conditions is new.

Whichever edition you use, the list makes a good review checklist for every feature you ship. Injection deserves a special mention for Java developers: you already saw the fix in PreparedStatement and SQL Injection.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A logged-in user changes /orders/1001 to /orders/1002 in the URL and sees another customer's order. Which category is this?

    Authentication worked, but the server never checked that this user may see order 1002. Every resource access needs an authorization check.
  2. 2. In the PBKDF2 demo, why do Alice and Bob get different hashes for the same password?

    The random salt is part of the input, so identical passwords produce different hashes. The salt is stored next to the hash for verification.
  3. 3. Why is plain SHA-256 a bad choice for storing passwords?

    Password hashing must be deliberately slow (and salted). General-purpose hashes are built for speed, which helps attackers.
  4. 4. Your API is called by a mobile app and by curl scripts. A developer suggests adding CORS headers to block unwanted clients. What is wrong with that idea?

    CORS controls which web pages may read responses in a browser. Non-browser clients ignore it completely; use authentication and authorization instead.
  5. 5. Which measure protects a cookie-based session from CSRF?

    SameSite stops the browser from attaching the cookie to cross-site requests, and a CSRF token proves the request came from your own page. HttpOnly protects against script access (XSS), not CSRF.

Summary

  • Authentication proves who the user is (401 when missing); authorization decides what they may do (403). Check authorization on the server for every resource, every time.
  • Store passwords with a slow, salted algorithm: Argon2id, scrypt, bcrypt or PBKDF2 (600,000 iterations for PBKDF2-HMAC-SHA256). Compare hashes in constant time with MessageDigest.isEqual, and never log passwords.
  • Sessions keep state on the server behind a random cookie id and are easy to revoke; tokens like JWTs are signed, self-contained and best kept short-lived. Signed means tamper-proof, not secret.
  • Use HTTPS everywhere with HSTS.
  • Prevent XSS with context-aware output encoding (template engines do it), plus Content-Security-Policy and HttpOnly cookies.
  • CORS lets trusted origins read your responses in browsers; it isn't access control. Use an explicit allow-list.
  • Prevent CSRF with SameSite cookies, CSRF tokens and no state changes on GET.
  • Add security headers, and use the OWASP Top 10 as a checklist.

Next: Jakarta EE Overview begins the servlet chapter with the specifications and servers behind classic Java web applications.