关于java:Spring-Boot-31中如何整合Spring-Security和Keycloak

1次阅读

共计 2667 个字符,预计需要花费 7 分钟才能阅读完成。

在往年 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。第一工夫理解前沿行业音讯、分享深度技术干货、获取优质学习资源

正文完
 0