@giovanny.lueilwitz
To use a refresh token with Keycloak and FastAPI, you can follow these steps:
- Obtain a refresh token: First, you need to obtain a refresh token from Keycloak by authenticating the user and receiving an access token and a refresh token.
- Set up Keycloak with FastAPI: You need to set up Keycloak with FastAPI by using the Keycloak library for Python. You can install the library using pip:
- Create a Keycloak client: Next, you need to create a Keycloak client in your FastAPI application to interact with Keycloak. You can create a client like this:
1
2
3
4
5
6
|
from keycloak import KeycloakOpenID
keycloak_openid = KeycloakOpenID(server_url="https://<keycloak-server>/auth/",
client_id="<client-id>",
realm_name="realm-name",
client_secret_key="<client-secret>")
|
- Use the refresh token: Once you have obtained the refresh token and set up the Keycloak client, you can use the refresh token to get a new access token. You can do this by calling the refresh_token method on the Keycloak client:
1
|
new_token = keycloak_openid.refresh_token(refresh_token="<refresh-token>")
|
- Validate the new access token: Finally, you can validate the new access token by calling the introspect method on the Keycloak client:
1
|
token_info = keycloak_openid.introspect(token=new_token['access_token'])
|
By following these steps, you can use a refresh token with Keycloak and FastAPI to authenticate users and obtain new access tokens.