Mithun
Mithun

Reputation: 8067

Invalid CSRF Token - error in chrome browser

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:

  1. Login to the application by providing userName and password
  2. Click on Logout button to logout. The user will be re-directed to the login page
  3. Then, in the login page again try to login. I am getting the below error

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

Answers (1)

holmis83
holmis83

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

Related Questions