Skip to content

Commit

Permalink
improve: select grant flows
Browse files Browse the repository at this point in the history
  • Loading branch information
samedii committed Dec 4, 2021
1 parent c1d3abb commit 9fe3b33
Show file tree
Hide file tree
Showing 13 changed files with 2,101 additions and 74 deletions.
11 changes: 3 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,33 +56,28 @@ fastapi-oidc + keycloak.
### Standard usage

```python3
from typing import Optional

from fastapi import Depends
from fastapi import FastAPI
from fastapi import Security
from fastapi import status

from fastapi_oidc import Auth
from fastapi_oidc import GrantType
from fastapi_oidc import KeycloakIDToken

auth = Auth(
openid_connect_url="http://localhost:8080/auth/realms/my-realm/.well-known/openid-configuration",
issuer="http://localhost:8080/auth/realms/my-realm", # optional, verification only
client_id="my-client", # optional, verification only
scopes=["email"], # optional, verification only
grant_types=[GrantType.IMPLICIT], # optional, docs only
idtoken_model=KeycloakIDToken, # optional, verification only
)

app = FastAPI(
title="Example",
version="dev",
dependencies=[Depends(auth.implicit_scheme)],
# multiple available schemes:
# - oidc_scheme (displays all schemes supported by the auth server in docs)
# - password_scheme
# - implicit_scheme
# - authcode_scheme
dependencies=[Depends(auth)],
)

@app.get("/protected")
Expand Down
26 changes: 13 additions & 13 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Easily used with authenticators such as:
- `Okta <https://www.okta.com/products/authentication/>`_


FastAPI's generated interactive documentation supports the grant flows
FastAPI's generated interactive documentation supports the grant types
``authorization_code``, ``implicit``, ``password`` and ``client_credentials``.

.. toctree::
Expand Down Expand Up @@ -46,33 +46,28 @@ Basic configuration for verifying OIDC tokens.

.. code-block:: python3
from typing import Optional
from fastapi import Depends
from fastapi import FastAPI
from fastapi import Security
from fastapi import status
from fastapi_oidc import Auth
from fastapi_oidc import GrantType
from fastapi_oidc import KeycloakIDToken
auth = Auth(
openid_connect_url="http://localhost:8080/auth/realms/my-realm/.well-known/openid-configuration",
issuer="http://localhost:8080/auth/realms/my-realm", # optional, verification only
client_id="my-client", # optional, verification only
scopes=["email"], # optional, verification only
grant_types=[GrantType.IMPLICIT], # optional, docs only
idtoken_model=KeycloakIDToken, # optional, verification only
)
app = FastAPI(
title="Example",
version="dev",
dependencies=[Depends(auth.implicit_scheme)],
# multiple available schemes:
# - oidc_scheme (displays all schemes supported by the auth server in docs)
# - password_scheme
# - implicit_scheme
# - authcode_scheme
dependencies=[Depends(auth)],
)
@app.get("/protected")
Expand All @@ -85,11 +80,16 @@ API Reference

Auth
----

.. automodule:: fastapi_oidc.auth
:members:

Types
------------
.. automodule:: fastapi_oidc.types
Grant Types
-----------
.. automodule:: fastapi_oidc.grant_types
:members:
:undoc-members:

IDToken Types
-------------
.. automodule:: fastapi_oidc.idtoken_types
:members:
Empty file added example/app/__init__.py
Empty file.
61 changes: 61 additions & 0 deletions example/app/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
from typing import Optional

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_oidc import Auth
from fastapi_oidc import KeycloakIDToken

auth = Auth(
openid_connect_url="http://localhost:8080/auth/realms/my-realm/.well-known/openid-configuration",
issuer="http://localhost:8080/auth/realms/my-realm", # optional, verification only
client_id="my-client", # optional, verification only
scopes=["email"], # optional, verification only
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)):
print(id_token)
return dict(message=f"You are {id_token.email}")


@app.get("/mixed")
def mixed(id_token: Optional[KeycloakIDToken] = Security(auth.optional)):
if id_token is None:
return dict(message="Welcome guest user!")
else:
return dict(message=f"Welcome {id_token.email}!")


if __name__ == "__main__":
uvicorn.run(
"example.main:cors", host="0.0.0.0", port=8000, loop="asyncio", reload=True
)
47 changes: 47 additions & 0 deletions example/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
version: '3'

services:

# test-fastapi-keycloak:
# build:
# context: .
# dockerfile: Dockerfile
# restart: always
# depends_on:
# - keycloak
# # keycloak:
# # condition: service_healthy
# network_mode: host

keycloak:
image: jboss/keycloak:15.0.2
volumes:
- ./my-realm-export.json:/tmp/my-realm-export.json
environment:
- DB_VENDOR=POSTGRES
- DB_ADDR=keycloak-postgres
- DB_DATABASE=keycloak
- DB_USER=keycloak
- DB_SCHEMA=public
- DB_PASSWORD=password
- KEYCLOAK_USER=admin
- KEYCLOAK_PASSWORD=admin
- KEYCLOAK_IMPORT=/tmp/my-realm-export.json
ports:
- 8080:8080
depends_on:
- keycloak-postgres
# healthcheck:
# test: ["CMD", "curl", "-f", "http://keycloak:8080"]
# interval: 10s
# timeout: 10s
# retries: 2

keycloak-postgres:
image: postgres:13.4-alpine3.14
volumes:
- ./data/keycloak-postgres:/var/lib/postgresql/data/
environment:
- POSTGRES_USER=keycloak
- POSTGRES_PASSWORD=password
- POSTGRES_DB=keycloak
Loading

0 comments on commit 9fe3b33

Please sign in to comment.