keycloak~网站对接到Keycloak的步骤

新网站对接到KC的部署

  1. kc的环境
  2. 向kc申请自己的客户端
  3. kc的登录接口
  4. 通过code换token接口
  5. 刷新token接口
  6. kc的用户信息接口
  7. kc的jwt token说明

1. kc的环境

测试环境:https://test-kc.xxx.com
预发布环境:https://pre-kc.xxx.com
生产环境:https://kc.xxx.com

2. 向kc申请自己的客户端

联系负责开发kc的同事,申请一个客户端,需要提供以下信息:

client_id: 客户端id
client_secret: 客户端密码

3. kc的登录接口

  • /auth/realms/{realm}/protocol/openid-connect/auth?client_id=client_id&response_type=code&redirect_uri=redirect_uri

  • 参数说明:

client_id: 客户端id
response_type: code
redirect_uri: 登录成功后的回调地址

4. 通过code换token接口

当你把第3步地址复制到浏览器后,会重写向到登录页,输入正确的用户名和密码后,提交后会重定向到来源页,带在地址上带着code码,这个code码是用来换取token的。

  • /auth/realms/{realm}/protocol/openid-connect/token
  • 请求方式:POST
  • 请求参数:
client_id: 客户端id
client_secret: 客户端密码
grant_type: authorization_code
code: 通过登录成功重写向后地址上带着的code
  • 返回参数:
{
    "access_token": "token",
    "expires_in": 1800,
    "refresh_expires_in": 1800,
    "refresh_token": "refresh_token",
    "token_type": "bearer"
}

5. 刷新token接口

通过第4步获取到合法的token后,token的有效期是30分钟,可以在kc上配置,如果过期了,需要通过刷新token接口获取新的token

  • /auth/realms/{realm}/protocol/openid-connect/token
  • 请求方式:POST
  • 请求参数:
client_id: 客户端id
client_secret: 客户端密码
grant_type: refresh_token
refresh_token: 通过第4步获取到的refresh_token
  • 返回参数:
{
    "access_token": "token",
    "expires_in": 1800,
    "refresh_expires_in": 1800,
    "refresh_token": "refresh_token",
    "token_type": "bearer"
}

6. kc的用户信息接口

通过第4步获取到的token,可以通过用户信息接口获取到用户的信息

  • /auth/realms/{realm}/protocol/openid-connect/userinfo
  • 请求方式:GET
  • 请求头:
Authorization Bearer token
  • 返回参数:
{
    "sub": "1",
    "email_verified": false,
    "name": "admin",
    "preferred_username": "admin",
    "given_name": "admin",
    "family_name": "admin",
    "email": "
}

kc的jwt-token字段说明

  • exp token过期时间戳
  • iat token生成时间戳
  • jti token的唯一身份标识,对接token_id或者refresh_token_id,这两个id在服务端会有存储,与它颁发的token里的jti相对应
  • iss token的发行机制,kc中的域,例如:https://kc.xxx.com/auth/realms/
  • aud 授权到的客户端
  • sub 当前用户ID
  • typ 认证方式
  • azp 当前客户端client_id
  • session_state 当前会话id,浏览器中的AUTH_SESSION_ID和AUTH_SESSION_ID_LEGACY
  • acr 如果clientSession通过cookie (SSO)进行身份验证,则使用0,否则为1
  • allowed-origins 允许哪种域名使用我们的token
  • realm_access 域的权限
  • resource_access 客户端(资源)权限,kc允许你为用户依照客户端去授权
  • scope 客户端模板,它将一类jwt中的属性进行分类,通过这个scope模块去渲染你的jwt字段
posted @ 2024-04-08 11:39  张占岭  阅读(265)  评论(0编辑  收藏  举报