Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/livioribeiro/fastapi-resource-server
Authenticate FastAPI with OIDC discovery
https://github.com/livioribeiro/fastapi-resource-server
authentication fastapi oidc python web
Last synced: about 1 month ago
JSON representation
Authenticate FastAPI with OIDC discovery
- Host: GitHub
- URL: https://github.com/livioribeiro/fastapi-resource-server
- Owner: livioribeiro
- License: mit
- Created: 2021-05-27T17:22:43.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2021-05-28T13:36:52.000Z (over 3 years ago)
- Last Synced: 2024-03-14T13:02:22.140Z (9 months ago)
- Topics: authentication, fastapi, oidc, python, web
- Language: Python
- Homepage:
- Size: 6.84 KB
- Stars: 21
- Watchers: 4
- Forks: 3
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# FastAPI Resource Server
Build an OIDC resource server using FastAPI.
Your aplication receives the claims decoded from the access token.
# Usage
Run keycloak on port 8888:
```sh
docker container run --name auth-server -d -p 8888:8080 \
-e KEYCLOAK_USER=admin -e KEYCLOAK_PASSWORD=admin \
jboss/keycloak:latest
```Install dependencies
```sh
pip install fastapi fastapi_resource_server uvicorn
```Create the main.py module
```python
from fastapi import Depends, FastAPI, Security
from pydantic import BaseModelfrom fastapi_resource_server import JwtDecodeOptions, OidcResourceServer
app = FastAPI()
decode_options = JwtDecodeOptions(verify_aud=False)
auth_scheme = OidcResourceServer(
"http://localhost:8888/auth/realms/master",
scheme_name="Keycloak",
jwt_decode_options=decode_options,
)class User(BaseModel):
username: str
given_name: str
family_name: str
email: strdef get_current_user(claims: dict = Security(auth_scheme)):
claims.update(username=claims["preferred_username"])
user = User.parse_obj(claims)
return user@app.get("/users/me")
def read_current_user(current_user: User = Depends(get_current_user)):
return current_user
```Run the application
```sh
uvicorn main:app
```