- 首先需要使用Keycloak Admin API获取access token和refresh token。
- 在本地设置一个路由,用于在每次请求时验证refresh token。
- 在路由的处理程序中,使用Keycloak提供的jwt.decode()方法对refresh token进行解码并验证。
- 如果token未过期,则通过使用Keycloak提供的Token Endpoint来获取新的access token和refresh token。
代码示例:
import jwt
import requests
# 获取access token和refresh token
def get_tokens():
url = "https://your-keycloak-url/auth/realms/your-realm/protocol/openid-connect/token"
data = {
"grant_type": "password",
"client_id": "your-client-id",
"username": "your-username",
"password": "your-password"
}
response = requests.post(url, data=data)
tokens = response.json()
access_token = tokens["access_token"]
refresh_token = tokens["refresh_token"]
return access_token, refresh_token
# 验证refresh token是否有效
def verify_refresh_token(refresh_token):
public_key_url = "https://your-keycloak-url/auth/realms/your-realm/protocol/openid-connect/certs"
response = requests.get(public_key_url)
public_key = response.json()["keys"][0]["x5c"][0]
try:
decoded_token = jwt.decode(refresh_token, public_key, algorithms=["RS256"], audience="your-client-id")
return decoded_token.get("exp") > time.time()
except:
return False
# 获取新的access token和refresh token
def refresh_tokens(refresh_token):
url = "https://your-keycloak-url/auth/realms/your-realm/protocol/openid-connect/token"
data = {
"grant_type": "refresh_token",
"client_id": "your-client-id",
"refresh_token": refresh_token
}
response = requests.post(url, data=data)
tokens = response.json()
access_token = tokens["access_token"]
refresh_token = tokens["refresh_token"]
return access_token, refresh_token
# 路由处理程序
def refresh_token_handler():