在今年2月14日的时候,Keycloak 团队宣布他们正在弃用大多数 Keycloak 适配器。其中包括Spring Security和Spring Boot的适配器,这意味着今后Keycloak团队将不再提供针对Spring Security和Spring Boot的集成方案。但是,如此强大的Keycloak,还要用怎么办呢?本文就来聊聊,在最新的Spring Boot 3.1版本之下,如何将Keycloak和Spring Security一起跑起来。

准备工作

这里所采用的框架与工具版本信息如下:

  • Spring Boot 3.1.0
  • Keycloak 21.1.1

如果您采用的是其他版本,本文内容不一定有效,但可以作为参考。

配置Keycloak

第一步:为Spring Boot应用创建Realm,并在下面创建一个Client

第二步:创建一个SYS_ADMIN角色,并创建一个用户赋予SYS_ADMIN角色

第三步:调用Keycloak接口生成Access Token,可以用下面的curl命令或者其他任何发请求的工具,比如:Postman等。

curl --location 'http://localhost:9090/realms/MyAppRealm/protocol/openid-connect/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'username=<YOUR_USER_NAME>' \
--data-urlencode 'password=<YOUR_USER_PASSWORD>' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'client_id=My-Awesome-App' \
--data-urlencode 'client_secret=<KEYCLOAK_CLIENT_SECRET>' \
--data-urlencode 'scope=openid'

记住获得到Access Token,后续验证时候要用。

如果您学习过程中如遇困难?可以加入我们超高质量的Spring技术交流群,参与交流与讨论,更好的学习与进步!

配置Spring Boot应用

第一步:创建一个Spring Boot应用,这个很简单,这里不赘述了。如果您还不会,可以看看我的Spring Boot教程

第二步:在pom.xml中添加依赖:

<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
</dependency>

第三步:修改配置文件

spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:9090/realms/MyAppRealm
jwk-set-uri: http://localhost:9090/realms/MyAppRealm/protocol/openid-connect/certs

第四步:创建一个需要鉴权的测试接口

@RequestMapping("/test")
@RestController
public class MySuperSecuredController { @GetMapping("/hello")
public String hello(){
return "hello";
} }

第五步:创建SecurityFilterChain,用来告知Spring Security在JWT令牌中查找角色信息的位置。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig { @Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.authorizeHttpRequests(registry -> registry
.requestMatchers("/test/**").hasRole("SYS_ADMIN")
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2Configurer -> oauth2Configurer.jwt(jwtConfigurer -> jwtConfigurer.jwtAuthenticationConverter(jwt -> {
Map<String, Collection<String>> realmAccess = jwt.getClaim("realm_access");
Collection<String> roles = realmAccess.get("roles");
var grantedAuthorities = roles.stream()
.map(role -> new SimpleGrantedAuthority("ROLE_" + role))
.toList();
return new JwtAuthenticationToken(jwt, grantedAuthorities);
})))
; return httpSecurity.build();
}
}

验证一下

在完成了上面配置所有之后之后,启动Spring Boot应用,同时保证Keycloak也在运行中。

尝试请求/test/hello接口:

  • 当不包含Authorization头信息的时候,将返回401错误
  • 当包含Authorization头信息(前文用调接口获取的Access Token)的时候,才能正确访问到。

小结

虽然Keycloak 团队宣布了不再对Spring Security提供适配,但Spring Security长期以来一直为OAuth和OIDC提供强大的内置支持。所以,只要我们理解Spring Security是如何处理OAuth和OIDC的,那么与Keyloak的集成依然不复杂。好了,今天的分享就到这里!如果您学习过程中如遇困难?可以加入我们超高质量的Spring技术交流群,参与交流与讨论,更好的学习与进步!

欢迎关注我的公众号:程序猿DD。第一时间了解前沿行业消息、分享深度技术干货、获取优质学习资源

Spring Boot 3.1中如何整合Spring Security和Keycloak的更多相关文章

  1. Spring Boot的前世今生以及它和Spring Cloud的关系详解。

    要了解Spring Boot的发展背景,还得从2004年Spring Framework1.0版本发布开始说起,不过大家都是从开始学习Java就使用Spring Framework了,所以就不做过多展 ...

  2. Spring Boot + MyBatis + Druid + Redis + Thymeleaf 整合小结

    Spring Boot + MyBatis + Druid + Redis + Thymeleaf 整合小结 这两天闲着没事想利用**Spring Boot**加上阿里的开源数据连接池**Druid* ...

  3. 解决Spring Boot(2.1.3.RELEASE)整合spring-data-elasticsearch3.1.5.RELEASE报NoNodeAvailableException[None of the configured nodes are available

    Spring Boot(2.1.3.RELEASE)整合spring-data-elasticsearch3.1.5.RELEASE报NoNodeAvailableException[None of ...

  4. Spring Boot 2.0 快速集成整合消息中间件 Kafka

    欢迎关注个人微信公众号: 小哈学Java, 每日推送 Java 领域干货文章,关注即免费无套路附送 100G 海量学习.面试资源哟!! 个人网站: https://www.exception.site ...

  5. Spring Boot系列(三):Spring Boot整合Mybatis源码解析

    一.Mybatis回顾 1.MyBatis介绍 Mybatis是一个半ORM框架,它使用简单的 XML 或注解用于配置和原始映射,将接口和Java的POJOs(普通的Java 对象)映射成数据库中的记 ...

  6. spring boot 学习(六)spring boot 各版本中使用 log4j2 记录日志

    spring boot 各版本中使用 log4j2 记录日志 前言 Spring Boot中默认日志工具是 logback,只不过我不太喜欢 logback.为了更好支持 spring boot 框架 ...

  7. Spring Boot和Feign中使用Java 8时间日期API(LocalDate等)的序列化问题【转】

    Spring Boot和Feign中使用Java 8时间日期API(LocalDate等)的序列化问题 http://blog.didispace.com/Spring-Boot-And-Feign- ...

  8. Spring Boot源码中模块详解

    Spring Boot源码中模块详解 一.源码 spring boot2.1版本源码地址:https://github.com/spring-projects/spring-boot/tree/2.1 ...

  9. 阿里P7级教你如何在Spring Boot应用程序中使用Redis

    在Spring Boot应用程序中使用Redis缓存的步骤: 1.要获得Redis连接,我们可以使用Lettuce或Jedis客户端库,Spring Boot 2.0启动程序spring-boot-s ...

  10. 曹工说Spring Boot源码(17)-- Spring从xml文件里到底得到了什么(aop:config完整解析【中】)

    写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...

随机推荐

  1. arc145前三题

    为什么只有前三题呢...第四题想了一个小时没思路(主要是半个小时的时候发现看错题了),然后看粉兔博客发现要用Cantor集一类的神奇玩意,手贱看了E题发现还是线性基.于是就run了.NOIP前再学吧 ...

  2. python入门教程之三编码问题

    1编码问题 Python文件中如果未指定编码,在执行过程中会出现报错: !/usr/bin/python print ("你好,世界") 以上程序执行输出结果为: 文件" ...

  3. [Linux/Apache Http]Apache Http(d)服务访问时报: 403 Forbidden You don't have permission to access /cdh/ on this server.

    1 问题描述 http错误代码403:403 Forbidden 资源不可用.服务器理解客户的请求,但拒绝处理它.通常由于服务器上文件或目录的权限设置导致. 2 解决思路 胜利的果实: 确保关闭sel ...

  4. BISS-C 8通道采集renishaw传感器及其CRC校验

    背景 BISS-C 是常见的位置编码器传输协议,相对于传统的协议,支持更快的传输速度,电器接口为电压差分RS422或者485,抗干扰能力较强,在精密位置传输中应用广泛. 下述信息源自雷尼绍 典型的请求 ...

  5. 【Vue】二

    一个第三方js处理类库 BootCDN Vue过滤器 Date.now() 获取时间戳 Date.now() 1652411231222 计算属性实现 <body> <div id= ...

  6. VUE项目 启动提示 npn ERRT nissing script: dev解决办法

    VUE项目 启动提示 npn ERRT nissing script: dev 提示 丢失 dev 解决办法 首先 查看项目目录里面的 package.json 文件, 文件内容如下: 发现红框这里是 ...

  7. Docker构建镜像踩坑日记

    从Github上拉取python项目后,运行dockerfile构建镜像失败,一步步查找原因 主要原因就是国内下载各种依赖超时,以下提供pip.apt.pipenv镜像解决方案 pip更换国内镜像 这 ...

  8. Java的对象克隆

    本节我们会讨论 Cloneable 接口,这个接口指示一个类提供了一个安全的 clone() 方法. Object 类提供的 clone() 方法是 "浅拷贝",并没有克隆对象中引 ...

  9. docker上面部署nginx-waf 防火墙“modsecurity”,使用CRS规则,搭建WEB应用防火墙

    web防火墙(waf)免费开源的比较少,并且真正可以商用的WAF少之又少,modsecurity 是开源防火墙鼻祖并且有正规公司在维护着,目前是https://www.trustwave.com在维护 ...

  10. win11 计算器的进制转换