How to connect fastapi to Redhat SSO (Keycloak) OpenID Connect OIDC

118 views Asked by At

I have the next code triyng to authenticate my fastapi vs redhat sso:

import uvicorn
from fastapi import Depends
from fastapi import FastAPI
from fastapi import Security
from fastapi import status
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import RedirectResponse

from fastapi_third_party_auth import Auth
from fastapi_third_party_auth import KeycloakIDToken


auth = Auth(
  openid_connect_url="https://XXXXX/auth/realms/Sandbox/.well-known/openid-configuration",
  issuer="https://XXXX/auth/realms/Sandbox",  # optional, verification only
  client_id="devops-tool",  # optional, verification only
  #scopes=["email", "openid"],  # optional, verification only
  #grant_types=[GrantType.IMPLICIT],  # optional, docs only
  grant_types=["authorization_code"],
  #grant_types=["client_credentials"]
  #idtoken_model=KeycloakIDToken,  # optional, verification only
)


app = FastAPI(
    title="Example",
    version="dev",
    dependencies=[Depends(auth)],
)

# CORS errors instead of seeing internal exceptions
# https://stackoverflow.com/questions/63606055/why-do-i-get-cors-error-reason-cors-request-did-not-succeed
#cors = CORSMiddleware(
#    app=app,
#    allow_origins=["*"],
#    allow_credentials=True,
#    allow_methods=["*"],
#    allow_headers=["*"],
#)


@app.get("/", status_code=status.HTTP_303_SEE_OTHER)
def redirect_to_docs():
    return RedirectResponse(url="/docs")


@app.get("/protected")
def protected(id_token: KeycloakIDToken = Security(auth.required)):
    return dict(message=f"You are {id_token}")

This code is functioning with the implicit grant type.

However, when I attempted to switch to the authorization code grant type, I encountered the error message "Missing parameter: code_challenge_method."

Despite searching, I was unable to locate an option to specify the code_challenge_method. Consequently, I tried disabling PKCE (Proof Key for Code Exchange), but this resulted in a new error:

{"error":"invalid_request","error_description":"Missing parameter: username"}

0

There are 0 answers