To implement CSRF token creation and validation in a Struts framework application using Java, you can follow these steps:

Vishvjeet_singh_rathore
2 min readDec 28, 2023

--

  1. Generate CSRF Token in Action Class:

In your Struts action class, generate a CSRF token and store it in the session. Here’s an example:

import org.apache.struts.action.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

public class YourAction extends Action {

public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// Generate CSRF token
String csrfToken = UUID.randomUUID().toString();

// Store the token in the session
HttpSession session = request.getSession();
session.setAttribute("csrfToken", csrfToken);

// Other action logic...
// Return appropriate ActionForward
}
}

2. Include CSRF Token in Forms:

In your JSP pages where forms are rendered, include the CSRF token as a hidden input field within the form:

<form action="yourAction.do" method="post">
<!-- Other form fields -->
<input type="hidden" name="csrfToken" value="<%= session.getAttribute("csrfToken") %>">
<input type="submit" value="Submit">
</form>

3. Validate CSRF Token in Action Class:

When processing the form submission in your action class, retrieve the CSRF token from the request and validate it against the token stored in the session:

public class YourAction extends Action {

public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// Retrieve CSRF token from request
String requestCsrfToken = request.getParameter("csrfToken");

// Retrieve CSRF token from session
HttpSession session = request.getSession();
String sessionCsrfToken = (String) session.getAttribute("csrfToken");

// Check if CSRF tokens match
if (sessionCsrfToken != null && sessionCsrfToken.equals(requestCsrfToken)) {
// Tokens match, proceed with action logic
// ...
} else {
// Tokens don't match, handle the invalid CSRF token
// Redirect, display error, or take appropriate action
}

// Other action logic...
// Return appropriate ActionForward
}
}

By implementing these steps, you create a CSRF token, store it in the session, include it in your forms, and validate it in your action class to ensure that the submitted token matches the one stored in the session, thereby helping protect against CSRF attacks in your Struts framework application.

--

--