P
P
parkito2016-10-05 04:19:20
Java
parkito, 2016-10-05 04:19:20

Why doesn't cross-site scripting protection work in spring security?

Hello. Help, please, to solve a problem. Set up spring security. Everything is working. Authorization goes well. But when I try to execute a request with ajax, I get

org.springframework.web.servlet.PageNotFound Request method 'POST' not supported at org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.handleHttpRequestMethodNotSupported(DefaultHandlerExceptionResolver.java:215)

Those. ajax does not fire up the servlet.
ajax
function popBox(num1, num2) {
   x = confirm('Are you sure? ');
   if (x == true) {
     var xhr = new XMLHttpRequest();
    xhr.open("POST", "userChangeTariff?tariffId=" + num1 + "&contractNumber=" + num2, false);
   xhr.send();
}

servlet
@RequestMapping(value = "/userChangeTariff", method = RequestMethod.POST)
    public String changeTariff(HttpServletRequest request, Locale locale, Model model,
                               @RequestParam(value = "tariffId") String tariffId,
                               @RequestParam(value = "contractNumber") String contractNumber) {
        int tariffID = Integer.parseInt(tariffId);
        Contract contract = contractService.getContractByNumber(contractNumber);
        Tariff tariff = tariffService.getEntityById(tariffID);
        contract.setTariff(tariff);
        contractService.updateEntity(contract);
        return "user/userTariffs";
    }

The most interesting thing is that when I turn off csrf ( ) everything starts working.
There is a token on the page
<input type="hidden" name="<c:out value="${_csrf.parameterName}"/>"
    value="<c:out value="${_csrf.token}"/>"/>

Why is csrf cutting off my servlet? How can this be fixed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-10-05
@parkito

That's right, you don't pass the csrf-token in the ajax request, so it looks like a malicious one and is not processed. About it is in the documentation.

<html>
    <head>
        <meta name="_csrf" content="${_csrf.token}"/>
        <meta name="_csrf_header" content="${_csrf.headerName}"/>
        ...
    </head>
    ...
</html>

var csrfHeaderName = "X-CSRF-TOKEN";
var csrfTokenValue;

var metaTags = document.getElementsByTagName('meta'); 
for(var i = 0; i < metaTags.length; i++) {
    var metaTagName = metaTags[i].getAttribute("name");
    if(metaTagName === "_csrf_header")
        csrfHeaderName = metaTags[i].getAttribute("content");
    if(metaTagName === "_csrf")
        csrfTokenValue = metaTags[i].getAttribute("content");
}

...
var xhr = new XMLHttpRequest();
xhr.open("POST", "userChangeTariff?tariffId=" + num1 + "&contractNumber=" + num2, false);
xhr.setRequestHeader(csrfHeaderName, csrfTokenValue);
xhr.send();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question