如何跳过Apache Tomcat登录页直接访问Spring Boot项目?
解决Spring Security默认登录页问题
问题原因
引入spring-boot-starter-security依赖后,Spring Security会默认启用全局认证保护,所有请求都需要登录才能访问,默认登录页是Tomcat提供的表单页,且默认用户名是user(不是admin/root),密码是启动日志中生成的随机字符串,这也是你用admin/root登录失败的原因。
解决方案
方案1:完全禁用Spring Security(适合不需要任何安全控制的场景)
在配置文件中添加以下配置:
# application.properties spring.security.enabled=false
或者直接在build.gradle中移除spring-boot-starter-security依赖:
// 移除该行依赖 implementation 'org.springframework.boot:spring-boot-starter-security'
方案2:配置Spring Security允许匿名访问所有请求(适合后续可能需要安全控制的场景)
根据你的Spring Boot版本选择对应的配置方式:
Spring Boot 2.x版本
创建Security配置类:
import org.springframework.context.annotation.Configuration; 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; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest().permitAll() // 允许所有请求匿名访问 .and().csrf().disable(); // 可选:若不需要CSRF保护可关闭 } }
Spring Boot 3.x版本(WebSecurityConfigurerAdapter已废弃)
创建Security配置类:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth .anyRequest().permitAll() ).csrf(csrf -> csrf.disable()); // 可选:关闭CSRF保护 return http.build(); } }
内容的提问来源于stack exchange,提问作者hhrzc
相关产品推荐
相关产品推荐

