Skip to content

Commit

Permalink
Add support for PKCE
Browse files Browse the repository at this point in the history
  • Loading branch information
torbsto committed Mar 12, 2024
1 parent ecf55b7 commit 5bb4280
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 41 deletions.
7 changes: 6 additions & 1 deletion keycloak_oauth/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from typing import Any
import pydantic
from authlib.common.security import generate_token
from authlib.integrations.starlette_client import OAuth, StarletteOAuth2App
from authlib.jose import JWTClaims, JsonWebToken, JsonWebKey

Expand Down Expand Up @@ -28,6 +29,7 @@ def __init__(
base_url: str = "/",
logout_target: str = "/",
) -> None:
self.code_verifier = generate_token(48)
self._base_url = base_url
self._logout_page = logout_target
oauth = OAuth()
Expand All @@ -38,6 +40,7 @@ def __init__(
client_secret=client_secret,
server_metadata_url=server_metadata_url,
client_kwargs=client_kwargs,
code_challenge_method="S256",
)
assert isinstance(oauth.keycloak, StarletteOAuth2App)
self.keycloak = oauth.keycloak
Expand All @@ -62,7 +65,9 @@ async def login_page(
)
if next := request.query_params.get("next"):
redirect_uri = redirect_uri.include_query_params(next=next)
return await self.keycloak.authorize_redirect(request, redirect_uri)
return await self.keycloak.authorize_redirect(
request, redirect_uri, code_verifier=self.code_verifier
)

async def auth(self, request: Request) -> RedirectResponse:
"""Authorize user with Keycloak access token."""
Expand Down
80 changes: 40 additions & 40 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 5bb4280

Please sign in to comment.