Skip to content
Tutorials Center
My learning

Topics

Lesson 114 of 119 ยท Projects

Project: Login and Registration with Servlets, JSP and JDBC

Build a classic Java web app with servlets, JSP, JSTL and JDBC - registration, password hashing, login and logout with sessions, an auth filter and CSRF tokens.

Almost every web application starts with the same three pages: create an account, sign in, and a page only signed-in users may see. They look simple, and that is exactly why they are so often built badly: passwords stored in a way that leaks, sessions that an attacker can hijack, error messages that reveal who has an account, and redirects that send users to phishing sites. In this project you will build that classic login application with servlets, JSP, JSTL and JDBC, and you will get every one of those details right.

Two kinds of code appear on this page. The real application (Jakarta Servlet 6.1 classes, JSP views with JSTL, web.xml) is shown read-only, because a servlet container can't run in your browser. Next to it, four runnable stages rebuild each piece on the JDK's HttpServer with an H2 database and a miniature servlet API that copies the real method names. When you press Run, a real HTTP client registers, signs in and signs out, so you see the actual status codes, Set-Cookie headers and redirects that a browser would get.

You should know Servlets, Handling Requests and Forms, Sessions and Cookies, Filters and Listeners and JSTL and Expression Language. The security background is in Web Security Basics. This project puts all of it together and links back instead of repeating it.

What we are building

The requirements:

  • Register with email, display name and password (entered twice). Emails are unique regardless of case. Passwords need 12 to 128 characters. Errors are shown next to each field, and the form keeps what was typed, except the passwords.
  • Passwords are stored only as salted, slow hashes.
  • Sign in with email and password. A wrong password and an unknown email produce the same message. Five wrong passwords lock the account for 15 minutes.
  • A signed-in user sees /account. Anyone else who opens it is sent to the login form and, after signing in, back to the page they wanted, but never to another site.
  • Sign out destroys the session on the server.
  • Every form is protected against cross-site request forgery (CSRF).
  • Every value from a user is escaped in the HTML.

The real application uses the classic layout of a Maven WAR project. Views live under WEB-INF, so a browser can never request a JSP directly and skip the servlet that prepares its data:

TEXT
login-app/
โ”œโ”€โ”€ pom.xml
โ””โ”€โ”€ src/main/
    โ”œโ”€โ”€ java/com/example/login/
    โ”‚   โ”œโ”€โ”€ User.java, UserDao.java, UserService.java, PasswordHasher.java
    โ”‚   โ”œโ”€โ”€ AppContextListener.java          creates the DataSource and services at startup
    โ”‚   โ””โ”€โ”€ web/
    โ”‚       โ”œโ”€โ”€ PageServlet.java             base class: forwards to a JSP with a CSRF token
    โ”‚       โ”œโ”€โ”€ RegisterServlet.java, LoginServlet.java, AccountServlet.java, LogoutServlet.java
    โ”‚       โ”œโ”€โ”€ CsrfFilter.java, AuthFilter.java
    โ”‚       โ””โ”€โ”€ Csrf.java
    โ”œโ”€โ”€ resources/schema.sql
    โ””โ”€โ”€ webapp/WEB-INF/
        โ”œโ”€โ”€ web.xml                          filter order, session cookie settings
        โ””โ”€โ”€ views/register.jsp, login.jsp, account.jsp
XML
<packaging>war</packaging>

<dependencies>
    <dependency>                              <!-- supplied by Tomcat 11 at run time -->
        <groupId>jakarta.servlet</groupId>
        <artifactId>jakarta.servlet-api</artifactId>
        <version>6.1.0</version>
        <scope>provided</scope>
    </dependency>
    <dependency>                              <!-- JSTL API + implementation: Tomcat doesn't ship them -->
        <groupId>jakarta.servlet.jsp.jstl</groupId>
        <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
        <version>3.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.web</groupId>
        <artifactId>jakarta.servlet.jsp.jstl</artifactId>
        <version>3.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>42.7.14</version>
    </dependency>
    <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
        <version>6.3.0</version>
    </dependency>
</dependencies>

The versions are examples; check for the current ones. The servlet API is provided because the server has its own copy (Servlet Lifecycle and Deployment explains why bundling it breaks class loading). Tomcat implements servlets and JSP but not JSTL, so the JSTL jars go into the WAR. Full application servers such as WildFly or GlassFish include JSTL, and there you would mark it provided too.

Stage 1: users, password hashing and the login rules

The bottom layer has no HTTP at all: a table, a password hasher, a DAO and a service with the rules. Building it first means every security rule can be tested without a server.

The table is called app_user because USER is a reserved word in H2 and several other databases. Two details guard the "unique regardless of case" rule. The service normalizes every email (trims it and lowercases it with Locale.ROOT, so a Turkish system locale can't turn I into a dotless ฤฑ), and a CHECK (email = LOWER(email)) constraint makes sure no code path ever stores a mixed-case email that would slip past the UNIQUE constraint.

PasswordHasher is the PBKDF2 scheme from Web Security Basics, packaged as a class. The stored string contains the algorithm, the iteration count, a random 16-byte salt and the hash, so you can raise the work factor later and verify old hashes with the count stored next to them. Production code should use about 600,000 PBKDF2 iterations, or Argon2id or bcrypt from a library; the demo uses 10,000 so it runs quickly on a shared server.

UserService holds the rules:

  • Registration validates all fields and collects every error into one ValidationException, so the form can show them all at once. A duplicate email is detected by the database: the DAO turns SQLState 23505 (unique violation) into DuplicateEmailException. Checking with a SELECT first would leave a gap in which two simultaneous registrations both pass; the UNIQUE constraint wins every race.
  • Login returns a LoginResult, either a user or one message. An unknown email and a wrong password both return Invalid email or password., and for an unknown email the service still verifies the password against a dummy hash. Without that, an unknown email would be answered in microseconds and a known one after a slow hash, and an attacker could find valid accounts just by timing the responses.
  • Lockout counts failures in one atomic UPDATE. The failure that reaches the limit sets locked_until and resets the counter. A successful login clears both.
Java Stage 1: users, password hashing and the login rules

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 output shows each rule. The email was trimmed and lowercased before it was stored, the hash string reveals its structure but not the password, and hashing the same password twice gives different results because of the salt. The first registration form fails on all four fields at once; the second fails only because [email protected] is the same email in different case. After the wrong password and four more guesses, the fifth failure locks the account, so even the right password is refused until the clock moves past the 15 minutes.

The registration form does reveal whether an email is registered ("An account with this email already exists"). Many sites accept that trade-off for usability. Sites where the existence of an account is itself sensitive answer every registration with "Check your inbox" and send either a confirmation link or a "you already have an account" email. The lockout message has the same property. Both are product decisions; make them on purpose.

Stage 2: servlets, views and sessions

The web layer of the real application is four servlets and three JSPs. The servlets are controllers: they read parameters, call UserService, and either forward to a view or redirect. Services are created once at startup by a listener and stored in the ServletContext, the classic way to share objects without a dependency injection framework:

Java
@WebListener
public class AppContextListener implements ServletContextListener {
    private HikariDataSource dataSource;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        var config = new HikariConfig();
        config.setJdbcUrl(System.getenv("DB_URL"));                  // never hard-code credentials
        config.setUsername(System.getenv("DB_USER"));
        config.setPassword(System.getenv("DB_PASSWORD"));
        dataSource = new HikariDataSource(config);
        var users = new UserService(new UserDao(dataSource), new PasswordHasher(), Clock.systemUTC());
        event.getServletContext().setAttribute("userService", users);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        dataSource.close();                                           // release the pool on undeploy
    }
}

A small base class keeps the views consistent. It puts the CSRF token (stage 3) into the request and forwards to a JSP under WEB-INF/views:

Java
public abstract class PageServlet extends HttpServlet {
    protected UserService users() {
        return (UserService) getServletContext().getAttribute("userService");
    }

    protected void show(String view, HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setAttribute("csrfToken", Csrf.token(req));
        req.getRequestDispatcher("/WEB-INF/views/" + view + ".jsp").forward(req, resp);
    }
}

@WebServlet("/register")
public class RegisterServlet extends PageServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        show("register", req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            users().register(req.getParameter("email"), req.getParameter("displayName"),
                req.getParameter("password"), req.getParameter("confirmation"));
            resp.sendRedirect(req.getContextPath() + "/login?registered");     // Post/Redirect/Get
        } catch (ValidationException e) {
            req.setAttribute("errors", e.errors);
            req.setAttribute("email", req.getParameter("email"));             // never echo passwords
            req.setAttribute("displayName", req.getParameter("displayName"));
            show("register", req, resp);
        }
    }
}

Always prefix redirects with req.getContextPath(): the app may be deployed at /login-app instead of /. Make sure the request encoding is UTF-8 before reading parameters, too. Servlet 6 lets you set <request-character-encoding>UTF-8</request-character-encoding> once in web.xml.

The JSP for the form uses JSTL for every value that came from a user. <c:out> escapes <, >, & and both quote characters, so it's safe in text and inside quoted attributes. EL can read a Map with dot syntax, so ${errors.email} is the message for the email field:

JSP
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Create an account</title></head>
<body>
<h1>Create an account</h1>
<form method="post" action="${pageContext.request.contextPath}/register">
  <input type="hidden" name="_csrf" value="${csrfToken}">
  <label>Email <input name="email" type="email" value="<c:out value='${email}'/>" required></label>
  <c:if test="${not empty errors.email}"><p class="error"><c:out value="${errors.email}"/></p></c:if>
  <label>Name <input name="displayName" value="<c:out value='${displayName}'/>" required></label>
  <c:if test="${not empty errors.displayName}"><p class="error"><c:out value="${errors.displayName}"/></p></c:if>
  <label>Password <input name="password" type="password" minlength="12" required></label>
  <c:if test="${not empty errors.password}"><p class="error"><c:out value="${errors.password}"/></p></c:if>
  <label>Repeat password <input name="confirmation" type="password" required></label>
  <c:if test="${not empty errors.confirmation}"><p class="error"><c:out value="${errors.confirmation}"/></p></c:if>
  <button>Create account</button>
</form>
</body>
</html>

The login servlet is where sessions start. After a successful login it calls req.changeSessionId() before storing the user. The session keeps its attributes but gets a new ID, which defeats session fixation: an attacker who planted a session ID in the victim's browser before login now holds an ID that leads nowhere (the attack is explained in Sessions and Cookies). The session stores a small SessionUser record, never the entity with the password hash, and the record is Serializable so the container can save sessions to disk or replicate them across a cluster.

Java
@WebServlet("/login")
public class LoginServlet extends PageServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        LoginResult result = users().login(req.getParameter("email"), req.getParameter("password"));
        if (!result.succeeded()) {
            req.setAttribute("error", result.error());
            req.setAttribute("email", req.getParameter("email"));
            req.setAttribute("next", req.getParameter("next"));
            show("login", req, resp);
            return;
        }
        User user = result.user();
        req.changeSessionId();                                         // defeat session fixation
        HttpSession session = req.getSession();
        session.setAttribute("user", new SessionUser(user.id(), user.email(), user.displayName()));
        Csrf.rotate(session);
        resp.sendRedirect(req.getContextPath() + safeTarget(req.getParameter("next")));
    }
    // doGet and safeTarget as in the runnable stage 3
}

The runnable stage 2 has the same four servlets on a miniature container. HttpServletRequest, HttpServletResponse, HttpSession and HttpServlet have the real method names (getParameter, getSession(false), changeSessionId, sendRedirect, doGet, doPost), so the servlet code reads like the real thing. The Views class plays the JSPs; its esc method does what <c:out> does. At the bottom, a Browser class (an HttpClient with a cookie jar and automatic redirects switched off) visits the site and prints every hop: method, path, status, Set-Cookie, the page heading and any messages. Lines indented under a 302 are the GET that a browser sends to the Location.

In this stage, AccountServlet checks the session itself. Stage 3 moves that check into a filter.

Java Stage 2: servlets, views and sessions over real HTTP

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.

Follow the conversation from the top:

  • GET /account without a session is redirected to the login form.
  • The invalid registration answers with the form again and three field errors. The valid one answers 302, and the browser's follow-up GET /login?registered shows the notice. That is Post/Redirect/Get: after a successful form post, the server redirects, so pressing Reload repeats a harmless GET instead of posting the form again.
  • The failed login shows the generic message. The successful one is the first response with a Set-Cookie: a new JSESSIONID, with HttpOnly (JavaScript can't read it) and SameSite=Lax (other sites can't send it along with their form posts).
  • The account page shows the name Ana <script>alert(1)</script> escaped, as &lt;script&gt;. The browser displays the text; it never runs it.
  • After the logout, the account page is closed again, and the server holds no sessions.

Stage 3: an authentication filter, CSRF tokens and safe redirects

Three problems remain, and each belongs in a filter or a helper, not in the servlets:

  1. Authentication checks repeat. Every protected servlet would start with the same five lines from stage 2's AccountServlet, and the first page someone forgets is open to everyone. An AuthFilter mapped to /account/* runs before every servlet under that path. A pattern /account/* also matches /account itself. The filter also sends Cache-Control: no-store, so the browser's back button can't show a private page after logout.
  2. Cross-site request forgery. While you are signed in, any other site can show you a form that posts to /logout (or to "change email"), and your browser attaches your session cookie. SameSite=Lax stops most of these cross-site posts in modern browsers, but you shouldn't rely on one cookie attribute alone. The classic defense is a synchronizer token: a random value stored in the session and repeated in a hidden field of every form. CsrfFilter rejects every POST whose token is missing or wrong with 403. Another site can make your browser send the cookie, but it can't read your pages, so it can't know the token. The token is compared in constant time and replaced with a new one at login.
  3. Open redirects. The login form remembers where the user wanted to go in a hidden next field. If the servlet redirected to any next, a link like /login?next=https://evil.example/phish would turn your trusted login page into a springboard for phishing. safeTarget allows only local paths: it must start with / but not // (a protocol-relative URL to another host), and backslashes are refused because some browsers treat /\ like //.

The real filters extend HttpFilter (Servlet 4.0+), which hands you HTTP-typed request and response objects:

Java
public class AuthFilter extends HttpFilter {
    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpSession session = req.getSession(false);                  // never create one here
        if (session != null && session.getAttribute("user") instanceof SessionUser) {
            resp.setHeader("Cache-Control", "no-store");
            chain.doFilter(req, resp);
        } else if (req.getMethod().equals("GET")) {
            String target = req.getRequestURI().substring(req.getContextPath().length());
            resp.sendRedirect(req.getContextPath() + "/login?next=" + URLEncoder.encode(target, UTF_8));
        } else {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    }
}

Filter order matters: the CSRF check should run before anything else touches a POST. The order of @WebFilter annotations is not defined by the specification, so declare the order in web.xml, where <filter-mapping> elements run in the order they appear. The same file configures the session cookie:

XML
<web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" version="6.1">
    <request-character-encoding>UTF-8</request-character-encoding>

    <filter><filter-name>csrf</filter-name><filter-class>com.example.login.web.CsrfFilter</filter-class></filter>
    <filter><filter-name>auth</filter-name><filter-class>com.example.login.web.AuthFilter</filter-class></filter>
    <filter-mapping><filter-name>csrf</filter-name><url-pattern>/*</url-pattern></filter-mapping>
    <filter-mapping><filter-name>auth</filter-name><url-pattern>/account/*</url-pattern></filter-mapping>

    <session-config>
        <session-timeout>30</session-timeout>
        <cookie-config>
            <http-only>true</http-only>
            <secure>true</secure>                       <!-- HTTPS only; the local demo runs on plain HTTP -->
            <attribute>
                <attribute-name>SameSite</attribute-name>
                <attribute-value>Lax</attribute-value>
            </attribute>
        </cookie-config>
        <tracking-mode>COOKIE</tracking-mode>          <!-- never put session IDs in URLs -->
    </session-config>
</web-app>

The logout servlet accepts only POST (a GET logout can be triggered by an <img> tag on any page), invalidates the session, and tells the browser to delete the cookie. The account page shows the signed-in user and the logout form:

Java
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        Cookie expired = new Cookie("JSESSIONID", "");
        expired.setPath(req.getContextPath().isEmpty() ? "/" : req.getContextPath());
        expired.setMaxAge(0);
        expired.setHttpOnly(true);
        resp.addCookie(expired);
        resp.sendRedirect(req.getContextPath() + "/login?loggedOut");
    }
}
JSP
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Your account</title></head>
<body>
<h1>Your account</h1>
<p class="who">Signed in as <c:out value="${sessionScope.user.displayName}"/> (<c:out value="${sessionScope.user.email}"/>)</p>
<form method="post" action="${pageContext.request.contextPath}/logout">
  <input type="hidden" name="_csrf" value="${csrfToken}">
  <button>Sign out</button>
</form>
</body>
</html>

EL reads record components such as ${sessionScope.user.displayName} since Jakarta Expression Language 6.0 (Jakarta EE 11). With older containers, give SessionUser classic getters such as getDisplayName().

In the runnable stage 3, the miniature container gains Filter, FilterChain and addFilter, with the same chain behavior as a real container: each filter decides whether to call chain.doFilter (go on) or to answer by itself (stop). The Browser learns to submit forms like a real browser, copying the hidden _csrf field from the last page it loaded. Its post method sends exactly the fields it is given, which is what a forged form on another site does.

Java Stage 3: an authentication filter, CSRF tokens and safe redirects

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.

Some lines need a closer look:

  • The very first response, GET /register, already sets a cookie. The form needs a CSRF token, and the token lives in a session, so even guests get one on pages with forms. That's normal (and it also protects the login form against login CSRF, where an attacker signs you in to their account).
  • GET /account redirects to /login?next=%2Faccount, and after the login the browser lands on /account. The session ID changed at login, which the program checks by comparing cookies.
  • The forged POST /logout without a token is refused with 403, and the next GET /account proves the user is still signed in.
  • The real logout answers with Max-Age=0, which deletes the cookie, and the login page that follows immediately starts a fresh guest session for its form.
  • The login with next=https://evil.example/phish lands on /account, not on the attacker's site.
  • Replaying the session ID from before the logout gets a redirect to the login form, because that session no longer exists on the server.

The demo runs on plain HTTP, so its cookie has no Secure attribute. In production, serve every page over HTTPS, set <secure>true</secure>, and add Strict-Transport-Security. A session cookie sent over plain HTTP even once can be read by anyone on the same network, and then all the other protections on this page don't matter.

Stage 4: end-to-end tests with JUnit

Security rules are exactly the kind of behavior that breaks silently: nobody notices that the session ID stopped changing at login until an attacker does. Stage 4 turns the walk-throughs of stages 2 and 3 into end-to-end tests that send real HTTP requests to a freshly deployed app. Each test gets its own H2 database and its own server on a random port in @BeforeEach, and stops the server in @AfterEach, so tests can run in any order (setup and teardown are covered in Test Lifecycle and Organization).

The helpers register and login act like a person: they open the form page first and then submit it, so the CSRF token is always fresh. Two choices keep the suite fast. The tests use a PasswordHasher with only 1,000 iterations, because they test the login rules, not the cost of the hash. And the open-redirect rule is a plain unit test of safeTarget with four malicious values, because it needs no server at all.

Java Stage 4: end-to-end tests with JUnit

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.

All 13 tests pass. Each one protects a rule that is easy to break during a refactoring:

  • Delete req.changeSessionId() from LoginServlet and theSessionIdChangesAtLogin fails.
  • Remove container.addFilter("/*", new CsrfFilter()) and aPostWithoutTheCsrfTokenIsForbidden fails: the forged logout now works.
  • Replace esc(user.displayName()) with user.displayName() in Views.account and namesAreEscapedOnEveryPage fails, because the page now contains a live <script> tag.
  • Change the dummy-hash branch in UserService.login to return a different message and aWrongPasswordAndAnUnknownEmailLookTheSame catches the account-enumeration leak.

In the real project, the same tests run against Tomcat itself. You can start an embedded Tomcat in the test (org.apache.tomcat.embed:tomcat-embed-core and tomcat-embed-jasper for JSPs) or deploy the WAR to a container with Testcontainers, and point the same HttpClient helpers at it. Integration Testing shows both approaches.

Design decisions in review

Concern Choice here Why
Password storage PBKDF2 with a random salt and the work factor in the stored string Slow to attack, and the cost can be raised later
Unknown email vs wrong password Same message, and a dummy hash for unknown emails No account enumeration by message or by timing
Duplicate emails Normalized email, UNIQUE + CHECK constraints, SQLState 23505 Correct under concurrent registrations
Brute force Atomic failure counter, 15-minute lock Guessing becomes slow without blocking users forever
Session fixation changeSessionId() at login An ID known before login is worthless after it
Session contents A small Serializable record, no hash Less to leak, works with session replication
Access control AuthFilter on /account/* One place to get right; new pages are protected by default
CSRF Session token in a hidden field, checked by a filter, rotated at login Other sites can trigger requests but can't read the token
Redirects Post/Redirect/Get; next limited to local paths No duplicate posts, no open redirect
Output <c:out> (or esc) for every user value No stored XSS
Cookies HttpOnly, SameSite=Lax, Secure in production, cookie-only tracking Scripts and other sites can't use the session

Spring Security implements most rows of this table for you: password encoders, the session-fixation defense, CSRF tokens, login and logout handling, and a filter chain for access rules (Spring Security). Having built them by hand, you now know what its defaults protect you from, and what breaks when someone switches one off.

Ideas for extending the project

  • Remember me. Add a checkbox that issues a long-lived, random token stored hashed in a remember_token table, with a fresh token on each use and all tokens deleted at password change.
  • Password reset. Email a single-use link with a random token that expires after 30 minutes. Store only a hash of the token, and answer every reset request with the same message, whether or not the email exists.
  • Email verification. Mark new accounts as unverified and let them sign in only after following a link.
  • Change password. Require the current password, rehash with the current work factor, invalidate all other sessions of the user, and rotate the session ID.
  • Rehash on login. When a stored hash has fewer iterations than the current setting, rehash the password after a successful login.
  • Rate limiting per IP address, in addition to the per-account lock, so an attacker can't lock out many accounts or try one password against thousands of emails.
  • Security headers from Web Security Basics (Content-Security-Policy, X-Content-Type-Options, Referrer-Policy) in one more filter.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does UserService verify the password against a dummy hash when the email doesn't exist?

    Without the dummy check, an unknown email would be answered almost instantly and a known one only after a slow hash. The same message alone isn't enough; the timing must match too.
  2. 2. What does req.changeSessionId() at login protect against?

    The session keeps its data but gets a new ID. An ID that was planted or observed before login doesn't lead to the signed-in session.
  3. 3. Another site shows a signed-in user a hidden form that posts to /logout. The browser sends the session cookie along. What stops the request in stage 3?

    The attacker's page can make the browser send cookies, but it can't read the victim's pages, so it doesn't know the token. CsrfFilter answers 403 before the servlet runs.
  4. 4. What does LoginServlet.safeTarget("//evil.example/phish") return, and why?

    Browsers read //host/path as a URL on another host with the current scheme. Only local paths are allowed, so the method falls back to /account.
  5. 5. Why does a successful registration answer with a 302 redirect instead of rendering a "welcome" page directly?

    If the POST response were the page itself, Reload would ask to resubmit the form and could create a second request. The redirect makes the final page a plain GET.

Summary

  • Build the user layer first: a normalized, unique email, a salted slow password hash with its parameters stored alongside, and a service that returns one generic message for every login failure, with a dummy hash to equalize timing.
  • Let the database's UNIQUE constraint detect duplicates (SQLState 23505) instead of checking with a SELECT first, and count failed logins with one atomic UPDATE.
  • Servlets are controllers: read parameters, call the service, then forward to a JSP under WEB-INF or redirect (Post/Redirect/Get). Prefix redirects with the context path.
  • Escape every user value with <c:out> or fn:escapeXml; never write raw EL from user input into HTML.
  • At login, call changeSessionId(), store a small Serializable user record, and rotate the CSRF token. At logout, invalidate() the session and expire the cookie, and accept logout only by POST.
  • Put cross-cutting rules in filters (authentication, CSRF), declare their order in web.xml, and redirect only to local paths.
  • Test the whole flow end to end with real HTTP requests, one fresh database and server per test.

Next: Project: Employee Management with Spring Data JPA builds a REST back end with entities, repositories, paging, validation and DTOs.