In this blog, I am going to explain how to implement Cross-Site Request Forgery protection in Spring.
No need to worry to enable CSRF in Spring. Spring Security comes with CSRF enabled. And if required we can disable it as well. Although disabling CSRF is a bad practice but Spring provides us the mechanism to disable it. We can disable CSRF protection by using following single line of code while configuring Security in Spring.
http.csrf().disable();
We are not here to disable CSRF protection but to configure it to work well and prevent CSRF attack. As I said, there is nothing to do to keep it enable, just configure spring security for login, logout, page permission by user roles etc. Once security configured, start your application with your favorite server. It will fail when you try to login at the very beginning of your application. And it is good as it indicates that CSRF protection has kicked in to prevent us to access the login functionality. It is expecting CSRF token along with the request. Adding the following line will allow you to access your application.
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
Do the same for your all forms that brings confidential information to the server.
Hope that would help you setup CSRF protection in your application.
Thanks. Happy Coding.
0 Comment(s)