在Session中设置CSRF Token失败问题求助
Got it, let's figure out why your session.setAttribute isn't working and fix this. The main issue here is that you're hardcoding a static string into the session instead of using the actual randomly generated CSRF token value you need. Here's how to sort this out:
What's Wrong With Your Current Code?
Right now, this line:
<%session.setAttribute("csrftoken","8f16a344767af48bd99493a8c7f1f6a0");%>
is storing a fixed, hardcoded string in the session—but your actual CSRF token is a dynamic, randomly generated value (either the csrfPreventionSalt variable or the name attribute of your hidden input). Since you're not binding that dynamic value, the session doesn't hold the real token, which is why it's not behaving as expected.
Fixed Code to Store the Dynamic Token
Assuming csrfPreventionSalt is the variable that holds your randomly generated CSRF token, update your code to store that dynamic value instead of the hardcoded string:
<input type="hidden" name="${fn:escapeXml(csrfPreventionSalt)}" value="<c:out value='${fn:escapeXml(csrfPreventionSalt)}'/>"/> <% // Grab the dynamic token from the page context (or request scope if that's where it's stored) String actualCsrfToken = (String) pageContext.getAttribute("csrfPreventionSalt"); session.setAttribute("csrftoken", actualCsrfToken); %>
If the random value you're targeting is actually the name attribute of the hidden input (the 8f16a344767af48bd99493a8c7f1f6a0 string), you can refactor it to use a variable for clarity:
<% String csrfTokenName = (String) pageContext.getAttribute("csrfPreventionSalt"); // Use the variable that generates this random name session.setAttribute("csrftoken", csrfTokenName); %> <input type="hidden" name="${fn:escapeXml(csrfTokenName)}" value="<c:out value='${fn:escapeXml(csrfPreventionSalt)}'/>"/>
Accessing the Token on the Server
Once the token is stored in the session, you can retrieve it in your server-side logic (like a servlet) without needing to pull it from request parameters at all:
String csrfToken = (String) request.getSession().getAttribute("csrftoken"); // Use this token for CSRF validation
Quick Checks to Ensure It Works
- Make sure
csrfPreventionSalt(or whatever variable holds your random token) is properly available in the JSP's scope—whether that'spageContext,request, orsession—before this code runs. - Confirm you're operating within the same user session when retrieving the token; if the session expires or switches, the stored value won't be accessible.
内容的提问来源于stack exchange,提问作者Aniket G

