Spring Boot (vii): How spring Security enables and disables CSRF

Source: Internet
Author: User

Starting with spring security 4, the default enable CSRF mechanism, which is not a big deal, but with spring boot together, then the implementation is more troublesome, especially after the use of the split-end of the development architecture, the configuration of the CSRF mechanism is more difficult, Almost all online solutions are unable to solve the problem of how to get CSRF coding, first by landing the wrong town floor with the form:

There was a unexpected error (Type=forbidden, status=403).
Invalid CSRF Token ' null ' is found on the request parameter ' _CSRF ' or header ' X-xsrf-token '.
1. Disabling the CSRF mechanism

Disabling the CSRF mechanism is perfectly compatible with the old Spring security version, but in the implementation of Spring boot, if you continue with the old version of the configuration, most people will encounter the following error:

An authentication object is not found in the SecurityContext

This is because spring MVC automatically proxies the problems caused by all requests, so the workaround is simple, convert multiple "http" configurations to an "HTTP" configuration, and prohibit the use of "security=" None ", the following is the wrong way to do this:

<sec:http pattern= "/login.html*" security= "None"/>

The correct wording is as follows:

<sec:http use-expressions= "false" >
    <sec:intercept-url pattern= "/login.html*" access= "IS_" authenticated_anonymously "/>
</sec:http>

The difference between the two is that the second will pass through all the safety filters, such as "Securitycontextpersistencefilter", "Logoutfilter", "Csrffilter" and so on, while the first is not. Obviously, the first kind of performance is much higher for static resources, but if your static delegate spring boot is managed, you can only use the second configuration.

Disabling the CSRF mechanism is simple, just set it to "disabled", as follows:

<SEC:CSRF disabled= "true"/>

But in the actual combat, I found that many people in the landing process, will be prompted the following error:

There was a unexpected error (Type=method not allowed, status=405).
Request method ' POST ' is not supported

After debugging, it is found that the problem is not csrf, but the "form-login" configuration error, as follows:

<sec:form-login login-page= "/login.html"
                password-parameter= "password" username-parameter= "username"
                default-target-url= "/admin.html"
                <!--The problem is this configuration, forward-->
                Authentication-success-forward-url= "/admin.html"        
                login-processing-url= "/j_security_check"/>

The problem is in the annotation line of code, "Authentication-success-forward-url" means that the landing request will be forwarded to the new address, this will be a novelty address must support the "POST", or there will be 405 errors, so the solution is also very simple, Either log off the configuration or the forwarded address must support a "POST" request. 2. Enabling the CSRF mechanism

The CSRF mechanism must be enabled to do the following:
1. First name the CSRF Cookie;
2. Obtain csrf Token from cookies;
3. The CSRF Token must be added when submitting the form;
4. The cancellation system must be in the post way (necessarily add csrf Token);
The above four things to do less, will prompt the following error:

There was a unexpected error (Type=forbidden, status=403).
Invalid CSRF Token ' null ' is found on the request parameter ' _CSRF ' or header ' X-xsrf-token '.
2.1 Name CSRF cookies

The named CSRF cookie is used in conjunction with the following two configurations, as follows:

<SEC:CSRF token-repository-ref= "Tokenrepository"/> <bean id= "tokenrepository"
      Org.springframework.security.web.csrf.CookieCsrfTokenRepository ">
    <property name=" Cookiehttponly " Value= "false"/>
    <property name= "CookieName" value= "X-xsrf-token"/> "<property name=
    " HeaderName "Value=" X-xsrf-token "/>
</bean>
2.2 Get CSRF Token

In a back-and-forth structure, the new CSRF Token is returned each time the view is refreshed, but in our first step, the CSRF Token is placed in a cookie, so it is only necessary to remove it from the cookie, as follows:

  converts a cookie to a JS Object
function initcookies () {
    var cookie = document.cookie,
        items = Cookie.split (";") ,
        keys = {};
    Items.foreach (function (item) {
        var kv = item.split (' = ');
        Keys[$.trim (kv[0])] = $.trim (kv[1]);
    return keys;
}  get csrf Token
var _csrf = initcookies () [' X-xsrf-token '];
2.3 Add CSRF Token to Ajax requests

With the second step, it's much easier to add CSRF token now, as follows:

  Submit data
$.post (URL, {
    userid:code,
    _csrf:cookies[' X-xsrf-token ']
}, function (datas) {
    //  TODO something
})
2.4 Logout system changed to post mode

Refer to the above operation can be, slightly. Conclusions

Disabling CSRF is easy, hard to enable CSRF, and very different, please pay close attention to their impact on the security filter.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.