Spring Security 4 + CSRF (adding a cross-site request forgery protection project to Spring) Hello!
A modern web application is considered vulnerable if there is no protection against a
cross-site request forgery (CSRF) .
It is enabled by default in Spring Security 4.x, so when you
migrate from Spring Security 3.x to 4.x, you must either disable it.
< http > ... < csrf disabled = "true" /> </ http >
or, more correctly and more credibly, add to the project.
Actually, I did it in a 10-minute video:
VIDEO Below are the main points of CSRF implementation in the project: Use correct HTTP requests: by default CSRF protection is absent for GET, HEAD, TRACE, OPTIONS requests . This means, in particular, that for logout, if we don’t want a malicious site to log out a user who is authorized in our application, a POST request is required. In all forms where there is submit, add the hidden field name = _csrf with the value csrfToken. The easiest way to do this is through the Spring's form tag library , which, apart from binding and validation, with csrf enabled, will substitute the required hidden field into the form. < %@taglib prefix = "form" uri = "http://www.springframework.org/tags/form" %> ... < form:form method = "post" ... > ... </ form:form >
For ajax requests, the csrf token is added to the header. And you can do it immediately for all ajax requests. < sec:csrfMetaTags />
var token = $("meta[name='_csrf']" ).attr("content" ); var header = $("meta[name='_csrf_header']" ).attr("content" ); $(document ).ajaxSend(function ( e, xhr, options ) { xhr.setRequestHeader(header, token); });
Finally, for stateless REST requests, the easiest method of protection is: deny any non-JSON POST / PUT / DELETE @RestController @RequestMapping (value = AdminRestController.REST_URL, consumes = MediaType.APPLICATION_JSON_VALUE)
And finally, a few links to the topic: Thank you for your attention and, I hope, you already wanted to incorporate protection against CSRF into your project.
')
Source: https://habr.com/ru/post/264641/All Articles