Spring?Boot?3.1中整合Spring?Security和Keycloak的方法
在今年2月14日的時候,Keycloak 團隊宣布他們正在棄用大多數(shù) Keycloak 適配器。其中包括Spring Security和Spring Boot的適配器,這意味著今后Keycloak團隊將不再提供針對Spring Security和Spring Boot的集成方案。但是,如此強大的Keycloak,還要用怎么辦呢?本文就來聊聊,在最新的Spring Boot 3.1版本之下,如何將Keycloak和Spring Security一起跑起來。
準(zhǔn)備工作
這里所采用的框架與工具版本信息如下:
- Spring Boot 3.1.0
- Keycloak 21.1.1
如果您采用的是其他版本,本文內(nèi)容不一定有效,但可以作為參考。
配置Keycloak
第一步:為Spring Boot應(yīng)用創(chuàng)建Realm,并在下面創(chuàng)建一個Client
第二步:創(chuàng)建一個SYS_ADMIN角色,并創(chuàng)建一個用戶賦予SYS_ADMIN角色
第三步:調(diào)用Keycloak接口生成Access Token,可以用下面的curl命令或者其他任何發(fā)請求的工具,比如: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,后續(xù)驗證時候要用。
配置Spring Boot應(yīng)用
第一步:創(chuàng)建一個Spring Boot應(yīng)用,這個很簡單,這里不贅述了。如果您還不會,可以看看我的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
第四步:創(chuàng)建一個需要鑒權(quán)的測試接口
@RequestMapping("/test") @RestController public class MySuperSecuredController { @GetMapping("/hello") public String hello(){ return "hello"; } }
第五步:創(chuàng)建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應(yīng)用,同時保證Keycloak也在運行中。
嘗試請求/test/hello
接口:
- 當(dāng)不包含
Authorization
頭信息的時候,將返回401錯誤 - 當(dāng)包含
Authorization
頭信息(前文用調(diào)接口獲取的Access Token)的時候,才能正確訪問到。
小結(jié)
雖然Keycloak 團隊宣布了不再對Spring Security提供適配,但Spring Security長期以來一直為OAuth和OIDC提供強大的內(nèi)置支持。所以,只要我們理解Spring Security是如何處理OAuth和OIDC的,那么與Keyloak的集成依然不復(fù)雜。
到此這篇關(guān)于Spring Boot 3.1中如何整合Spring Security和Keycloak的文章就介紹到這了,更多相關(guān)Spring Boot 3.1整合Spring Security和Keycloak內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring中的SpringApplicationRunListener詳細解析
這篇文章主要介紹了Spring中的SpringApplicationRunListener詳細解析,SpringApplicationRunListener是一個監(jiān)聽SpringApplication中run方法的接口,在項目啟動過程的各個階段進行事件的發(fā)布,需要的朋友可以參考下2023-11-11java實現(xiàn)簡單學(xué)生成績管理系統(tǒng)
這篇文章主要為大家詳細介紹了java實現(xiàn)簡單學(xué)生成績管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02