thymeleaf csrf
时间: 2023-08-29 16:09:34 浏览: 54
Thymeleaf is a popular Java-based templating engine used for server-side rendering in web applications. It works well with Spring and Spring Boot frameworks. CSRF (Cross-Site Request Forgery) is a security vulnerability that allows attackers to perform unwanted actions on behalf of authenticated users. To prevent CSRF attacks in Thymeleaf, you can use Thymeleaf's built-in support for CSRF protection.
Thymeleaf provides a CSRF token mechanism that you can use to protect your forms. To include a CSRF token in your Thymeleaf forms, you can use the `th:action` and `th:object` attributes. Here's an example:
```html
<form th:action="@{/submit}" th:object="${form}" method="post">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
<!-- other form fields -->
<button type="submit">Submit</button>
</form>
```
In this example, `@{/submit}` is the form action URL, `${form}` is the form object, and `${_csrf.parameterName}` and `${_csrf.token}` are Thymeleaf expressions for the CSRF token name and value, respectively. The CSRF token is added as a hidden input field in the form.
On the server-side, you need to configure CSRF protection in your Spring Security configuration. You can enable CSRF protection by adding the `@EnableWebSecurity` annotation to your configuration class and configuring it to use Thymeleaf's CSRF support. Here's an example:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
}
```
In this example, `CookieCsrfTokenRepository.withHttpOnlyFalse()` is used as the CSRF token repository. This configuration allows the CSRF token to be stored in a cookie and sent as a request header.
By following these steps, you can integrate Thymeleaf's CSRF protection in your web application to prevent CSRF attacks.