经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
Spring Boot 3.1中如何整合Spring Security和Keycloak
来源:cnblogs  作者:程序猿DD  时间:2023/6/2 10:52:52  对本文有异议

在今年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等。

  1. 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中添加依赖:

  1. <dependency>
  2. <groupId>org.springframework.security</groupId>
  3. <artifactId>spring-security-oauth2-jose</artifactId>
  4. </dependency>

第三步:修改配置文件

  1. spring:
  2. security:
  3. oauth2:
  4. resourceserver:
  5. jwt:
  6. issuer-uri: http://localhost:9090/realms/MyAppRealm
  7. jwk-set-uri: http://localhost:9090/realms/MyAppRealm/protocol/openid-connect/certs

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

  1. @RequestMapping("/test")
  2. @RestController
  3. public class MySuperSecuredController {
  4. @GetMapping("/hello")
  5. public String hello(){
  6. return "hello";
  7. }
  8. }

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

  1. @Configuration
  2. @EnableWebSecurity
  3. public class WebSecurityConfig {
  4. @Bean
  5. public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
  6. httpSecurity
  7. .authorizeHttpRequests(registry -> registry
  8. .requestMatchers("/test/**").hasRole("SYS_ADMIN")
  9. .anyRequest().authenticated()
  10. )
  11. .oauth2ResourceServer(oauth2Configurer -> oauth2Configurer.jwt(jwtConfigurer -> jwtConfigurer.jwtAuthenticationConverter(jwt -> {
  12. Map<String, Collection<String>> realmAccess = jwt.getClaim("realm_access");
  13. Collection<String> roles = realmAccess.get("roles");
  14. var grantedAuthorities = roles.stream()
  15. .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
  16. .toList();
  17. return new JwtAuthenticationToken(jwt, grantedAuthorities);
  18. })))
  19. ;
  20. return httpSecurity.build();
  21. }
  22. }

验证一下

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

尝试请求/test/hello接口:

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

小结

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

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

原文链接:https://www.cnblogs.com/didispace/p/17448193.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号