Helper classes for keycloak authentication in Django and FastAPI
Project description
keycloak auth utils
Installation
1. Django/DRF
pip install git+https://github.com/ottuco/keycloak-auth-utils#egg=keycloak-utils[django]
2. FastAPI
pip install git+https://github.com/ottuco/keycloak-auth-utils#egg=keycloak-utils[fastapi]
Usage
1. Django/DRF
# authentication.py
from django.contrib.auth import get_user_model
from keycloak_utils.authentication.rest_framework import BaseDRFKCAuthentication
User = get_user_model()
class KeycloakDRFAuthentication(BaseDRFKCAuthentication):
kc_host = "http://localhost:8080"
kc_realm = "your-realm-nae"
kc_algorithms = ["RS256"]
kc_audience = "account"
def get_or_create_user(self, claims: dict):
# override this method to get or create user
# return User.objects.get_or_create(email=claims["email"])
return user_instance
# views.py
from rest_framework.views import APIView
class TestView(APIView):
authentication_classes = [KeycloakDRFAuthentication] # Add authentication class here
def get(self, request):
return Response({"message": "Hello, world!"})
2. FastAPI
# middlewares.py
import typing
from fastapi import Request
from keycloak_utils.authentication.fastapi import BaseFastAPIKCAuthentication
class AuthenticationMiddleware(BaseFastAPIKCAuthentication):
kc_host = "http://localhost:8080"
kc_realm = "your-realm-nae"
kc_algorithms = ["RS256"]
kc_audience = "account"
def post_process_claims(
self,
claims: typing.Optional[dict],
request: Request,
) -> Request:
# do something with `claims` here
return request
# main.py
from fastapi import FastAPI
app = FastAPI()
app.add_middleware(AuthenticationMiddleware) # Add middleware here
@app.get("/")
def read_root():
return {"Hello": "World"}
Test
# Install the dependencies
pip install .[test]
# Run tests
python -m pytest
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
keycloak-utils-0.0.1.tar.gz
(6.9 kB
view hashes)
Built Distribution
Close
Hashes for keycloak_utils-0.0.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9a834bad134361f2af0b7598f505888a19032c0758d66d43b4164d941a1255f9 |
|
MD5 | a2fb87fce010c8bd6207b47dd77ee6e1 |
|
BLAKE2b-256 | c2abca3af67d697a81991e2940a4a8790897b81512d8d651e8027c8a9103a5b2 |