Understanding Cross‑Site Request Forgery (CSRF) and Its Prevention Techniques
This article explains what CSRF attacks are, how they exploit authenticated browsers through forged requests, outlines the three essential conditions for a successful attack, and presents practical defense measures such as token validation, cookie handling, secondary authentication, and code examples in Java and JSP.
Cross‑Site Request Forgery (CSRF) is an attack where an adversary tricks a trusted, logged‑in user into sending unintended requests to a target server, leveraging the browser’s automatic inclusion of authentication cookies.
The attacker typically lures the victim to click a malicious link or load a malicious page, causing the browser to issue a request that the server mistakenly treats as legitimate because it cannot distinguish whether the request was voluntarily initiated by the user.
Three key conditions must be met for a CSRF attack: (1) there is a relevant operation in the application that the attacker can induce (e.g., changing a password or modifying permissions); (2) the application relies solely on cookie‑based session handling without additional verification; and (3) the request does not contain unpredictable parameters that the attacker cannot guess.
Primary causes include persistent cookies that remain valid after the user closes the browser, while secondary causes involve insufficient validation of request legitimacy.
An example of a malicious request is an <img src="https://www.renzhikeji.com/index.php?action=delete&id=123" /> tag, which can trigger a delete operation on the target site without the user’s awareness.
Common defense strategies are:
Validating the HTTP Referer header (often unreliable due to browser settings and privacy concerns).
Embedding a CSRF token in forms and verifying it on the server side. The token is a random value not stored in cookies, making it impossible for the attacker to guess.
Example Java utility for generating a random token:
package com.renzhikeji.demo;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
/**
* @author 认知科技技术团队
* 微信公众号:认知科技技术团队
*/
public final class CSRFTools {
public static String getToken() throws NoSuchAlgorithmException {
// 随机数生成
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
byte[] data = new byte[16];
secureRandom.nextBytes(data);
// 转换为 Base64 字符串返回
return Base64.getEncoder().encodeToString(data);
}
}JSP snippet that generates the token, stores it in a cookie, and includes it as a hidden form field:
<%
// 随机生成 CSRF token
String csrfToken = CSRFTools.getToken();
// 把 CSRF token 存在 cookie 中
javax.servlet.http.Cookie cookie = new javax.servlet.http.Cookie("csrf", csrfToken);
response.addCookie(cookie);
%>
<form action="/action" method="POST">
<input type="hidden" name="csrfToken" value="<%= csrfToken %>"/>
</form>During form submission, the server validates the token; frameworks like Spring Security provide built‑in CSRF protection (see https://docs.spring.io/spring-security/reference/features/exploits/csrf.html ).
Additional recommendations include clearing authentication cookies when the user closes the page, adding secondary authentication for sensitive actions, and employing CAPTCHAs.
References:
https://docs.spring.io/spring-security/reference/features/exploits/csrf.html
https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.md
https://knowledge-base.secureflag.com/vulnerabilities/cross_site_request_forgery/cross_site_request_forgery_java.html
https://www.freebuf.com/articles/web/341591.html
https://portswigger.net/web-security/csrf
https://baike.baidu.com/item/跨站请求伪造/13777878
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.