Reason for vulnerability: The code performs a sensitive action without validating a CSRF token, making it susceptible to CSRF attacks.
Fixed Code:
javascriptCopy code// Fetch CSRF token from meta tag
const token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
fetch('/update-profile', {
method: 'POST',
headers: {
'CSRF-Token': token,
'Content-Type': 'application/json'
},
body: JSON.stringify({ email: 'newemail@example.com' })
});
Reason for fix: Including a CSRF token in the request header ensures that the request is legitimate and not forged by an attacker.
Vulnerable Code
@Controller
public class TransferController {
@PostMapping("/transfer")
public String transferMoney(@RequestParam String to, @RequestParam BigDecimal amount) {
// Perform money transfer
return "redirect:/success";
}
}
Reason for Vulnerability:
This endpoint doesn't implement any CSRF protection, allowing attackers to trick users into making unintended transfers.
Fixed Code:
javaCopy@Controller
public class TransferController {
@PostMapping("/transfer")
public String transferMoney(@RequestParam String to, @RequestParam BigDecimal amount,
@RequestParam String _csrf, HttpSession session) {
if (!_csrf.equals(session.getAttribute("csrfToken"))) {
return "redirect:/error";
}
// Perform money transfer
return "redirect:/success";
}
@ModelAttribute
public void addCsrfToken(HttpSession session, Model model) {
String csrfToken = UUID.randomUUID().toString();
session.setAttribute("csrfToken", csrfToken);
model.addAttribute("csrfToken", csrfToken);
}
}
Reason for Fix:
The fixed code implements a custom CSRF token validation. A more robust solution would be to use Spring Security's built-in CSRF protection.