Home >Java >javaTutorial >How java framework prevents CSRF attacks
The Java framework protects against CSRF attacks through the following mechanisms: Token Validation: Generates and validates CSRF tokens to ensure the request comes from the expected source. Same-Origin policy: The browser only sends requests to its original origin to prevent cross-site attacks. Custom token storage: Allows storing CSRF tokens in cookies, headers, or sessions.
What is a CSRF attack?
A cross-site request forgery (CSRF) attack is a type of cyber attack in which an attacker tricks a victim into performing actions on a website without the victim's knowledge. The attacker used the victim's session cookie to impersonate their identity.
How does the Java framework prevent CSRF attacks?
Java frameworks such as Spring MVC and JSF provide multiple mechanisms to prevent CSRF attacks:
Token Validation
@CsrfToken
annotation. <inputsecret></inputsecret>
tag. Same-Origin policy
CsrfConfigurer
configuration to specify URLs that require CSRF protection. csrfTokenValidator
to validate CSRF tokens and block cross-origin requests. Custom token storage
CsrfFilter
and CsrfTokenRepository
. Practical case: Spring MVC
1. Install dependencies:
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.5.7</version> </dependency>
2. Configure Spring Security:
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .and() // 其他安全配置 ; } }
3. Generate token on controller method:
@RequestMapping("/transferMoney") @PostMapping public String transferMoney(@RequestParam int amount, @CsrfToken String csrfToken) { // 验证令牌 csrfTokenManager.verifyToken(csrfToken); // 执行转账操作 }
4. Add token in HTML page :
<form action="/transferMoney" method="post"> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> <input type="text" name="amount" /> <input type="submit" value="Submit" /> </form>
The above is the detailed content of How java framework prevents CSRF attacks. For more information, please follow other related articles on the PHP Chinese website!