You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IDEA启动Spring Boot项目出现异常登录页面问题求助

问题排查与解决方案

核心原因是Spring Security默认会拦截所有HTTP请求,强制跳转至登录页面——只要项目引入了Spring Security依赖,它就会自动启用默认的安全规则,所有未认证的请求都会被重定向到登录页。

以下是具体的排查和解决步骤:

  • 自定义Spring Security权限配置
    创建一个安全配置类,放开根路径的匿名访问权限:
    (适用于Spring Security 5.7之前版本,继承WebSecurityConfigurerAdapter)

    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()
                    .antMatchers("/").permitAll() // 允许根路径匿名访问
                    .anyRequest().authenticated() // 其他请求需认证
                .and()
                .formLogin() // 保留默认登录页(按需调整)
                .and()
                .logout().permitAll();
        }
    }
    

    (Spring Security 5.7+ / Spring Boot 2.7+推荐的无继承配置方式)

    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
    @EnableWebSecurity
    public class SecurityConfig {
        @Bean
        public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
            http
                .authorizeHttpRequests(auth -> auth
                    .requestMatchers("/").permitAll()
                    .anyRequest().authenticated()
                )
                .formLogin(form -> form.permitAll())
                .logout(logout -> logout.permitAll());
            return http.build();
        }
    }
    
  • 检查Controller路由配置
    确认Controller类上没有额外的@RequestMapping前缀,比如如果加了@RequestMapping("/demo"),那你的根路径映射实际是/demo而非/,会导致访问localhost:9092时匹配不到你的Controller方法,触发Security的默认拦截。

  • 验证模板文件路径
    确保homes.html放在src/main/resources/templates/目录下(Thymeleaf默认扫描路径),虽然这不是导致跳转登录的直接原因,但路径错误会导致正常授权后无法显示模板。

  • 临时禁用Security(仅用于测试验证)
    若要快速确认问题根源,可在application.properties中添加配置临时关闭Security:

    spring.security.enabled=false
    

    重启项目后访问localhost:9092,如果能正常显示你的模板,即可确认是Spring Security的拦截规则导致的跳转。

内容的提问来源于stack exchange,提问作者user18583088

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:03:20