To disable Spring Security for static resources in a Spring Boot application, you can configure Spring Security to ignore specific paths or patterns. Here are the steps:
-
Configure Spring Security to Ignore Static Resources:
You can use the
WebSecurityCustomizer
to ignore specific paths or patterns. For example, to ignore all requests to the/static/**
path, you can add the following configuration:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/static/**");
}
}
-
Using
requestMatchers
in Spring Security 6: If you are using Spring Security 6, you need to userequestMatchers
instead ofantMatchers
. Here is an example:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) {
web.ignoring().requestMatchers(PathRequest.toStaticResources());
}
}
-
Customizing Resource Handling:
You can also customize how static resources are handled by Spring Boot by configuring the
ResourceHandlerRegistry
in aWebMvcConfigurer
implementation:
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new VersionResourceResolver().addContentVersionStrategy("/**"));
}
}
-
Using
Cache-Control
Headers: If you need to set specificCache-Control
headers for static resources, you can do so by setting the headers directly in theHttpServletResponse
from a controller method:
@Controller
public class MyController {
@RequestMapping(...)
public String myMethod(HttpServletResponse response) {
response.setHeader("Cache-Control", "max-age=14400");
// ...
}
}
By following these steps, you can ensure that Spring Security does not interfere with the serving of static resources in your Spring Boot application.
Citations:
[1] https://stackoverflow.com/questions/76097411/how-can-i-configure-spring-security-6-to-ignore-the-static-resources-folder
[2] https://www.codejava.net/frameworks/spring-boot/spring-security-allow-static-resources
[3] https://www.geeksforgeeks.org/serve-static-resources-with-spring/
[4] https://www.reddit.com/r/javahelp/comments/125ds72/spring_security_not_allowing_static_folder_access/
[5] https://stackoverflow.com/questions/33214501/how-to-add-cache-control-header-to-static-resource-in-spring-boot
Top comments (0)