Can't create CSRF token with Spring Security

前端 未结 6 1316
清酒与你
清酒与你 2020-12-29 10:26

I am using Spring Security 3.2.3 in my Spring MVC application and getting some unexpected behavior.

According to the documentation here, it should be possible to us

6条回答
  •  有刺的猬
    2020-12-29 11:04

    I finally solved this problem, but it basically required rewriting Spring Security. Here it is in all its glory.

    First, I followed the suggestions in Eyal Lupu's great blog post here, but I had to tweak it to my situation because of my AJAX requirement.

    As for the Thymeleaf situation, the key tidbit is hidden away in the archives of the Thymeleaf forums - Infamous Issue 7.

    https://github.com/thymeleaf/thymeleaf-spring/issues/7#issuecomment-27643488

    The last comment by the creator of Thymeleaf himself says that:

    th:action ... detects when this attribute is being applied on a tag --which should be the only place, anyway--, and in such case calls RequestDataValueProcessor.getExtraHiddenFields(... ) and adds the returned hidden fields just before the closing tag.

    That was the key phrase I needed to get the token to work. Unfortunately it's completely not obvious why th:action would also kick off getExtraHiddenFields, but at any rate it does, and that's what matters.

    So for anyone struggling with Thymeleaf + Spring Security CSRF + AJAX POST, here are my steps (this is paring it down quite a bit but these are the high-level concepts to solve it):

    1. Implement the Spring interface RequestDataValueProcessor and register it in Spring Security's XML config so you can override the method getExtraHiddenFields, which allows you to insert a hidden input field into the HTML (with the token of course). The token itself is generated with a Java.Util UUID.

    2. With JQuery, read the value from that hidden field and set the Request Header's "X-CSRF-Token" attribute so that it gets sent over HTTP. It's not possible to simply leave the token in the hidden input field because we are not doing a form Submit, instead we use AJAX POST to call methods on the server side.

    3. Extend Spring's HandlerInterceptorAdapter and register it as an interceptor so that every time a POST method is done, the "preHandle" method on the server side is called so it can compare the request token (extracted from the HTTP header in the previous step) to the session's token (should be the same!). After it does this check, it can either allow the request to go through or return an error.

提交回复
热议问题