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

Spring Boot集成Spring Security时/h2-console免登录访问失效问题

问题排查与解决方案

核心问题分析

你的配置遗漏了H2控制台必需的iframe权限配置,这是导致登录提示仍出现的关键原因:

  1. H2控制台依赖iframe渲染页面,Spring Security默认启用X-Frame-Options限制,会阻止H2控制台的iframe加载,进而触发登录拦截(即便你已配置permitAll)。
  2. 另外你的内存认证配置未生效——configureGlobal方法未添加@Autowired注解,Spring Security不会自动调用该方法,不过这不是当前访问H2控制台的障碍。

修正后的完整配置

package com.taxiWithBack.config;

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.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public BCryptPasswordEncoder encodePwd(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                // 禁用CSRF,适配H2控制台的POST请求
                .csrf().disable()
                // 禁用X-Frame-Options,允许H2控制台的iframe加载
                .headers(headers -> headers.frameOptions().disable())
                .authorizeHttpRequests(authorize -> authorize
                        // 允许所有请求访问H2控制台
                        .requestMatchers("/h2-console/**").permitAll()
                        .requestMatchers("/admin").hasRole("ADMIN")
                        .requestMatchers("/").permitAll()
                        // 其余请求需要认证
                        .anyRequest().authenticated()
                )
                .formLogin()
                .permitAll();

        return http.build();
    }

    // 修正内存认证配置:添加@Autowired让Spring自动调用
    @Autowired
    public void configureGlobal(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user").password(encodePwd().encode("password")).roles("USER")
                .and()
                .withUser("admin").password(encodePwd().encode("password")).roles("ADMIN");
    }
}

额外注意事项

  • 确保application.properties/application.yml中H2控制台配置正确,示例:
    spring.h2.console.enabled=true
    spring.h2.console.path=/h2-console
    spring.datasource.url=jdbc:h2:mem:testdb
    
  • 重启应用后访问/h2-console,即可直接进入控制台无需登录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 10:03:16