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

45 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. 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
  6. Your website is terribly informative and your articles are wonderful.
    vivint review

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

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

    ReplyDelete
  9. 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
  10. The quality of your articles and contents is great.
    i thought about this

    ReplyDelete
  11. 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
  12. 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
  13. Great post, you have pointed out some fantastic points , I likewise think this s a very wonderful website. Stainless Steel Screen Doors

    ReplyDelete
  14. 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
  15. 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
  16. 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
  17. Corrugated cardboard rolls or sheets can likewise be utilized to secure ground surface. Layer gives sway protection anyway it isn't covered with a water safe completion and ought to be kept dry consistently so it doesn't crumble. EMF Protectors

    ReplyDelete
  18. Consequently the focal point of the short conversation circles around the kinds of protection reached out in the United States, the new shows and arrangements like TRIPS and how it has adequately had an effect over the protection of plants in the United States and the fallout outcomes.
    EMF Protectors

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! security company in singapore

    ReplyDelete
  21. This is such a great resource that you are providing and you give it away for free. https://securitycompany123.blogspot.com/2021/09/the-commercial-enterprise-owners.html

    ReplyDelete
  22. Thank you so much for the post you do. I like your post and all you share with us is up to date and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job. security guard services singapore

    ReplyDelete
  23. Anonymous27/9/21 06:59

    Can I just say what a relief to find someone who actually knows what theyre talking about on the internet. You definitely know how to bring an issue to light and make it important. More people need to read this and understand this side of the story. I cant believe youre not more popular because you definitely have the gift. close protection chauffeur

    ReplyDelete
  24. I would like to say that this blog really convinced me to do it! Thanks, very good post. cambodia security company

    ReplyDelete
  25. This comment has been removed by the author.

    ReplyDelete
  26. Thanks for your insight for your fantastic posting. I’m glad I have taken the time to see this. best cambodian security company

    ReplyDelete
  27. This comment has been removed by the author.

    ReplyDelete
  28. I got too much interesting stuff on your blog. I guess I am not the only one having all the enjoyment here! Keep up the good work. Reliable Security Service in Cambodia

    ReplyDelete
  29. I was looking at some of your posts on this website and I conceive this web site is really instructive! Keep putting up.. check more info about security company

    ReplyDelete
  30. This was a really great contest and hopefully I can attend the next one. It was alot of fun and I really enjoyed myself.. https://www.tumblr.com/blog/securityservicecambodia1212

    ReplyDelete
  31. Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include. security guard company in phnom penh

    ReplyDelete
  32. I have bookmarked your blog, the articles are way better than other similar blogs.. thanks for a great blog! security company in cambodia

    ReplyDelete
  33. Wow, cool post. I'd like to write like this too - taking time and real hard work to make a great article... but I put things off too much and never seem to get started. Thanks though. cambodian security guard

    ReplyDelete
  34. Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. https://security-service-company-in-cambodia.mystrikingly.com/

    ReplyDelete
  35. A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. security service company in cambodia

    ReplyDelete
  36. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. security services

    ReplyDelete
  37. You have performed a great job on this article. It’s very precise and highly qualitative. You have even managed to make it readable and easy to read. You have some real writing talent. Thank you so much. https://security-company-in-phnom-penhs-site.yolasite.com/

    ReplyDelete
  38. You there, this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming. https://maryjames121973.wixsite.com/my-site-1/post/the-best-security-company-in-cambodia

    ReplyDelete
  39. 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. security guard in cambodia

    ReplyDelete
  40. When you use a genuine service, you will be able to provide instructions, share materials and choose the formatting style. best security company

    ReplyDelete
  41. Thanks for a wonderful share. Your article has proved your hard work and experience you have got in this field. Brilliant .i love it reading. best khmer security company

    ReplyDelete
  42. Great article Lot's of information to Read...Great Man Keep Posting and update to People..Thanks hire private security company

    ReplyDelete
  43. What a fantabulous post this has been. Never seen this kind of useful post. I am grateful to you and expect more number of posts like these. Thank you very much. https://johnbrito195907221.wordpress.com/2022/05/19/khmer-security-company/

    ReplyDelete
  44. pgaztec เกมแตกดี ที่สุด ในตอนนี้ เป็นหนึ่งในเกมสล็อตที่ได้รับความนิยมจากผู้เล่นมากมาย เกมนี้มีธีมที่น่าสนใจจากชุดหุ่นของชนบทและวัฒนธรรมอะซเทคจาก pg slot ซึ่งนำเสนอบรรยากาศ

    ReplyDelete