Spring?Boot?3.1中整合Spring?Security和Keycloak的方法
在今年2月14日的時候,Keycloak 團(tuán)隊(duì)宣布他們正在棄用大多數(shù) Keycloak 適配器。其中包括Spring Security和Spring Boot的適配器,這意味著今后Keycloak團(tuán)隊(duì)將不再提供針對Spring Security和Spring Boot的集成方案。但是,如此強(qiáng)大的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ù)驗(yàn)證時候要用。
配置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();
}
}驗(yàn)證一下
在完成了上面配置所有之后之后,啟動Spring Boot應(yīng)用,同時保證Keycloak也在運(yùn)行中。
嘗試請求/test/hello接口:
- 當(dāng)不包含
Authorization頭信息的時候,將返回401錯誤 - 當(dāng)包含
Authorization頭信息(前文用調(diào)接口獲取的Access Token)的時候,才能正確訪問到。
小結(jié)
雖然Keycloak 團(tuán)隊(duì)宣布了不再對Spring Security提供適配,但Spring Security長期以來一直為OAuth和OIDC提供強(qiáng)大的內(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)文章希望大家以后多多支持腳本之家!
- SpringBoot如何整合Springsecurity實(shí)現(xiàn)數(shù)據(jù)庫登錄及權(quán)限控制
- SpringBoot2.0 整合 SpringSecurity 框架實(shí)現(xiàn)用戶權(quán)限安全管理方法
- Spring Boot整合Spring Security簡單實(shí)現(xiàn)登入登出從零搭建教程
- Spring Boot整合Spring Security的示例代碼
- SpringBoot整合Keycloak實(shí)現(xiàn)單點(diǎn)登錄的示例代碼
- Spring Boot/Angular整合Keycloak實(shí)現(xiàn)單點(diǎn)登錄功能
相關(guān)文章
Java?入門圖形用戶界面設(shè)計(jì)之事件處理下
圖形界面(簡稱GUI)是指采用圖形方式顯示的計(jì)算機(jī)操作用戶界面。與早期計(jì)算機(jī)使用的命令行界面相比,圖形界面對于用戶來說在視覺上更易于接受,本篇精講Java語言中關(guān)于圖形用戶界面的事件處理2022-02-02
Spring中的SpringApplicationRunListener詳細(xì)解析
這篇文章主要介紹了Spring中的SpringApplicationRunListener詳細(xì)解析,SpringApplicationRunListener是一個監(jiān)聽SpringApplication中run方法的接口,在項(xiàng)目啟動過程的各個階段進(jìn)行事件的發(fā)布,需要的朋友可以參考下2023-11-11
java實(shí)現(xiàn)簡單學(xué)生成績管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)簡單學(xué)生成績管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02
Spring?Boot中@Import三種使用方式實(shí)例詳解
這篇文章主要介紹了Spring?Boot中@Import三種使用方式,主要有引入普通類,引入importSelector的實(shí)現(xiàn)類及引入importBeanDefinitionRegister的實(shí)現(xiàn)類,結(jié)合實(shí)例代碼給大家講解的非常詳細(xì),需要的朋友可以參考下2022-11-11

