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

Spring 3.0整合Keycloak配置Spring Security遇阻,求基础配置方案

Spring Boot 3.0 集成Keycloak + Spring Security 基础配置方案

核心配置变更说明

  • WebSecurityConfigurerAdapter已完全移除:Spring Boot 3.0不再支持继承该类,需通过@Bean方式注册SecurityFilterChain来配置HttpSecurity。
  • HttpSecurity构建方式调整:直接通过链式调用或Lambda表达式配置,无需重写configure方法。

依赖准备

在pom.xml中添加所需依赖(Maven示例):

<dependencies>
    <!-- Spring Security 核心依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <!-- Keycloak 官方集成依赖 -->
    <dependency>
        <groupId>org.keycloak</groupId>
        <artifactId>keycloak-spring-boot-starter</artifactId>
        <version>22.0.5</version> <!-- 替换为匹配Keycloak服务的版本 -->
    </dependency>
    <!-- 若作为OAuth2资源服务器,可替换为Spring官方OAuth2依赖 -->
    <!-- <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    </dependency> -->
</dependencies>

完整配置示例

1. Spring Security 配置类

替换原继承WebSecurityConfigurerAdapter的写法,改用SecurityFilterChain配置:

@Configuration
@EnableWebSecurity
@Slf4j
public class WebSecurityConfig {

    // 注入自定义未认证处理器(可选,根据业务需求实现)
    private final AuthenticationEntryPoint unauthorizedHandler;

    public WebSecurityConfig(AuthenticationEntryPoint unauthorizedHandler) {
        this.unauthorizedHandler = unauthorizedHandler;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        log.trace("配置HttpSecurity规则");
        http
            .cors(withDefaults()) // 启用CORS,可自定义CorsConfigurationSource细化规则
            .csrf(csrf -> csrf.disable()) // 无状态API场景建议禁用CSRF
            .exceptionHandling(exceptions -> exceptions
                .authenticationEntryPoint(unauthorizedHandler) // 自定义未授权请求处理逻辑
            )
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 启用无状态会话,适配JWT
            )
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**", "/actuator/**").permitAll() // 公开接口无需认证
                .anyRequest().authenticated() // 其余所有接口需身份认证
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt.decoder(jwtDecoder())) // 配置JWT解码器,对接Keycloak
            );

        return http.build();
    }

    @Bean
    public JwtDecoder jwtDecoder() {
        // 指向Keycloak对应Realm的OpenID配置地址
        return JwtDecoders.fromIssuerLocation("http://你的Keycloak地址/auth/realms/你的Realm名称");
    }
}

2. Keycloak 配置(application.yml)

方式一:使用Keycloak官方starter配置

keycloak:
  auth-server-url: http://你的Keycloak地址/auth
  realm: 你的Realm名称
  resource: 你的客户端ID
  credentials:
    secret: 你的客户端密钥
  use-resource-role-mappings: true
  bearer-only: true # 作为资源服务器时必须设置为true

方式二:使用Spring OAuth2资源服务器配置

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://你的Keycloak地址/auth/realms/你的Realm名称

关键注意事项

  • 会话策略:无状态API场景必须设置SessionCreationPolicy.STATELESS,避免Spring创建会话存储用户信息。
  • JWT验证:issuer-uri必须指向Keycloak Realm的OpenID配置地址(完整路径一般为http://{Keycloak地址}/auth/realms/{Realm名称}/.well-known/openid-configuration),Spring会自动拉取公钥验证JWT合法性。
  • 权限控制:可通过hasRole("角色名")或hasAuthority("权限名")细化接口权限,Keycloak中配置的角色会自动映射为带ROLE_前缀的Spring Security权限。
  • CORS配置:若前端存在跨域请求,需自定义CorsConfigurationSource指定允许的域名、请求方法、请求头规则,避免跨域拦截。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 17:25:31