What is CSRF?
CSRF (Cross-site request forgery), Chinese name: cross-site request forgery, also known as: one click attack/session riding, abbreviation: CSRF/XSRF.
What can CSRF do?
You can understand CSRF attacks like this: the attacker stole your identity and sent a malicious request in your name. Things CSRF can do include: sending emails, sending messages, stealing your account, and even purchasing goods, transferring money from virtual currency... Problems caused include: personal privacy leakage and property security.
Current status of CSRF vulnerability
CSRF attack method was proposed by foreign security personnel in 2000, but it was not until 2006 that it began to be paid attention to in China. In 2008, CSRF vulnerabilities were exposed in many large communities and interactive websites at home and abroad, such as: NYTimes.com (New York Times), Metafilter (a large BLOG website), YouTube and Baidu HI... Now, many sites on the Internet are still unprepared for this, so the security industry calls CSRF a "sleeping giant."
In a spring boot project, CSRF attacks need to be prevented, and only relevant filters in spring security can be introduced.
Add relevant dependencies in pom
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <!-- Security (used for CSRF protection only) --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> </dependency> </dependency> </dependencies>
Add CsrfFilter when the app starts
@SpringBootApplicationpublic class Application extends WebMvcConfigurerAdapter { @Bean public FilterRegistrationBean csrfFilter() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new CsrfFilter(new HttpSessionCsrfTokenRepository())); registration.addUrlPatterns("/*"); return registration; } public static void main(String[] args) { SpringApplication.run(Application.class, args); }}Add hidden field of CSRF in form
<input name="${(_csrf.parameterName)!}" value="${(_csrf.token)!}" type="hidden">Adding the header of CSRF in ajax
xhr.setRequestHeader("${_csrf.headerName}", "${_csrf.token}");github address is https://github.com/kabike/spring-boot-csrf
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.