Spring Boot 3.1中如何整合Spring Security和Keycloak

在今年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。第一時間瞭解前沿行業消息、分享深度技術乾貨、獲取優質學習資源

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章