微服务网关集成Keycloak网关层授权
nanshan 2024-10-22 12:54 42 浏览 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
相关推荐
- 0722-6.2.0-如何在RedHat7.2使用rpm安装CDH(无CM)
-
文档编写目的在前面的文档中,介绍了在有CM和无CM两种情况下使用rpm方式安装CDH5.10.0,本文档将介绍如何在无CM的情况下使用rpm方式安装CDH6.2.0,与之前安装C5进行对比。环境介绍:...
- ARM64 平台基于 openEuler + iSula 环境部署 Kubernetes
-
为什么要在arm64平台上部署Kubernetes,而且还是鲲鹏920的架构。说来话长。。。此处省略5000字。介绍下系统信息;o架构:鲲鹏920(Kunpeng920)oOS:ope...
- 生产环境starrocks 3.1存算一体集群部署
-
集群规划FE:节点主要负责元数据管理、客户端连接管理、查询计划和查询调度。>3节点。BE:节点负责数据存储和SQL执行。>3节点。CN:无存储功能能的BE。环境准备CPU检查JDK...
- 在CentOS上添加swap虚拟内存并设置优先级
-
现如今很多云服务器都会自己配置好虚拟内存,当然也有很多没有配置虚拟内存的,虚拟内存可以让我们的低配服务器使用更多的内存,可以减少很多硬件成本,比如我们运行很多服务的时候,内存常常会满,当配置了虚拟内存...
- 国产深度(deepin)操作系统优化指南
-
1.升级内核随着deepin版本的更新,会自动升级系统内核,但是我们依旧可以通过命令行手动升级内核,以获取更好的性能和更多的硬件支持。具体操作:-添加PPAs使用以下命令添加PPAs:```...
- postgresql-15.4 多节点主从(读写分离)
-
1、下载软件[root@TX-CN-PostgreSQL01-252software]#wgethttps://ftp.postgresql.org/pub/source/v15.4/postg...
- Docker 容器 Java 服务内存与 GC 优化实施方案
-
一、设置Docker容器内存限制(生产环境建议)1.查看宿主机可用内存bashfree-h#示例输出(假设宿主机剩余16GB可用内存)#Mem:64G...
- 虚拟内存设置、解决linux内存不够问题
-
虚拟内存设置(解决linux内存不够情况)背景介绍 Memory指机器物理内存,读写速度低于CPU一个量级,但是高于磁盘不止一个量级。所以,程序和数据如果在内存的话,会有非常快的读写速度。但是,内存...
- Elasticsearch性能调优(5):服务器配置选择
-
在选择elasticsearch服务器时,要尽可能地选择与当前业务量相匹配的服务器。如果服务器配置太低,则意味着需要更多的节点来满足需求,一个集群的节点太多时会增加集群管理的成本。如果服务器配置太高,...
- Es如何落地
-
一、配置准备节点类型CPU内存硬盘网络机器数操作系统data节点16C64G2000G本地SSD所有es同一可用区3(ecs)Centos7master节点2C8G200G云SSD所有es同一可用区...
- 针对Linux内存管理知识学习总结
-
现在的服务器大部分都是运行在Linux上面的,所以,作为一个程序员有必要简单地了解一下系统是如何运行的。对于内存部分需要知道:地址映射内存管理的方式缺页异常先来看一些基本的知识,在进程看来,内存分为内...
- MySQL进阶之性能优化
-
概述MySQL的性能优化,包括了服务器硬件优化、操作系统的优化、MySQL数据库配置优化、数据库表设计的优化、SQL语句优化等5个方面的优化。在进行优化之前,需要先掌握性能分析的思路和方法,找出问题,...
- Linux Cgroups(Control Groups)原理
-
LinuxCgroups(ControlGroups)是内核提供的资源分配、限制和监控机制,通过层级化进程分组实现资源的精细化控制。以下从核心原理、操作示例和版本演进三方面详细分析:一、核心原理与...
- linux 常用性能优化参数及理解
-
1.优化内核相关参数配置文件/etc/sysctl.conf配置方法直接将参数添加进文件每条一行.sysctl-a可以查看默认配置sysctl-p执行并检测是否有错误例如设置错了参数:[roo...
- 如何在 Linux 中使用 Sysctl 命令?
-
sysctl是一个用于配置和查询Linux内核参数的命令行工具。它通过与/proc/sys虚拟文件系统交互,允许用户在运行时动态修改内核参数。这些参数控制着系统的各种行为,包括网络设置、文件...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- 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)