javaspringspring-bootspring-securitystatic-files

Unable to download static content using spring boot with spring security


I need to serve a static csv file in my spring boot app so that the browser can download it from the server. As read in multiple docs, spring boot serves the content of src/main/resources by default.

I have just kept my sample-user-creation.csv file in the src/main/resources folder. Apart from that I have not added any line of code for this to work.

I am trying to download file using GET request:

http://localhost:8080/sample-user-creation.csv

but it doesn't work at all.

I have also tried setting the :

spring.mvc.static-path-pattern=/content/** 

and tried using:

http://localhost:8080/content/sample-user-creation.csv

This doesn't work either.

I am using spring security and also tried setting the requestMatchers explicitly for the file to permitAll() but that doesn't work either.

.authorizeHttpRequests((auth) -> auth
                            .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                            .requestMatchers("/admin/**")
                            .hasRole("ADMIN")
                            .requestMatchers(HttpMethod.POST, "/public/login").permitAll()
                            .requestMatchers(HttpMethod.POST, "/public/register")
                            .permitAll()
                            .requestMatchers("/sample-user-creation.csv").permitAll()
                            .anyRequest().authenticated()
                        )

Why is this not working for me. All the docs say that this is a default behaviour and works without any configuration.

Am I doing anything wrong here or do I need to add any other configuration.

Adding few more details:

  1. I am passing a valid auth token (which works for my other api) with this API too.
  2. I have tried setting Content-Type: text/csv also in my requests.

Solution

  • Spring does not serve static content from the resources folder; it serves it from a folder named resources, or static, or public on the classpath.

    Inside your resources folder, put a folder named static, public, or resources. Any files then placed inside this folder will be served as static content.

    So, in your case, consider adding a folder inside of /src/main/resources called, static. Inside the static folder, add your file, sample-user-creation.csv. Start your app and you should be able to access that file at the root of your application, http://localhost:8080/sample-user-creation.csv

    If you still have the static path set, e.g. spring.mvc.static-path-pattern=/content/**, it will be available at http://localhost:8080/content/sample-user-creation.csv