Aleix Alcover
Aleix Alcover

Reputation: 649

Static resources are secured and not accessible after migrating to Spring Boot 2.0

I have migrated a Spring Boot web application from 1.5.10 to 2.0.0, which is deployed with Heroku and runs over several domains. For the main domain, that was the first one to be set, everything is working smoothly but for the rest any of the static resources; like Javascript, CSS, images and icons (Webjars) are not accessible.

maindomain.com/js/example.js works fine and can be directly accessed with the browser. secondarydomain.com/js/example.js can't be accessed by the browser and running the app arises this error, I guess because instead of the .js file is returning some text message:

Refused to execute script from '' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled

The static resources are located at:

/resources/static/css

/resources/static/js

/resources/static/images

I have set the Spring security configuration with an extension of WebSecurityConfigurerAdapter, where I have withdrawn the annotation @EnableWebSecurity and I have added this code, with the intention to make sure that those resources are accessible, without success:

http
 .authorizeRequests()
     .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()

There is a HandleInterceptor, which deals with the directories accessible by each secondary domain. The main one, has access all over the application. In this other question, with a different approach to the same problem, there is an extract of the HandleInterceptor.

Spring Boot 2.0.0 & static resources with different domains for the same app

Upvotes: 1

Views: 810

Answers (1)

Wei Chun
Wei Chun

Reputation: 1343

Spring Security with boot is on the classpath, the auto-configuration secures all endpoints by default.

However, when it comes to complex applications, we need different security policies per endpoints. We also need to configure which endpoints should be secured, what type of users should be able to access the endpoints, and which endpoints should be public.

WebSecurity allow we to configure adding RequestMatcher instances that Spring Security should ignore.

HttpSecurity allow we can configure the endpoints that should be secured and the endpoint that should be public

public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
        .antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/css/**", "/js/**", "/image/**"").permitAll()
    }
}

Hope it help.

Upvotes: 1

Related Questions