CSRF / XSRF protection using Spring Security

The last few years there is an almost constant stream of news articles about some company leaking customer information one way or the other. While not all of these leaks are caused by badly protected websites themselves, a lot are caused by misconfigurations in the web/data servers, programmers still have a hard time integrating some basic protection against attacks.
I won't pretend to have knowledge of every aspect of a vigorous web attack against a website (I need to point you to Erik Hooijmeijer for this), I do know that some of the basic protections are easy to implement due to support by the underlying framework.
The same goes for a Spring MVC webapplication. With the Spring-Security framework it becomes easier to protect your (web)application. One of the threats is CSRF short for Cross Site Request Forgery. CSRF or XSRF uses an already established session with a trusted website to create a 'forged' request and execute an unwanted command to that website. This can be mitigated by requiring a unique token to be send with the request which has been generated and stored in the httpsession.
Spring has the capability to auto generate and validate the token and fields in the MVC forms. Enabling this feature is as simple as adding a library in your project, and adding a bit of configuration in your pom.xml:

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
Then add the following files to your projects pom file:
<SecurityWebApplicationInitializer.java>
  
/**
  * This WebApplicationInitializer register its security filters on the Application
  *
  * @Order(2)
  public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {}
  
  
/**
  * This WebApplicationInitializer register its security filters on the Application
  *
  * @Order(2)
  */
  public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {}
  
<SecurityConfig.java>
  
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
  * Because authentication is handled outside the application we don't have to authorize any requests

  */
  @Override
  @SuppressWarnings("PMD.SignatureDeclareThrowsException")
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/**").permitAll();
  }
}
  
Notice that in the above file we don't enable csrf protection explicitly as Spring enabled this by default.
You can only explicitly disable it by writing:
  
protected void configure(HttpSecurity http) throws Exception {
  http.authorizeRequests().antMatchers("/**").permitAll().and().csrf().disable();
}
  
Now in your JSP replace the default  <form> tag with the spring-form JSP tag library version and you get auto _csrf hidden input field injected into your forms.
There are 2 gotchas!
  1. When also configuring a CharacterEncodingFilter, to make sure you have UTF-8 support all the way through your webstack, you need to make sure that this filter is loaded before the filters that the SecurityWebApplicationInitializer adds to the mix. Because the CSRF filter reads the request parameters the character encoding is already set on the request causing the CharacterEncodingFilter to be pointless. So annotate your base WebApplicationInitializer with a @Order(1) and the SecurityWebApplicationInitializer with @Order(2). This way the CharacterEncodingFilter is loaded before the other filters.
    There is a second way. You can also override beforeSpringSecurityFilterChain and add the CharacterEncodingFilter in that method.
  2. The Security configuration stores the generated token in the HttpSession on the server (to verify against the returning token). So make sure that your loadbalancers are configured with a sticky-session configuration, otherwise the post to the server can be forwarded to the wrong webserver. As the user has no valid session on that server the validation of the CSRF token will fail.
Read more on Spring Security
And other possible attacks on your website: OWASP

19 comments:

  1. I am so satisfied with Guard America best 5 Home Security Companies. This is basically the thirdly security alarms firm we have experienced in past times 25 years and this infant really does all that you should continue to be safe. The customer services are exceptional for those who have concerns when installing.

    ReplyDelete
  2. it was a wonderful chance to visit this kind of site and I am happy to know. thank you so much for giving us a chance to have this opportunity.. security guards

    ReplyDelete
  3. Going to graduate school was a positive decision for me. I enjoyed the coursework, the presentations, the fellow students, and the professors. And since my company reimbursed 100% of the tuition, the only cost that I had to pay on my own was for books and supplies. Otherwise, I received a free master’s degree. All that I had to invest was my time. security company

    ReplyDelete
  4. Keep the balls rolling!! Nice posts you have given for us.
    home security systems

    ReplyDelete
  5. The effectiveness of IEEE Project Domains depends very much on the situation in which they are applied. In order to further improve IEEE Final Year Project Domains practices we need to explicitly describe and utilise our knowledge about software domains of software engineering Final Year Project Domains for CSE technologies. This paper suggests a modelling formalism for supporting systematic reuse of software engineering technologies during planning of software projects and improvement programmes in Project Centers in Chennai for CSE.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai

    ReplyDelete
  6. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post. IT Whiz CCTV

    ReplyDelete
  7. Your website is terribly informative and your articles are wonderful.
    vivint review

    ReplyDelete
  8. Your articles are very well written and unique.vivint security reviews

    ReplyDelete
  9. I am definitely enjoying your website. You definitely have some great insight and great stories. cctv camera

    ReplyDelete
  10. Numerous new security organization proprietors do no understand that it requires some investment, thought, and cash to improvement their business. mall security guard

    ReplyDelete
  11. breach the security Very efficiently written information. It will be beneficial to anybody who utilizes it, including me. Keep up the good work. For sure i will check out more posts. This site seems to get a good amount of visitors.

    ReplyDelete
  12. TouchTec is a leading company in region with more than 10 years of experience that provides Security, Safety and Surveillance Solutions with high assurance to improve security and efficiencies for identity management, access to critical facilities, intelligence analysis, guest worker programs, and national identity programs
    Cctv Camera In Mohali
    Cctv Camera In Chandigarh
    Cctv Camera Panchkula
    Cctv Camera Zirakpur

    ReplyDelete
  13. The quality of your articles and contents is great.
    i thought about this

    ReplyDelete
  14. Hey, I am so thrilled I found your blog, I am here now and could just like to say thank for a tremendous post and all round interesting website. Please do keep up the great work. I cannot be without visiting your blog again and again. Sydney Home Alarms

    ReplyDelete
  15. Bitcoin network keeps it deliberate, as during a given time range, all exchanges are gathered in a square. The diggers should approve exchanges, and everything is recorded in an overall record. bitcoin mixer

    ReplyDelete
  16. Great post, you have pointed out some fantastic points , I likewise think this s a very wonderful website. Stainless Steel Screen Doors

    ReplyDelete
  17. It's late finding this act. At least, it's a thing to be familiar with that there are such events exist. I agree with your Blog and I will be back to inspect it more in the future so please keep up your act. Security Services london

    ReplyDelete
  18. It is an excellent blog, I have ever seen. I found all the material on this blog utmost unique and well written. And, I have decided to visit it again and again. https://securityreservation.edublogs.org/2021/06/17/what-is-a-monitored-home-security-system/

    ReplyDelete
  19. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. https://kestrelis10.medium.com/

    ReplyDelete