微服务网关集成Keycloak网关层授权
nanshan 2024-10-22 12:54 28 浏览 0 评论
概述
本文演示网关层作为Oauth2 Client,后端微服务作为Oauth2 Resource Server的场景下如何集成keycloak实现SSO授权流程,具体流程可以参考前文《微服务网关集成Keycloak方案概述》
环境准备
- 在前文创建的SpringBoot Realm下创建名为keycloak-gateway的client,Access Type为confidential,Valid Redirect URIs配置为http://localhost:5556/*,如下所示:
2. 查看client相关配置,如下:
{
"realm": "SpringBoot",
"auth-server-url": "http://localhost:8180/auth/",
"ssl-required": "external",
"resource": "keycloak-gateway",
"credentials": {
"secret": "27ecd5ee-5a1b-4158-a2f4-e983487ae6f8"
},
"confidential-port": 0
}
应用开发
注册中心准备
继续沿用之前的项目模块
- 主pom中加入SpringCloud相关依赖
<spring-cloud.version>2020.0.4</spring-cloud.version>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
- 创建注册中心子模块
创建keycloak-registration-eureka子模块作为注册中心,添加maven依赖如下:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
- 创建application.yml配置文件
eureka:
instance:
hostname: localhost
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
server:
peer-eureka-nodes-update-interval-ms: 1000
enable-self-preservation: false
wait-time-in-ms-when-sync-empty: 0
spring:
application:
name: keycloak-registration-eureka
server:
port: 8761
这样Eureka注册中心监听在8761端口。
- 创建启动类
package com.ywu.keycloak;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/**
* Hello world!
*
*/
@SpringBootApplication
@EnableEurekaServer
public class KeycloakEurekaServerApplication {
public static void main( String[] args ) {
SpringApplication.run(KeycloakEurekaServerApplication.class, args);
}
}
启动注册中心
后端微服务(Oauth2 Resource Server)开发
- 创建keycloak-resource-server1子模块
添加maven依赖,如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
因为这个模块充当的角色时Oauth2 Resource Server,所以这里我们引入了spring-boot-starter-oauth2-resource-server依赖。
- 创建启动类
package com.ywu.keycloak;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* Hello world!
*
*/
@SpringBootApplication
@EnableDiscoveryClient
public class KeycloakResourceServerApplication {
public static void main( String[] args ) {
SpringApplication.run(KeycloakResourceServerApplication.class, args);
}
}
- 创建受保护资源
package com.ywu.keycloak.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
@Controller
public class PrincipleController {
@ResponseBody
@GetMapping(path = "/protected/principle")
public Object getPrinciple(Principal principal) {
return principal;
}
@GetMapping(path = "/logout")
public String logout(HttpServletRequest request) throws ServletException {
request.logout();
return "/";
}
}
其中,/protected/principle是受保护资源,返回认证后的身份信息,如用户名等
- 创建应用配置
创建application.yml,内容如下:
spring:
application:
name: keycloak-resource-server1
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:8180/auth/realms/SpringBoot
server:
port: 8280
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
这里指定了如下信息:
- 指定了eureka注册中心
- 指定了本服务监听的端口为8280
- 指定了资源服务器采用jwt token,授权服务地址为http://localhost:8180/auth/realms/SpringBoot,即为我们创建的SpringBoot Realm地址
- 资源权限配置
创建资源访问拦截配置,如下:
package com.ywu.keycloak.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(new KeycloakRealmRoleConverter());
http.authorizeRequests(authz -> authz
.antMatchers(HttpMethod.GET, "/testing/").permitAll()
.antMatchers(HttpMethod.GET, "/protected/**").hasRole("ADMIN")
.anyRequest().authenticated())
.oauth2ResourceServer().jwt().jwtAuthenticationConverter(converter);
}
}
package com.ywu.keycloak.config;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class KeycloakRealmRoleConverter implements Converter<Jwt, Collection<GrantedAuthority>> {
@Override
public Collection<GrantedAuthority> convert(Jwt jwt) {
final Map<String, Object> realmAccess = (Map<String, Object>) jwt.getClaims().get("realm_access");
return ((List<String>) realmAccess.get("roles")).stream()
.map(roleName -> "ROLE_" + roleName)
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
}
}
这里我们创建了SecurityConfig自定义配置类,并继承了WebSecurityConfigurerAdapter,关键在覆盖的configure()方法中,指定/protected/**匹配的路径需要ADMIN角色才能访问。如下代码
oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(converter)
指定了资源服务器校验的token类型是jwt,并使用自定义的转换器转换,这个主要是为了适配keycloak颁发的Token,从中解析出角色信息。
到这里后端服务就开发完成了,启动服务,服务正常监听在8280端口
- 服务测试
通过Post Man访问资源地址,如下:
cURL如下:
curl --location --request GET 'http://localhost:8280/protected/principle' \
--header 'Cookie: JSESSIONID=2EEB43E37A897D93BC38A00BCAE84DE2'
返回401未授权,这是正常的,因为/protected/principle资源需要ADMIN角色才能访问
接着我们通过Post Man获取一个Token(如何获取Token可以参考前文《Keycloak Servlet Filter Adapter使用》)
获取到Token后,将这里的Token放到之前请求的Header部分,如下:
再次请求发现能访问了,完整cRUL如下:
curl --location --request GET 'http://localhost:8280/protected/principle' \
--header 'Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJyOGxFQUMyQmZSVUhUVDUtRGEyUUp3dFJBNFdMbnpOaHZsTjdMSVF1YXVZIn0.eyJleHAiOjE2NTA4OTQzOTksImlhdCI6MTY1MDg5NDA5OSwianRpIjoiOTJmNjIxMzctMDVkMy00ZmYwLTg1OWMtZjYzMTAyNjRjNGNmIiwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo4MTgwL2F1dGgvcmVhbG1zL1NwcmluZ0Jvb3QiLCJhdWQiOlsiYWRhcHRlci1zZXJ2bGV0IiwiYWNjb3VudCJdLCJzdWIiOiI5MjUzNmM2Ny00YzdlLTQ2YzctOWM0NS04YWRkYWVjYTRmYzQiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJhZGFwdGVyLXNlcnZsZXQtcHVibGljIiwic2Vzc2lvbl9zdGF0ZSI6ImNkZjFkYjg0LTA0MjQtNGQ5ZC1hYzVjLThmMjViNzMxYzc4ZCIsImFjciI6IjEiLCJyZWFsbV9hY2Nlc3MiOnsicm9sZXMiOlsib2ZmbGluZV9hY2Nlc3MiLCJST0xFX0FETUlOIiwiQURNSU4iLCJ1bWFfYXV0aG9yaXphdGlvbiJdfSwicmVzb3VyY2VfYWNjZXNzIjp7ImFkYXB0ZXItc2VydmxldCI6eyJyb2xlcyI6WyJTWVMiXX0sImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sInNjb3BlIjoicHJvZmlsZSBlbWFpbCIsImVtYWlsX3ZlcmlmaWVkIjpmYWxzZSwicHJlZmVycmVkX3VzZXJuYW1lIjoiemhhbmdzYW4ifQ.d5dvPPn_7I0xqk11MgVrHp8g0nAUcw_leOvgdFw6MeKloUH9743fn0Z9bj_j6Hs4jBN87sXqUlrSuBn29MxV92FIUvaRV9nHjt8Ia1RLcqGw-3z-HBg1hc8BoGTfaNXmfYQCMN6q0imuD4Ln2fPrXAgqa0S3lXAKyyxZOV2PuIiTCd7fPOGd90B8H-49xNWWMaZxPHmI5qSDsVqBMaSTh6txI_5vgiQA2pKkavlMuPwaSnmvfJs1tQgzlGMBo7fpr-bG3mVO7PlHrtJxdYh79bK7RfZI2eniJ70udFBwWkpy4HuqQ_fPUQuUtDRkdiObgTZD3DPXT-90mfUcebvCLQ' \
--header 'Cookie: JSESSIONID=68D613089536D5B8224A32DA64E0909A'
为什么此时没有通过网关代理,请求头里传递Token就能访问了呢?具体原因在下文源码解读中分析
网关(Oauth2 Client)开发
- 创建网关子模块
创建keycloak-gateway-as-client子模块,添加pom依赖如下:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
前两个依赖是网关和注册中心相关依赖,由于本网关模块充当的是Oauth2 Client角色,所以需要引入spring-boot-starter-oauth2-client模块
- 创建启动类
package com.ywu.keycloak;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Hello world!
*
*/
@SpringBootApplication
public class KeycloakGatewayApplication {
public static void main( String[] args ) {
SpringApplication.run(KeycloakGatewayApplication.class, args);
}
}
- 创建应用配置
创建application.yml,内容如下:
server:
port: 5556
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
spring:
application:
name: keycloak-gateway-as-client
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
default-filters:
# 传递token到后端服务
- TokenRelay
security:
oauth2:
client:
provider:
my-keycloak-provider:
issuer-uri: http://localhost:8180/auth/realms/SpringBoot
# Individual properties can also be provided this way
# token-uri: http://localhost:8080/auth/realms/amrutrealm/protocol/openid-connect/token
# authorization-uri: http://localhost:8080/auth/realms/amrutrealm/protocol/openid-connect/auth
# userinfo-uri: http://localhost:8080/auth/realms/amrutrealm/protocol/openid-connect/userinfo
# user-name-attribute: preferred_username
registration:
keycloak-spring-gateway-client:
provider: my-keycloak-provider
client-id: keycloak-gateway
client-secret: 27ecd5ee-5a1b-4158-a2f4-e983487ae6f8
authorization-grant-type: authorization_code
# redirect-uri: "{baseUrl}/login/oauth2/code/keycloak"
这里配置稍微有点多,主要分为以下几块
- 网关配置
指定了网关监听的端口为5556,启用了注册中心服务自动发现功能,配置了全局过滤器TokenRelay,其作用是将授权后获取的Token自动放入到请求的Header中,以便请求转发到后端微服务是可以获取Token
- 注册中心配置
指定了eureka注册中心地址为http://localhost:8761/eureka/
- oauth2 client配置
这里配置了一个oauth认证provider,就是上述环境准备部分创建的client信息,指定使用授权码流程来获取Token
- 权限配置
创建访问拦截配置,如下:
package com.ywu.keycloak.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http.authorizeExchange()
.pathMatchers("/actuator/**")
.permitAll()
.and()
.authorizeExchange()
.anyExchange()
.authenticated()
.and()
.oauth2Login(); // to redirect to oauth2 login page.
return http.build();
}
}
这里配置了除/actuator/**匹配的路径外,其余都需要认证后才能访问,并调用了oauth2Login()方法,这是关键部分,下文会分析其原理。
到这里网关模块就开发完成了,启动服务,服务正常监听在5556端口
测试
将注册中心(keycloak-registration-eureka)、后端微服务(keycloak-resource-server1)以及网关(keycloak-gateway-as-client)都启动,在注册中心控制台看到服务信息如下:
打开浏览器,访问受保护资源http://localhost:5556/keycloak-resource-server1/protected/principle,页面重定向到了Keycloak的登录页,引导用户授权,如下:
完整地址如下:
http://localhost:8180/auth/realms/SpringBoot/protocol/openid-connect/auth?
response_type=code&client_id=keycloak-gateway&
state=5D-L5Q-yzoNYgvDFe0Z-nL112fr3YnTGnu86RQ08SlE%3D
&redirect_uri=http://localhost:5556/login/oauth2/code/keycloak-spring-gateway-client
输入之前创建的用户名/密码 zhangsan/123456后登入,如下
至此,网关作为Oauth2 Client集成Keycloak就已经实现了。
源码
- 注册中心
https://github.com/ywu2014/keycloak-demo/tree/master/keycloak-registration-eureka
- 后端服务
https://github.com/ywu2014/keycloak-demo/tree/master/keycloak-resource-server1
- 网关
https://github.com/ywu2014/keycloak-demo/tree/master/keycloak-gateway-as-client
相关推荐
- 服务器数据恢复—Raid5数据灾难不用愁,Raid5数据恢复原理了解下
-
Raid5数据恢复算法原理:分布式奇偶校验的独立磁盘结构(被称之为raid5)的数据恢复有一个“奇偶校验”的概念。可以简单的理解为二进制运算中的“异或运算”,通常使用的标识是xor。运算规则:若二者值...
- 服务器数据恢复—多次异常断电导致服务器raid不可用的数据恢复
-
服务器数据恢复环境&故障:由于机房多次断电导致一台服务器中raid阵列信息丢失。该阵列中存放的是文档,上层安装的是Windowsserver操作系统,没有配置ups。因为服务器异常断电重启后,rai...
- 服务器数据恢复-V7000存储更换磁盘数据同步失败的数据恢复案例
-
服务器数据恢复环境:P740+AIX+Sybase+V7000存储,存储阵列柜上共12块SAS机械硬盘(其中一块为热备盘)。服务器故障:存储阵列柜中有磁盘出现故障,工作人员发现后更换磁盘,新更换的磁盘...
- 「服务器数据恢复」重装系统导致XFS文件系统分区丢失的数据恢复
-
服务器数据恢复环境:DellPowerVault系列磁盘柜;用RAID卡创建的一组RAID5;分配一个LUN。服务器故障:在Linux系统层面对LUN进行分区,划分sdc1和sdc2两个分区。将sd...
- 服务器数据恢复-ESXi虚拟机被误删的数据恢复案例
-
服务器数据恢复环境:一台服务器安装的ESXi虚拟化系统,该虚拟化系统连接了多个LUN,其中一个LUN上运行了数台虚拟机,虚拟机安装WindowsServer操作系统。服务器故障&分析:管理员因误操作...
- 「服务器数据恢复」Raid5阵列两块硬盘亮黄灯掉线的数据恢复案例
-
服务器数据恢复环境:HPStorageWorks某型号存储;虚拟化平台为vmwareexsi;10块磁盘组成raid5(有1块热备盘)。服务器故障:raid5阵列中两块硬盘指示灯变黄掉线,无法读取...
- 服务器数据恢复—基于oracle数据库的SAP数据恢复案例
-
服务器存储数据恢复环境:某品牌服务器存储中有一组由6块SAS硬盘组建的RAID5阵列,其中有1块硬盘作为热备盘使用。上层划分若干lun,存放Oracle数据库数据。服务器存储故障&分析:该RAID5阵...
- 「服务器虚拟化数据恢复」Xen Server环境下数据库数据恢复案例
-
服务器虚拟化数据恢复环境:Dell某型号服务器;数块STAT硬盘通过raid卡组建的RAID10;XenServer服务器虚拟化系统;故障虚拟机操作系统:WindowsServer,部署Web服务...
- 服务器数据恢复—RAID故障导致oracle无法启动的数据恢复案例
-
服务器数据恢复环境:某品牌服务器中有一组由4块SAS磁盘做的RAID5磁盘阵列。该服务器操作系统为windowsserver,运行了一个单节点Oracle,数据存储为文件系统,无归档。该oracle...
- 服务器数据恢复—服务器磁盘阵列常见故障表现&解决方案
-
RAID(磁盘阵列)是一种将多块物理硬盘整合成一个虚拟存储的技术,raid模块相当于一个存储管理的中间层,上层接收并执行操作系统及文件系统的数据读写指令,下层管理数据在各个物理硬盘上的存储及读写。相对...
- 「服务器数据恢复」IBM某型号服务器RAID5磁盘阵列数据恢复案例
-
服务器数据恢复环境:IBM某型号服务器;5块SAS硬盘组成RAID5磁盘阵列;存储划分为1个LUN和3个分区:第一个分区存放windowsserver系统,第二个分区存放SQLServer数据库,...
- 服务器数据恢复—Zfs文件系统下误删除文件如何恢复数据?
-
服务器故障:一台zfs文件系统服务器,管理员误操作删除服务器上的数据。服务器数据恢复过程:1、将故障服务器所有磁盘编号后取出,硬件工程师检测所有硬盘后没有发现有磁盘存在硬件故障。以只读方式将全部磁盘做...
- 服务器数据恢复—Linux+raid5服务器数据恢复案例
-
服务器数据恢复环境:某品牌linux操作系统服务器,服务器中有4块SAS接口硬盘组建一组raid5阵列。服务器中存放的数据有数据库、办公文档、代码文件等。服务器故障&检测:服务器在运行过程中突然瘫痪,...
- 服务器数据恢复—Sql Server数据库数据恢复案例
-
服务器数据恢复环境:一台安装windowsserver操作系统的服务器。一组由8块硬盘组建的RAID5,划分LUN供这台服务器使用。在windows服务器内装有SqlServer数据库。存储空间LU...
- 服务器数据恢复—阿里云ECS网站服务器数据恢复案例
-
云服务器数据恢复环境:阿里云ECS网站服务器,linux操作系统+mysql数据库。云服务器故障:在执行数据库版本更新测试时,在生产库误执行了本来应该在测试库执行的sql脚本,导致生产库部分表被tru...
你 发表评论:
欢迎- 一周热门
-
-
爱折腾的特斯拉车主必看!手把手教你TESLAMATE的备份和恢复
-
如何在安装前及安装后修改黑群晖的Mac地址和Sn系列号
-
[常用工具] OpenCV_contrib库在windows下编译使用指南
-
WindowsServer2022|配置NTP服务器的命令
-
Ubuntu系统Daphne + Nginx + supervisor部署Django项目
-
WIN11 安装配置 linux 子系统 Ubuntu 图形界面 桌面系统
-
解决Linux终端中“-bash: nano: command not found”问题
-
NBA 2K25虚拟内存不足/爆内存/内存占用100% 一文速解
-
Linux 中的文件描述符是什么?(linux 打开文件表 文件描述符)
-
K3s禁用Service Load Balancer,解决获取浏览器IP不正确问题
-
- 最近发表
-
- 服务器数据恢复—Raid5数据灾难不用愁,Raid5数据恢复原理了解下
- 服务器数据恢复—多次异常断电导致服务器raid不可用的数据恢复
- 服务器数据恢复-V7000存储更换磁盘数据同步失败的数据恢复案例
- 「服务器数据恢复」重装系统导致XFS文件系统分区丢失的数据恢复
- 服务器数据恢复-ESXi虚拟机被误删的数据恢复案例
- 「服务器数据恢复」Raid5阵列两块硬盘亮黄灯掉线的数据恢复案例
- 服务器数据恢复—基于oracle数据库的SAP数据恢复案例
- 「服务器虚拟化数据恢复」Xen Server环境下数据库数据恢复案例
- 服务器数据恢复—RAID故障导致oracle无法启动的数据恢复案例
- 服务器数据恢复—服务器磁盘阵列常见故障表现&解决方案
- 标签列表
-
- linux 查询端口号 (58)
- docker映射容器目录到宿主机 (66)
- 杀端口 (60)
- yum更换阿里源 (62)
- internet explorer 增强的安全配置已启用 (65)
- linux自动挂载 (56)
- 禁用selinux (55)
- sysv-rc-conf (69)
- ubuntu防火墙状态查看 (64)
- windows server 2022激活密钥 (56)
- 无法与服务器建立安全连接是什么意思 (74)
- 443/80端口被占用怎么解决 (56)
- ping无法访问目标主机怎么解决 (58)
- fdatasync (59)
- 405 not allowed (56)
- 免备案虚拟主机zxhost (55)
- linux根据pid查看进程 (60)
- dhcp工具 (62)
- mysql 1045 (57)
- 宝塔远程工具 (56)
- ssh服务器拒绝了密码 请再试一次 (56)
- ubuntu卸载docker (56)
- linux查看nginx状态 (63)
- tomcat 乱码 (76)
- 2008r2激活序列号 (65)