网站首页 > 技术文章 正文
概述
本文演示网关层作为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
猜你喜欢
- 2024-11-26 学会IDEA REST Client后,postman就可以丢掉了...
- 2024-11-26 IntelliJ IDEA 自带的高能神器
- 2024-11-26 java 程序员如何更高效地测试接口?
- 2024-11-26 JWT 简介
- 2024-11-26 就在刚刚,马斯克 xAI 正式公测 xAI API,每天赠送 25 美元免费积分!
- 2024-11-26 用Postman测试需要授权的接口
- 2024-11-26 全面解读跨域身份验证方案——JWT
- 2024-11-26 Rest API的认证模式
- 2024-11-26 istio 1.10学习笔记13: 使用认证策略设置双向TLS和终端用户认证
- 2024-11-26 写给运维的Nginx秘籍
- 标签列表
-
- content-disposition (47)
- nth-child (56)
- math.pow (44)
- 原型和原型链 (63)
- canvas mdn (36)
- css @media (49)
- promise mdn (39)
- readasdataurl (52)
- if-modified-since (49)
- css ::after (50)
- border-image-slice (40)
- flex mdn (37)
- .join (41)
- function.apply (60)
- input type number (64)
- weakmap (62)
- js arguments (45)
- js delete方法 (61)
- blob type (44)
- math.max.apply (51)
- js (44)
- firefox 3 (47)
- cssbox-sizing (52)
- js删除 (49)
- js for continue (56)
- 最新留言
-