I have been learning Spring Security (and front end development) by going through several tutorials. However, I am getting very confused by the CSRF tokens, and I am clearly doing something wrong.
My Spring Security is configured using java, and when I disable CSRF (using the next snippet) then the form submits without a problem.
http.csrf().disable();
My understanding from here is that the steps I need to complete are:
1) Use proper verbs
2) Enable csrf protection
3) include _csrf as hidden fields in form.
All of these steps sound simple, but do not seem to be working for me, and I get the error:
HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
when I try to submit my registration form.
I did a little more checking, and I included the '_csrf' field as a visible field on the form as an interim step. I had assumed that this was not populated, but the token is clearly visible just prior to me posting the form, so the problem seems to be occurring when the data is posted, not when the data is generated.
The whole form syntax is shown below:
<form method="POST" th:object="${individualRegistrationInfo}">
<table>
<tr>
<td>Name:</td>
<td><input type="text" th:field="*{name}" /></td>
<td th:if="${#fields.hasErrors('name')}"><p th:errors="*{name}">Incorrect Name</p></td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" th:field="*{username}" /></td>
<td th:if="${#fields.hasErrors('username')}"><p th:errors="*{username}">Incorrect Username</p></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" th:field="*{password}" /></td>
<td th:if="${#fields.hasErrors('password')}"><p th:errors="*{password}">Incorrect Password</p></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="email" th:field="*{email}" /></td>
<td th:if="${#fields.hasErrors('email')}"><p th:errors="*{email}">Incorrect Email</p></td>
</tr>
<tr>
<td>Confirm Email:</td>
<td><input type="email" th:field="*{confirmEmail}" /></td>
<td th:if="${#fields.hasErrors('confirmEmail')}"><p th:errors="*{confirmEmail}">Incorrect Email Confirmation</p></td>
</tr>
<tr>
<td>Region:</td>
<td><select th:field="*{regionName}">
<option value="NONE">----Select----</option>
<option th:each="region : ${regions}" th:value="${region}" th:text="${region}">RegionTemplate</option>
</select></td>
<td th:if="${#fields.hasErrors('regionName')}"><p th:errors="*{regionName}">Region Name</p></td>
</tr>
<tr><td>
<span th:text= "${_csrf.parameterName}">CSRF Parm Name</span></td>
<td> <span th:text= "${_csrf.token}">CSRF Token value</span> </td></tr>
<tr>
<td colspan="3">
<input type="submit" value="Register" />
</td>
</tr>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</table>
</form>
There is one item that the previous article mentions, specifically: "One issue is that the expected CSRF token is stored in the HttpSession, so as soon as the HttpSession expires your configured AccessDeniedHandler will receive a InvalidCsrfTokenException. If you are using the default AccessDeniedHandler, the browser will get an HTTP 403 and display a poor error message."
I am not controlling the HttpSession at all, so I am not sure what the session timeout is set to (or how to override it.) However, since I am rebuilding the app and then testing directly afterwards, a session timeout seems unlikely.
I am using the following gradle dependencies:
compile group: 'org.springframework', name: 'spring-webmvc', version:'4.0.5.RELEASE'
compile group: 'org.springframework', name: 'spring-context-support', version:'4.0.5.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version:'1.1.4.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf', version:'1.1.4.RELEASE'
compile group: 'org.springframework.boot', name: 'spring-boot-starter-security', version:'1.1.4.RELEASE'
testCompile group: 'org.springframework.security', name:'spring-security-test', version:'4.0.0.M1'
So, when I do a final check through the three suggested steps:
1) Use proper verbs (POST is clearly visible on the form code snippet)
2) Enable csrf protection (http.csrf().disable(); is commented out and _CSRF shows in form)
3) include _csrf as hidden fields in form. (clearly visible on the form code snippet)
And thus I arrive at
4) I am missing something !
Can anyone suggest what I may be missing ?
Thank you for taking the time to read this.
Updated 29th July Noon
There is another guide which includes additional information regarding CSRF protection.
In particular, there is an AccessDeniedHandler which could be used.
I have now implemented this, and included a few additional logging details in this routine. What I am currently observing is that the _csrf token which is displayed on the page before submission is also being reported within the AccessDeniedHandler.
The handler is implemented as follows:
static class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
throws IOException, ServletException {
logger.warn("Arrived in custom access denied handler.");
HttpSession session = request.getSession();
System.out.println("Session is " +session );
System.out.println("Session id = " + session.getId());
System.out.println("Session max interval="+session.getMaxInactiveInterval());
System.out.println("Session last used="+session.getLastAccessedTime());
System.out.println("Time now="+new Date().getTime());
System.out.println();
System.out.println("csrf:");
Object csrf = request.getAttribute("_csrf");
if (csrf==null) {
System.out.println("csrf is null");
} else {
System.out.println(csrf.toString());
if (csrf instanceof DefaultCsrfToken) {
DefaultCsrfToken token = (DefaultCsrfToken) csrf;
System.out.println("Parm name " + token.getParameterName());
System.out.println("Token " + token.getToken());
}
}
System.out.println();
System.out.println("Request:");
System.out.println(request.toString());
System.out.println();
System.out.println("Response:");
System.out.println(response.toString());
System.out.println();
System.out.println("Exception:");
System.out.println(accessDeniedException.toString());
}
}
The output of this additional logging is:
Session is org.apache.catalina.session.StandardSessionFacade@579ebbb8
Session id = 7CC03DAFF6BC34E28F5E91974C7E4BA5
Session max interval=1800
Session last used=1406630832436
Time now=1406630878254
csrf:
org.springframework.security.web.csrf.DefaultCsrfToken@763659f8
Parm name _csrf
Token 1e9cb3cf-c111-4b05-aace-4f8480b7d67b
Request:
org.springframework.security.web.context.HttpSessionSecurityContextRepository$Servlet3SaveToSessionRequestWrapper@6a4ce569
Response:
org.springframework.security.web.context.HttpSessionSecurityContextRepository$SaveToSessionResponseWrapper@5e698704
Exception:
org.springframework.security.web.csrf.InvalidCsrfTokenException: Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
In this particular case, the token of 1e9cb3cf-c111-4b05-aace-4f8480b7d67b was embedded in the form.
The error is stating that CSRF token 'null' was found, but the printed lines show that the '_csrf' value is present in the request attributes.
Update 30th July I have replicated this issue into a smaller example project which is now available on GitHub: https://github.com/Mark-Allen/csrf-example.git
In its initial state, the application accepts a name, and then redisplays that name. When line 52 of SecurityWebConfiguration is commented out (see below for code which needs to be commented) Then the application fails.
http.csrf().disable();
Following @Bart's suggestion, I have included several debug statements to show the Session Id in place at key stages.
Hopefully this may enable someone to understand what I am doing wrong.