code-specialist / fastapi-keycloak

Keycloak integration for Python FastAPI
https://fastapi-keycloak.code-specialist.com/
Apache License 2.0
192 stars 49 forks source link

Object non evaluated on getting decoded_token from Keycloak #10

Closed germainlefebvre4 closed 2 years ago

germainlefebvre4 commented 2 years ago

How to reproduce ?

Env preparation.

pipenv install fastapi fastapi-keycloak

I followed your quickstart and full example instructions then :

pipenv run python main.py

What the result?

pipenv run python main.py 
Traceback (most recent call last):
  File "main.py", line 10, in <module>
    idp = FastAPIKeycloak(
  File "/home/germainlef/.local/share/virtualenvs/auth-keycloak-WIW7vmvr/lib/python3.8/site-packages/fastapi_keycloak/api.py", line 125, in __init__
    self._get_admin_token()  # Requests an admin access token on startup
  File "/home/germainlef/.local/share/virtualenvs/auth-keycloak-WIW7vmvr/lib/python3.8/site-packages/fastapi_keycloak/api.py", line 285, in _get_admin_token
    self.admin_token = response.json()['access_token']
  File "/home/germainlef/.local/share/virtualenvs/auth-keycloak-WIW7vmvr/lib/python3.8/site-packages/fastapi_keycloak/api.py", line 154, in admin_token
    if not decoded_token.get('resource_access').get('realm-management') or not decoded_token.get('resource_access').get('account'):
AttributeError: 'NoneType' object has no attribute 'get'
yannicschroeer commented 2 years ago

Mhh, that's weird. Seems like no token was issued. Did you save and import the realm-export.json as described in the docker compose yaml? I can't reproduce the error with the setup provided in the quickstart

germainlefebvre4 commented 2 years ago

Yes I created a brand new reals name Test and imported the file on realm creation.

My keycloak lives on port 8080 and my app on port 8081.

Docker images used:

Here is my docker-compose.yml:

version: '3'

networks:
  default:
    external: true
    name: maggiesfarm

services:
  db_keycloak:
    container_name: maggiesfarm_db_keycloak
    image: postgres:12
    volumes:
      - postgres_data:/var/lib/postgresql/data
    environment:
      POSTGRES_DB: keycloak
      POSTGRES_USER: keycloak
      POSTGRES_PASSWORD: password
  keycloak:
    container_name: maggiesfarm_keycloak
    image: jboss/keycloak:16.1.0
    # image: quay.io/keycloak/keycloak:latest
    command:
      - "-b 0.0.0.0 -Dkeycloak.profile.feature.upload_scripts=enabled"
    environment:
      DB_VENDOR: POSTGRES
      DB_ADDR: db_keycloak
      DB_DATABASE: keycloak
      DB_USER: keycloak
      DB_SCHEMA: public
      DB_PASSWORD: password
      KEYCLOAK_USER: admin
      KEYCLOAK_PASSWORD: password
      # Uncomment the line below if you want to specify JDBC parameters. The parameter below is just an example, and it shouldn't be used in production without knowledge. It is highly recommended that you read the PostgreSQL JDBC driver documentation in order to use it.
      #JDBC_PARAMS: "ssl=true"
    ports:
      - 8080:8080
    depends_on:
      - db_keycloak

volumes:
  postgres_data:
      driver: local

Somethin weird appeared on first keycloak login by fastapi and I needed to regenerate the "Client" secret and reported its new value in code:

app = FastAPI()
idp = FastAPIKeycloak(
    server_url="http://localhost:8080/auth",
    client_id="test-client",
    client_secret="z9vH17vqCWhngPj3IIEK5fTfePAdkR6e", # <<< new generated token for test-client
    admin_client_secret="hwBLV11xaGvkeQ24xLLzsASNFNPri9t4", # <<< new generated token for admin-cli
    realm="Test",
    callback_uri="http://localhost:8081/callback"
)
germainlefebvre4 commented 2 years ago

Before this step, with the intial copy/paste from your doc I had:

Traceback (most recent call last):
  File "/home/germainlef/.local/share/virtualenvs/auth-keycloak-WIW7vmvr/lib/python3.8/site-packages/fastapi_keycloak/api.py", line 285, in _get_admin_token
    self.admin_token = response.json()['access_token']
KeyError: 'access_token'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "try_fastapi-keycloak.py", line 10, in <module>
    idp = FastAPIKeycloak(
  File "/home/germainlef/.local/share/virtualenvs/auth-keycloak-WIW7vmvr/lib/python3.8/site-packages/fastapi_keycloak/api.py", line 125, in __init__
    self._get_admin_token()  # Requests an admin access token on startup
  File "/home/germainlef/.local/share/virtualenvs/auth-keycloak-WIW7vmvr/lib/python3.8/site-packages/fastapi_keycloak/api.py", line 289, in _get_admin_token
    raise KeycloakError(reason=f"The response did not contain an access_token: {response.json()}", status_code=403)
fastapi_keycloak.exceptions.KeycloakError: HTTP 403: The response did not contain an access_token: {'error': 'unauthorized_client', 'error_description': 'Invalid client secret'}

That's why I regerated the token

yannicschroeer commented 2 years ago

Please try to alter your docker compose yaml as follows:

volumes:
      - ./realm-export.json:/opt/jboss/keycloak/imports/realm-export.json
command:
      - "-b 0.0.0.0 -Dkeycloak.profile.feature.upload_scripts=enabled -Dkeycloak.import=/opt/jboss/keycloak/imports/realm-export.json"

You currently do not bind or import the config files. If you do not want to use our predefined config, please alter your realms admin-cli client:

as described in keycloak configuration.


However, thanks for opening this issue. It clearly shows that the error messages need a lot of improvement regarding explicity and exception handling in general.

germainlefebvre4 commented 2 years ago

Okey!!! I missed something... my bad

Service Accounts Roles was added to test-client instead of admin-cli.

jonra1993 commented 2 years ago

Thanks, @germainlefebvre4 I had the same error. These are the configurations required on admin-cli

image image
germainlefebvre4 commented 2 years ago

Absolutly!

I have scripted this part to avoid hands mistakes