Spring

 How to enable and use CSRF in spring boot security?

Jeff Cheak's profile image
Jeff Cheak posted Sep 05, 2018 07:58 PM

Apologies if this question is obvious. I have struggled with finding the right information. (while the internet is full of examples, my guess is that these are several years old...before spring boot started to enable CSRF tokens automatically...which is why you find many variations on how to use/implement)

 

The question: what do I have to do to enable CSRF protection using the latest spring boot version?

The follow up question: how do I use it?

 

I was reading the latest spring security document: https://docs.spring.io/spring-security/site/docs/current/reference/pdf/spring-security-reference.pdf starting on page 118

 

I thought that would be the best most current resource for information. More questions after reading it..

1) Is the _csrf request attribute automatically populated?

2) If spring is automatically enabling CSRF....can I just put a tag: <sec:csrfInput /> in each html file I have?

Thank you greatly in advance for reading and filling my large knowledge gap on this one.

Daniel Mikusa's profile image
Daniel Mikusa

I don't believe there's much you need to do. Boot doesn't do anything specific, as far as I saw in the docs [1], it's just relying on Spring Security. The info here [2] should be most relevant, assuming you're no Boot 2.0. Section 19.4 walks through what you need to do, which isn't all that much.

 

1.) Don't overload GET. Make proper use of PUT/POST/DELETE and other HTTP verbs.

2.) You don't need to enable CSRF protection as it's enabled by default. You can verify by trying to submit one of your forms. You should see a 403 "access denied" response. This is because of the CSRF protection.

3.) Modify your forms to include the CSRF token. When submitted with the token, you'll get past the 403. The csrfInput tag you mentioned should do exactly that.

 

If you're having issues check section 19.5 "Caveats" to see if you're running into any of those issues.

 

Hope that helps!

 

[1] - https://docs.spring.io/spring-boot/docs/2.0.4.RELEASE/reference/htmlsingle/#boot-features-security-csrf

[2] - https://docs.spring.io/spring-security/site/docs/5.0.7.RELEASE/reference/htmlsingle/#csrf