Include the CSRF Token in Spring Security | Code Factory
Form Submissions
_csrf
request attribute to obtain the current CsrfToken
. An example of doing this with a JSP is shown below:<c:url var="logoutUrl" value="/logout"/>
<form action="${logoutUrl}" method="post">
<input type="submit" value="Log out" />
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>
</form>
*Note : If you are using Spring MVC
<form:form>
tag or Thymeleaf 2.1+ and are using @EnableWebSecurity
, the CsrfToken
is automatically included for you (using the CsrfRequestDataValueProcessor
).Ajax and JSON Requests
If you are using JSON, then it is not possible to submit the CSRF token within an HTTP parameter. Instead you can submit the token within a HTTP header. A typical pattern would be to include the CSRF token within your meta tags. An example with a JSP is shown below:
<html>
<head>
<meta name="_csrf" content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>
</head>
You can then include the token within all your Ajax requests. If you were using jQuery, this could be done with the following:
$(function () {
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);
});
});
CookieCsrfTokenRepository
There can be cases where users will want to persist the
CsrfToken
in a cookie. By default the CookieCsrfTokenRepository
will write to a cookie named XSRF-TOKEN
and read it from a header named X-XSRF-TOKEN
or the HTTP parameter _csrf
.You can configure
CookieCsrfTokenRepository
in XML using the following:<http>
<!-- ... -->
<csrf token-repository-ref="tokenRepository"/>
</http>
<b:bean id="tokenRepository"
class="org.springframework.security.web.csrf.CookieCsrfTokenRepository"
p:cookieHttpOnly="false"/>
You can configure CookieCsrfTokenRepository
in Java Configuration using:
@EnableWebSecurity
public class WebSecurityConfig extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
}
Tags:
Cross Site Request Forgery (CSRF) - Spring
Guide to CSRF Protection in Spring Security
Spring Security CSRF Token
CSRF Token Implementation in Spring
How to Implement CSRF Token in java
Comments
Post a Comment