Logo

dev-resources.site

for different kinds of informations.

Spring Security: CSRF protection

Published at
1/1/2025
Categories
spring
springsecurity
Author
saladlam
Categories
2 categories in total
spring
open
springsecurity
open
Author
8 person written this
saladlam
open
Spring Security: CSRF protection

Code is extracted from my notice board example application, which uses Spring Security 5.6.7

CsrfFilter filter

CSRF protection is on by default when configuring HttpSecurity. A CsrfFilter is created and has the following function.

When the request method is not "GET", "HEAD", "TRACE" or "OPTIONS". To check if the provided CSRF matches record in the token registry. If not matched, a 403 forbidden response will be returned.

Otherwise, a SaveOnAccessCsrfToken is generated and saved as a HttpServletRequest attribute with name org.springframework.security.web.csrf.CsrfToken and _csrf. This token will not persist unless it is accessed by a template engine. When persistence it is done by HttpSessionCsrfTokenRepository instance and the token will be saved as a HttpSession attribute with name org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN.

Token access by thymeleaf engine

When rendering http form tag, such as

<form method="post" th:action="@{/loginHandler}" class="ui large form">
Enter fullscreen mode Exit fullscreen mode

a hidden input tag will append afterward to provide CSRF token. In other word

<form method="post" action="/loginHandler" class="ui large form"><input type="hidden" name="_csrf" value="3c2ffa6d-ab75-41f3-ba10-7c423bf56071"/>
Enter fullscreen mode Exit fullscreen mode

This is done by SpringActionTagProcessor. Then following method will be called to access CSRF token.

org.thymeleaf.spring5.requestdata.RequestDataValueProcessorUtils#getExtraHiddenFields
org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestDataValueProcessor#getExtraHiddenFields
org.springframework.security.web.servlet.support.csrf.CsrfRequestDataValueProcessor#getExtraHiddenFields
Enter fullscreen mode Exit fullscreen mode
@Override
public Map<String, String> getExtraHiddenFields(HttpServletRequest request) {
    if (Boolean.TRUE.equals(request.getAttribute(this.DISABLE_CSRF_TOKEN_ATTR))) {
        request.removeAttribute(this.DISABLE_CSRF_TOKEN_ATTR);
        return Collections.emptyMap();
    }
    CsrfToken token = (CsrfToken) request.getAttribute(CsrfToken.class.getName());
    if (token == null) {
        return Collections.emptyMap();
    }
    Map<String, String> hiddenFields = new HashMap<>(1);
    hiddenFields.put(token.getParameterName(), token.getToken());
    return hiddenFields;
}
Enter fullscreen mode Exit fullscreen mode

Reference

  1. Cross Site Request Forgery (CSRF)
spring Article's
30 articles in total
Favicon
Launched a Web version of my Project using Java Spring Framework, Spring Boot Web
Favicon
Developing a project using Java Spring Framework, JSON, JPA and PostgreSQL
Favicon
Волшебные скоупы: Как Spring организует работу бинов
Favicon
Quando usar ResponseEntity?
Favicon
What is load balancing and how to do it on client side
Favicon
Capturing and Testing Logs in Java with SLF4J and Logback: A Simple Guide
Favicon
Can you find the Output of this Java Code
Favicon
Ways to Speed Up Spring Boot Application Startup Time
Favicon
Apache wicket with spring boot example application: notice board
Favicon
Handling the "Forwarded" Header in Spring Boot Applications
Favicon
About UriComponentsBuilder and UriComponents
Favicon
Spring Boot: About @SpringBootApplication
Favicon
Spring Security: CSRF protection
Favicon
ISBN Stacks — A look at a possible Spring Application implementation without annotations
Favicon
spring profiles dev production
Favicon
Learn Spring Data JPA, Part - 1
Favicon
Methods for Efficient Large File Processing in Spring Boot
Favicon
Hexagonal Architecture — A Favorite Lyrics Spring Boot — Java Example
Favicon
Validation in Spring REST Framework (SRF)
Favicon
spring
Favicon
Spring Security: Redirect to login page if access pages which is for authorized user only
Favicon
Lambda vs. Named Functions: Choosing the Right Tool for the Job
Favicon
Techniques for Mastering Spring Interceptors: Detailed Guide with Examples
Favicon
Techniques for Using @NoRepositoryBean in Spring Data JPA: A Comprehensive Guide
Favicon
Understanding the Spring Framework: A Developer’s Journey to Clean Code 🚀
Favicon
@PreConstruct and @PostConstruct annotation Spring Boot Example
Favicon
Java’s Functional Programming: the OOP influence
Favicon
🧪 Тестирование с TestRestTemplate и MockMvc: миссия "Котики против багов" 🐞
Favicon
spring boot
Favicon
Reasons to Use WireMock for Testing REST APIs in Spring Boot Applications

Featured ones: