Spring Boot 3.1.3及以上版本集成Keycloak方案求助
适配Spring Boot 3+的Keycloak集成方案(替换废弃的
KeycloakWebSecurityConfigurerAdapter) 1. 依赖调整
Spring Boot 3+ 已移除对KeycloakWebSecurityConfigurerAdapter的支持,改用标准的OAuth2资源服务器模式,同时保留Keycloak的专属配置支持。更新你的pom.xml(Maven)或build.gradle(Gradle)依赖:
Maven 示例
<!-- Spring Boot OAuth2 资源服务器依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency> <!-- Keycloak Spring Boot Starter 适配3.x版本 --> <dependency> <groupId>org.keycloak</groupId> <artifactId>keycloak-spring-boot-starter</artifactId> <version>22.0.5</version> <!-- 需与Spring Boot 3.x版本兼容,建议使用Keycloak 21+ --> </dependency>
2. 核心安全配置替换
不再继承KeycloakWebSecurityConfigurerAdapter,而是通过定义SecurityFilterChain Bean来配置安全规则,结合OAuth2资源服务器的JWT验证机制。
基础安全配置类示例
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.oauth2.server.resource.authentication.JwtAuthenticationConverter; import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http // 关闭CSRF(前后端分离项目可按需求调整) .csrf(csrf -> csrf.disable()) // 配置请求权限规则 .authorizeHttpRequests(auth -> auth // 允许公开访问的接口(如登录、健康检查) .requestMatchers("/api/public/**", "/actuator/**").permitAll() // 需要特定角色的接口 .requestMatchers("/api/admin/**").hasRole("ADMIN") // 其余接口需认证 .anyRequest().authenticated() ) // 开启OAuth2资源服务器,使用JWT验证 .oauth2ResourceServer(oauth2 -> oauth2 .jwt(jwt -> jwt // 自定义JWT权限转换器,将Keycloak的roles转换为Spring Security的GrantedAuthority .jwtAuthenticationConverter(jwtAuthenticationConverter()) ) ); return http.build(); } // 自定义JWT权限转换器:将Keycloak中的"realm_access.roles"映射为带"ROLE_"前缀的Spring Security角色 private JwtAuthenticationConverter jwtAuthenticationConverter() { JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); grantedAuthoritiesConverter.setAuthoritiesClaimName("realm_access.roles"); grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_"); JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter); return jwtAuthenticationConverter; } }
3. 配置文件设置
在application.yml中配置Keycloak的连接信息,替代原有的Keycloak专属配置:
spring: security: oauth2: resourceserver: jwt: issuer-uri: http://your-keycloak-server/auth/realms/your-realm-name jwk-set-uri: http://your-keycloak-server/auth/realms/your-realm-name/protocol/openid-connect/certs keycloak: realm: your-realm-name resource: your-client-id credentials: secret: your-client-secret auth-server-url: http://your-keycloak-server/auth
4. 自定义认证逻辑(可选)
如果需要保留原有的Keycloak认证逻辑(如用户信息获取、自定义权限判断),可以通过KeycloakAuthenticationProvider实现:
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.ProviderManager; @Configuration public class KeycloakAuthConfig { @Bean public KeycloakAuthenticationProvider keycloakAuthenticationProvider() { KeycloakAuthenticationProvider provider = new KeycloakAuthenticationProvider(); // 自定义用户权限映射逻辑,比如结合数据库用户信息 provider.setGrantedAuthoritiesMapper(authorities -> { // 此处可添加自定义权限转换逻辑 return authorities; }); return provider; } @Bean public AuthenticationManager authenticationManager() { return new ProviderManager(keycloakAuthenticationProvider()); } }
5. Angular端适配说明
Angular端的Keycloak集成无需大幅改动,继续使用keycloak-angular和keycloak-js库,只需确保:
- 前端请求携带的JWT Token格式符合后端OAuth2资源服务器的验证要求
- Keycloak客户端配置的
redirectUri、webOrigin等参数与前端部署地址一致 - 后端配置允许前端域名的跨域请求(若启用CORS)
6. 示例项目核心结构
your-project/ ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ ├── com/yourcompany/ │ │ │ │ ├── config/ │ │ │ │ │ ├── SecurityConfig.java │ │ │ │ │ └── KeycloakAuthConfig.java(可选) │ │ │ │ ├── controller/ │ │ │ │ │ ├── PublicController.java │ │ │ │ │ └── AdminController.java │ │ │ │ └── service/ │ │ │ └── resources/ │ │ │ └── application.yml │ └── angular/ │ ├── src/ │ │ ├── app/ │ │ │ ├── keycloak/ │ │ │ │ └── keycloak-init.service.ts │ │ │ └── components/ │ │ └── environments/ │ │ └── environment.ts
内容的提问来源于stack exchange,提问作者user17099102
相关产品推荐
相关产品推荐

