javaspringspring-bootspring-securityunauthorized

Spring Security - Unauthorized though permitting all requests


I have such a web config in Spring Boot App:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().anyRequest().permitAll()
        .and()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
                .httpBasic();
    }
}

when trying to reach one of the urls (localhost:8080/test), I get Unauthorized. What am I doing wrong?


Solution

  • My shot is that your WebConfig is not placed in the right package. If your @SpringBootApplication annotated class is in com.example.demo then your WebConfig class should be placed under the com.example.demo package (or other sub-package, e.g: com.example.demo.config).

    package com.example.demo.config; // <-- move it to the (not-default) package
    
    // skipped imports
    // ...
    
    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class WebConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
          // config same as in the question's snippet
          // ...
        }
    }