Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access static content in secured Spring Boot application

I have a standalone Spring Boot application with templates in /src/main/resources/templates and static content in /src/main/resources/static. I would like the static content to be accessible before authentication, so the CSS loads on the login page as well. Now it only loads after authentication. My security configuration looks like this:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger logger = Logger.getLogger(SecurityConfig.class);

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) {
        try {
            auth.inMemoryAuthentication()
            ...
        } catch (Exception e) {
            logger.error(e);
        }
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .formLogin()
                .defaultSuccessUrl("/projects", true)
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
                .permitAll()
                .and()
            .authorizeRequests()
                .antMatchers("/static/**").permitAll()
                .anyRequest().authenticated();
    }

}
like image 860
user3170702 Avatar asked Apr 02 '14 21:04

user3170702


People also ask

How do you serve a static html content page in spring boot?

Using Spring BootSpring Boot comes with a pre-configured implementation of ResourceHttpRequestHandler to facilitate serving static resources. By default, this handler serves static content from any of the /static, /public, /resources, and /META-INF/resources directories that are on the classpath.

How do you restrict static resources processed by Spring Security?

The Ant matchers match against the request path and not the path of the resource on the filesystem.So ignore any request that starts with "/resources/". This is similar to configuring http@security=none when using the XML namespace configuration.


1 Answers

The static content in classpath:/static is served at the root of the application (i.e. /*), whether or not the application is secure, so you need to match on specific paths underneath the root. Spring Boot permits all access by default to /js/**, /css/**, /images/** (see SpringBootWebSecurityConfiguration for details), but you may have switched that off (can't see the rest of your code).

like image 81
Dave Syer Avatar answered Sep 21 '22 14:09

Dave Syer