我设置了主页,Spring Security中的任何人都可以访问该主页.然而,当我输入localhost:8080/home
时,它会将我重定向到第localhost:8080/login
页,并要求我登录.你能告诉我下面的代码出了什么问题吗?
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.csrf(CsrfConfigurer::disable)
.authorizeHttpRequests(requests -> requests
.dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll()
.requestMatchers("/home").permitAll()
)
.formLogin(withDefaults())
.build();
}
}
@Controller
public class AuthController {
@GetMapping("/home")
@ResponseBody
public String home() {
return "Home Page";
}
}
调试日志(log)为:
我正在使用:
- Spring Security版本6.1.4
- Spring Boot框架版本3.1.4
- JDK 20
- Java 17
problem是我的应用程序文件不在根包中.
solution(感谢Serghei Motpann)添加了一个显式基本包扫描,如:@SpringBootApplication(scanBasePackages = "package_name")