SOP
SOP

Reputation: 801

CSRF token is required in Spring 4.x

I am trying to send hidden form element from .js file , so it goes to the controller and in between it throws exception of CSRF token is invalid.

$(document.body).append(form);
            $(form).attr("action", "/controller_path");
            $(form).attr("method", "POST");
            var input = $("<input>").attr("type", "hidden").attr("name","payment_prim_customer").val(payment_prim_customer);

            $(form).append($(input));
            $(form).submit();

please suggest how to handle this?

CSRF Token is added in my .JSP file

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

Upvotes: 1

Views: 240

Answers (2)

Monzurul Shimul
Monzurul Shimul

Reputation: 8386

Include the CSRF token within your meta tags.

<html>
<head>
    <meta name="_csrf" content="${_csrf.token}"/>
    <!-- default header name is X-CSRF-TOKEN -->
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
    <!-- ... -->
</head>

And finally try with this:

$(document.body).append(form);
$(form).attr("action", "/controller_path");
$(form).attr("method", "POST");
var input = $("<input>").attr("type", "hidden").attr("name","payment_prim_customer").val(payment_prim_customer);
$(form).append($(input));

var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var csrf_input = $("<input>").attr("type", "hidden").attr("name",'_csrf').val(token);
$(form).append($(csrf_input ));

$(form).submit();

Upvotes: 1

zakaria amine
zakaria amine

Reputation: 3682

Because your using it from Js, You probably need to use a csrfTokenRepository and then retrieve the value from the cookies. You can add something like that to your config:

.and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());

And then retrieve the token from a cookie named X-XSRF-TOKEN

Upvotes: 0

Related Questions