Spring Boot 3+Gradle/Kotlin中WebSecurityConfigurerAdapter引用未解决求助
问题根源
你使用的Spring Boot 3.0.6对应Spring Security 6.x版本,而WebSecurityConfigurerAdapter在Spring Security 5.7+就已被标记为废弃,6.x版本直接移除了这个类——这就是IDE无法解析该类的核心原因,和IDE缓存、依赖配置无关。
替代配置方案
Spring Security 6.x采用基于Bean的组件式配置,不再依赖继承WebSecurityConfigurerAdapter。下面是适配你项目的Kotlin代码,实现简单的API Key认证:
package com.demo.dashboard.config import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.authentication.BadCredentialsException import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.http.SessionCreationPolicy import org.springframework.security.core.Authentication import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.web.SecurityFilterChain import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse @Configuration @EnableWebSecurity class SecurityConfig { // 自定义API Key校验过滤器 private class ApiKeyAuthFilter : UsernamePasswordAuthenticationFilter() { override fun attemptAuthentication(request: HttpServletRequest, response: HttpServletResponse): Authentication { val apiKey = request.getHeader("X-API-KEY")?.takeIf { it.isNotBlank() } ?: throw BadCredentialsException("API Key missing from request header") // 替换为你的实际校验逻辑:比如从配置文件/数据库验证API Key合法性 return if (apiKey == "your-valid-api-key") { UsernamePasswordAuthenticationToken(apiKey, null, emptyList()) } else { throw BadCredentialsException("Invalid API Key") } } } @Bean fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { return http // API场景禁用CSRF,采用无状态会话模式 .csrf { it.disable() } .sessionManagement { it.sessionCreationPolicy(SessionCreationPolicy.STATELESS) } // 配置接口授权规则 .authorizeHttpRequests { auth -> auth // 可选:开放无需认证的接口(如健康检查) .requestMatchers("/actuator/health").permitAll() // 其余所有接口需认证 .anyRequest().authenticated() } // 将自定义API Key过滤器加入认证链 .addFilterBefore(ApiKeyAuthFilter(), UsernamePasswordAuthenticationFilter::class.java) .build() } }
注意事项
- 你参考的文章基于Spring Security 5.x的旧写法,不适配6.x版本,建议以Spring官方文档为准。
- 生产环境不要硬编码API Key,可通过
@Value("${app.api-key}")从application.yml注入配置值。
内容的提问来源于stack exchange,提问作者Jesse
相关产品推荐
相关产品推荐

