'Thymeleaf cache and security in Spring Boot
In my web app (Spring Boot + Spring Security + Thymeleaf) I disabled caching for security purposes:
spring.thymeleaf.cache=false
I can't remember where did I get this information from, or if it's even true. I have a lot of images on my website and I'd like to cache them. What would you recommend?
Solution 1:[1]
Take a look at Spring Security – Cache Control Headers, it explains caching for ResponseEntity object, which can used to return an image in the form of a byte array.
This also shows a way of caching images specifically, although the post itself is from 2015, some parts can still be relevant.
Solution 2:[2]
Actually the spring.thymeleaf.cache property has nothing to do with security, but more with performance. If you disable the Thymeleaf cache, the templates will be automatically reloaded when they need to be parsed, it has to do with hot swapping your server-side templates.
This is helpful during development because you can instantly see changes to your templates. If not you would have to restart your application.
See the documentation on the Developer tools on what it's used for.
Spring as of version 4.x somewhere has several ways to implement static resource caching with versioning (cache busting mechanism). Assuming you are serving your images as static resources through Spring, you might want to look into these.
If the images themselves do not need to be secured, serving them up as static resources with caching applied like that should be enough.
Solution 3:[3]
Spring Security will automatically "cache bust" all requests, which is by design.
However for images that don't really need to be managed by Spring Security, you can disable it for specific resource directories, in your WebSecurityConfigurerAdapter (in this case the images directory would be in your ../resources/static directory).
@Override
public void configure(WebSecurity webSecurity) {
webSecurity.ignoring().antMatchers(
"/images/**"
)
}
And the Spring Boot way is to add
spring.resources.cache-period=your value here in seconds
You would only want to turn off the Thymeleaf cache in development, when you want to do a hot-reload of a template.
Test it works with
curl -X GET -I https://your-site/images/foo.png
This will cache them at the browser level. If you needed to cache them at a server level, you could use a reverse proxy like nginx.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daan Hoogland |
| Solution 2 | Arne Vandamme |
| Solution 3 |
