How do I create a servlet filter to make secure cookies?

The CookieFilter class in this example is a servlet filter. Servlet filters in Java web applications are used to perform tasks such as request/response modification, authentication, logging, and more. In the context of managing cookies, a CookieFilter can be used to intercept requests and responses to handle cookie-related operations, such as setting secure attributes on cookies or checking cookie values for authentication purposes.

Here’s an example of how you can implement a CookieFilter class in Java:

package org.kodejava.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class CookieFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // Initialization code, if needed
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        // Check if a session exists
        HttpSession session = httpRequest.getSession(false);
        if (session != null) {
            // Example: Set secure attribute on session cookie
            sessionCookieSecure(httpRequest, httpResponse);
        }

        // Continue the request chain
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // Cleanup code, if needed
    }

    private void sessionCookieSecure(HttpServletRequest request, HttpServletResponse response) {
        // Assuming the session cookie name
        String cookieName = "JSESSIONID"; 
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(cookieName)) {
                    // Set the secure attribute on the session cookie
                    cookie.setSecure(true);
                    // Update the cookie in the response
                    response.addCookie(cookie); 
                    break;
                }
            }
        }
    }
}

In this example:

  • The CookieFilter class implements the Filter interface, which requires implementing methods like init, doFilter, and destroy.
  • Inside the doFilter method, it checks if a session exists for the incoming request.
  • If a session exists, it calls the sessionCookieSecure method to set the secure attribute on the session cookie.
  • The sessionCookieSecure method iterates through cookies in the request, finds the session cookie (e.g., JSESSIONID), and sets its secure attribute to true.

You can modify this filter implementation based on your specific cookie management requirements, such as setting secure attributes on specific cookies or performing additional cookie-related tasks.

How do I configure secure cookies using web.xml?

To configure secure cookies using web.xml, you typically need to set the secure attribute on your cookie definitions. This ensures that the cookie is only sent over HTTPS connections, enhancing security by protecting sensitive information from being transmitted over unencrypted channels. Here’s how you can do it:

1. Define Your Servlet Filter (Optional but Recommended):

If you don’t have a servlet filter for managing cookies, you can create one. This filter can intercept requests and responses to handle cookie-related operations.

<filter>
    <filter-name>CookieFilter</filter-name>
    <filter-class>org.kodejava.servlet.CookieFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CookieFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Replace org.kodejava.servlet.CookieFilter with the actual class that implements your cookie handling logic.

2. Configure Secure Cookie in web.xml:

Inside your web.xml, you can define cookie configurations using <session-config> and <cookie-config> elements.

<session-config>
   <cookie-config>
      <!-- Recommended to prevent client-side script access -->
      <http-only>true</http-only>
      <!-- Set all cookies to be secure -->
      <secure>true</secure>
    </cookie-config>
</session-config>
  • <secure>true</secure>: This line ensures that all cookies are marked as secure, meaning they will only be sent over HTTPS connections.
  • <http-only>true</http-only>: This line makes cookies accessible only through HTTP headers, preventing client-side scripts (like JavaScript) from accessing them. It adds another layer of security against certain types of attacks.

3. Deploy and Test:

After making these changes, deploy your web application and test it over HTTPS. Verify that cookies are being set with the secure flag by checking your browser’s developer tools (usually under the “Application” or “Storage” tab).

By following these steps, you can configure secure cookies in your Java web application using web.xml.

Notes: Setting the secure attribute in web.xml configures the default behavior for cookies created by the servlet container. However, for custom cookies that your application creates programmatically, you need to explicitly call setSecure(true) on the Cookie object to make them secure.

How do I delete a cookie in Servlet?

The Servlet API doesn’t provide a direct way to delete a cookie in a Servlet application. If you want to delete a cookie you have to create a cookie that have the same name with the cookie that you want to delete and set the value to an empty string. You also need to set the max age of the cookie to 0. And then add this cookie to the servlet’s response object.

Let’s see the code example below:

package org.kodejava.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "DeleteCookieServlet", urlPatterns = "/deleteCookie")
public class DeleteCookieServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //
        // To delete a cookie, we need to create a cookie that have the same
        // name with the cookie that we want to delete. We also need to set
        // the max age of the cookie to 0 and then add it to the Servlet's
        // response method.
        //
        Cookie cookie = new Cookie("username", "");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
    }
}

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

How do I set the maximum age of a cookie?

package org.kodejava.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "CookieExpirationServlet", urlPatterns = "/cookie-expiration")
public class CookieExpirationServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        if (username != null) {
            Cookie cookie = new Cookie("username", username);

            // Set the cookie age to 600 seconds (10 minutes). Setting the age
            // to 0 will delete the cookie while giving it a negative value will
            // not store the cookie, and it will be deleted when the browser is
            // closed.
            cookie.setMaxAge(600);
            response.addCookie(cookie);
        }
    }
}

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

How do I read cookie in Servlet?

package org.kodejava.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "ReadCookieServlet", urlPatterns = "/read-cookie")
public class ReadCookieExample extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();

        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            writer.println("Name: " + cookie.getName() + "; Value: " + cookie.getValue());
        }
    }
}

An example result of the servlet above is:

Name: username; Value: jduke 
Name: JSESSIONID; Value: AE819A3F74E3700838ADFC99485216DF

Maven dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central