0

I'm trying to add spring security to a custom Java project, by manually adding all dependencies etc. So far I've been successful, but I (think I) have a problem with my WebSecurityConfigurerAdapter:

@Override
protected void configure(HttpSecurity http) throws Exception{
      http.authorizeRequests()
        .antMatchers("/index.html").hasAnyRole("USER", "ADMIN")
        .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.NEVER)
        .and()
        .formLogin()
        .loginPage("/sign-in")
        .permitAll();
}

When restricting index.html as above, the user is immediately required to login when entering the application base-URL (e.g localhost:8080/myapp/). However if I change the antMatcher to:

    ...
         http.authorizeRequests()
        .antMatchers("/test**").hasAnyRole("USER", "ADMIN")
        .and()
    ...

I can hit the application base-URL without having to login. It's worth mentioning that index.html and test.html are completely identical (they only contain an h1-tag), and are both located in the root of the generated .war-file: enter image description here

How do I configure the application so that the user doesn't have to login when entering the base-url, but only when requesting the index.html (e.g. localhost:8080/myapp/index.html)?

Thanks in advance

Edit: My app has an endpoint at localhost:8080/myapp/ looking like this:

@GetMapping("/")
public String home() {
    return ("<h1>Welcome</h1>");
}

The idea is that the user should be able to reach this without having to authenticate.

PeteHegn
  • 3
  • 4

1 Answers1

0

You can try this...

'''
         http.authorizeRequests()
        .antMatchers("/test**").permitAll().antMatchers("/index.html").hasAnyRole("USER", "ADMIN")
        .and()
'''
    

if test.html is your base file.

  • 1
    Thanks, I don't have a base file, but instead I have a rest endpoint at localhost:8080/myapp/, i.e. @GetMapping("/"), that greets the user. With your solution I'm still forced to login when hitting the base-url, but I can hit localhost:8080/myapp/test.html without login. – PeteHegn Jan 12 '21 at 10:49
  • You can permit @GetMapping("/") to all by using .antMatchers("/").permitAll() – Ajit Kumar Singh Jan 12 '21 at 17:39
  • I've already tried that, but as soon as I add the line .antMatchers("/index.html).hasAnyRole... in the configuration, it'll require login when hitting localhost:8080/myapp/... I can't figure out why that is. It's only when I'm filtering for index.html that it happens.... – PeteHegn Jan 12 '21 at 18:19
  • maybe you are calling index.html by @GetMapping("/"), Can you show your function in the controller for @GetMapping("/") – Ajit Kumar Singh Jan 12 '21 at 18:38
  • That's a good guess, but unfortunately it's not the case (see edit above). – PeteHegn Jan 12 '21 at 19:39