Reputation: 8067
I am working on a web application built using Spring framework. I am getting Invalid CSRF Token
error. I see this behavior only in Chrome browser. Following are the steps followed:
Invalid CSRF Token 'd82dfa89-81b1-449e-9ef5-cdd32957e7f3' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
Spring security configuration:
http.
addFilter(headerAdminFilter).
authorizeRequests().
regexMatchers("/login.*").permitAll().
regexMatchers("/api.*").fullyAuthenticated().
regexMatchers("/jolokia.*").hasRole(ADMINISTRATOR).
regexMatchers("/appadmin.*").hasRole(ADMINISTRATOR).
regexMatchers(".*").fullyAuthenticated().
and().
formLogin().loginPage("/login").successHandler(new RedirectingAuthenticationSuccessHandler()).
and().
exceptionHandling().authenticationEntryPoint(new RestAwareAuthenticationEntryPoint("/login"));
HTML code for Logout button:
<a id="logout-button" ng-click="ac.logout()" href="/login">Log Out</a>
AngularJS code for logout function:
this.logout = function () {
$http.post("/logout");
}
Upvotes: 0
Views: 17962
Reputation: 16604
The following javascript snippet fixes stale CSRF token. The idea is to fetch a fresh token when the user tries to submit the login form and update the CSRF value in the form before the form is actually submitted.
$(document).ready(function() {
$("form[method=post]").submit(function(event) {
var form = this;
$.get("csrf-token", function(content) {
$(form).find("input[name=_csrf]").val(content);
form.submit();
});
event.preventDefault();
});
});
You need a /csrf-token
mapping on the server side that returns the current CSRF token.
Upvotes: 2