1

I set up a basic Spring Boot project with *.js and *.css resources. I activated Thymeleaf, Spring Web and Spring Security. Now:

  1. for the url: http://localhost:8080/ css and js files are being read properly
  2. for the url: http://localhost:8080/second css and js files are still being read properly
  3. for the url: http://localhost:8080/second/third the application does not load the css and js files

I'm guessing it has to do with Spring security. Can anyone point me to the right direction, how to I set up SecurityConfig.java class properly, so the application would read the files after additional "/" in the url? I am aware of those solutions, they don't work :( Isn't putting "/second/**" enough as antMatchers?


My classes:

HomeController.java

@Controller
public class HomeController {

@GetMapping("/")
public String goHome() {
    return "index";
}

@GetMapping("/second")
public String goSecond() {
    return "secondpage";
}

@GetMapping("/second/third")
public String goThird() {
    return "thirdpage";
}
}

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth)
        throws Exception {
    PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
    auth.inMemoryAuthentication()
            .withUser("demo")
            .password(encoder.encode("demo"))
            .roles("USER", "ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/", "/second", "second/**").access("hasRole('USER')")
            .and()
            .formLogin();
}
}

This is the project structure:

enter image description here

Dominika
  • 187
  • 3
  • 13

2 Answers2

1

Try to add in SecurityConfig.class this configuration

@Override
public void configure(WebSecurity web) {
    web.ignoring()
        .antMatchers("/**/*.{js,html,css}");
}

It will allow js, html and css files to be ignored by security.

You also forgot a / before second/** in your configuration. I don't think it'll impact something but you could try:

.antMatchers("/", "/second", "/second/**").access("hasRole('USER')")
Lungu Daniel
  • 816
  • 2
  • 8
  • 15
0

So, after searching I found the solution, it's simpler than I thought.

I was putting

    <link href="css/styles.css" rel="stylesheet" type="text/css">

in my *.html files, instead of:

    <link href="/css/styles.css" rel="stylesheet" type="text/css">
  • there is a slash at the beginning of the href... And each file should have this slash at the beginning. Same goes for the *.js files.

Hope this helps someone one day.

Dominika
  • 187
  • 3
  • 13