1. Preface

  • docker pull keycloak/keycloak:23.0.7

  • Microservice Cloud Gateway OAuth2 Keycloak

  • Keycloak Authorization Server

  • Spring Cloud Gateway Api Gateway:
    OAuth2 Client and OAuth2 Resource Server

  • Two Boot Business Microservice

  • 对任何请求,将在转发到下游服务前验证访问令牌access token,
    对任何未经身份验证unauthenticated的请求,都会使用Keycloak
    初始化授权码流程initialize authorization code flow

2. 启动Keycloak

  • 请先参考MySQL镜像(参考MySQL.adoc):192.168.0.123:3306/elf

  • root - cipher,elf_user - elf_cipher

  • -e KC_DB_URL=jdbc:mysql://192.168.0.123:3306/keycloak

  • 访问Keycloak:http://192.168.0.123:18080/admin,
    admin - admin

  • 或http://192.168.0.123:18080,点击Administration Console

docker run \
	--name keycloak \
	-p 18080:8080 \
	--privileged=true \
	--net network-common \
	-e KEYCLOAK_ADMIN=admin \
	-e KEYCLOAK_ADMIN_PASSWORD=admin \
	-e KC_DB=mysql \
	-e KC_DB_URL=jdbc:mysql://mysql:3306/keycloak \
	-e KC_DB_USERNAME=root \
	-e KC_DB_PASSWORD=cipher \
	-itd keycloak/keycloak:23.0.7 start-dev

3. 配置Keycloak

  • 创建名为elf的新的realm,也可导入json文件,此文件包含此realm的所有配置,
    而非手动配置,参考realm-export.json,此处使用手动配置方式;

01CreateRealm
  • 在elf realm下创建oidc客户端:spring-with-test-scope,
    应启用客户端身份认证,Valid Redirect URI:*

  • 创建完客户端后,点击Credential Tab,选择Client Authenticator,
    复制Client Secret:riJEmHGVr0kvBSgTFRzZfJY5dhpBwc1A

02CreateOidcClientA
02CreateOidcClientB
02CreateOidcClientC
02CreateOidcClientD
  • 创建名为cs-elf的client scope,
    并将cs-elf添加到客户端spring-with-test-scope

03CreateClientScope
04AddClientScopeToClient
  • 还需创建用户来针对Keycloak进行身份认证,用户名为elf-user,
    创建用户后,选择Credential Tab来设置密码,密码为elf-cipher;

05CreateUserA
05CreateUserB
  • 完成配置后,可将其导出为realm-export.json文件,创建新realm时可使用此文件,
    此文件很有用,如可使用Testcontainers来构建自动化测试;

06ExportRealmElf
  • 很遗憾,Keycloak并没将realm user列表导出到此文件,我们需手动添加到json;

{
	"username": "elf-user",
	"email": "",
	"firstName": "",
	"lastName": "",
	"enabled": true,
	"credentials": [{
		"type": "password",
		"value": "elf-cipher"
	}],
	"realmRoles": [
		"default-roles-elf",
		"USER"
	]
}