CSRF

Cross-Site Request Forgery (CSRF) (https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request.

The Open Web Application Security Project (OWASP) considers CSRF as one of the most common security risks for web applications. OWASP publishes a list (known as the OWASP Top 10) every year, highlighting the top 10 security risks plaguing web applications—it considers CSRF to be in fifth position.

In Spring Security, CSRF is enabled by default. If needs be (we have disabled this in many of our examples so that we are able to concentrate on the main concept that the examples are supposed to convey), we can disable it explicitly by adding the following code snippet in your Spring Security configuration:

http
.csrf().disable();

Even though CSRF is enabled by default, for it to function, each request needs to provide a CSRF token. If a CSRF token is not sent across to the server, the server will reject the request and throw an error. If you are using Java Server Page (JSP) as your view, just by including hidden input, as shown in the following code snippet, many things would happen auto-magically:

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />

If you are using an AJAX request to call a server, instead of hidden input, you can supply the CSRF token in the form of an HTTP header. You can declare the CSRF-related header as meta tags, as shown in the following code snippet:

<head>
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<!-- ... -->
</head>

After that, while calling the server, include these (_csrf and _csrf_header) as headers and you will be allowed to call the required endpoints.

If you would like to persist the CSRF token, Spring Security allows you to do this by tweaking the configuration as shown in the following code snippet:

http
.csrf()
.csrfTokenRepository(new CookieCsrfTokenRepository());

While doing this, the CSRF token is persisted as a cookie, which can be read by the server and validated (all done auto-magically).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.100.20