keycloak-utils 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
File without changes
@@ -0,0 +1,56 @@
1
+ import typing
2
+
3
+ from fastapi import Request, Response
4
+ from fastapi.responses import JSONResponse
5
+ from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
6
+
7
+ from ..backend.fastapi import FastAPIKeycloakAuthBackend
8
+
9
+
10
+ class BaseFastAPIKCAuthentication(BaseHTTPMiddleware):
11
+ backend = FastAPIKeycloakAuthBackend
12
+
13
+ def __init__(
14
+ self,
15
+ host: typing.Optional[str] = None,
16
+ realm: typing.Optional[str] = None,
17
+ algorithms: typing.Optional[list[str]] = None,
18
+ audience: typing.Optional[str] = None,
19
+ *args,
20
+ **kwargs,
21
+ ):
22
+ super().__init__(*args, **kwargs)
23
+ self.host = host or self.kc_host
24
+ self.realm = realm or self.kc_realm
25
+ self.algorithms = algorithms or self.kc_algorithms
26
+ self.audience = audience or self.kc_audience
27
+
28
+ def authenticate(self, request: Request) -> typing.Optional[dict]:
29
+ backend = self.backend(
30
+ request=request,
31
+ host=self.host,
32
+ realm=self.realm,
33
+ algorithms=self.algorithms,
34
+ audience=self.audience,
35
+ )
36
+ return backend.authenticate()
37
+
38
+ def post_process_claims(
39
+ self,
40
+ claims: typing.Optional[dict],
41
+ request: Request,
42
+ ) -> Request:
43
+ return request
44
+
45
+ async def dispatch(
46
+ self,
47
+ request: Request,
48
+ call_next: RequestResponseEndpoint,
49
+ ) -> Response:
50
+ try:
51
+ claims = self.authenticate(request=request)
52
+ except self.backend.AuthError as e:
53
+ return JSONResponse(status_code=401, content={"detail": str(e)})
54
+ request = self.post_process_claims(claims=claims, request=request)
55
+ response = await call_next(request)
56
+ return response
@@ -0,0 +1,49 @@
1
+ import typing
2
+
3
+ from django.contrib.auth import get_user_model
4
+ from rest_framework.authentication import BaseAuthentication as DRFBaseAuth
5
+ from rest_framework.exceptions import AuthenticationFailed
6
+ from rest_framework.request import Request
7
+
8
+ from ..backend.rest_framework import DRFKeycloakAuthBackend
9
+
10
+ User = get_user_model()
11
+
12
+
13
+ class BaseDRFKCAuthentication(DRFBaseAuth):
14
+ kc_host: str
15
+ kc_realm: str
16
+ kc_algorithms: list[str]
17
+ kc_audience: str
18
+
19
+ keyword = "Bearer"
20
+ backend = DRFKeycloakAuthBackend
21
+ AuthFailedError: Exception = AuthenticationFailed
22
+
23
+ def get_or_create_user(self, claims: dict) -> User:
24
+ raise NotImplementedError
25
+
26
+ def authenticate(
27
+ self,
28
+ request: Request,
29
+ ) -> typing.Optional[typing.Tuple[User, None]]:
30
+ try:
31
+ backend = self.backend(
32
+ request,
33
+ host=self.kc_host,
34
+ realm=self.kc_realm,
35
+ algorithms=self.kc_algorithms,
36
+ audience=self.kc_audience,
37
+ )
38
+ claims = backend.authenticate()
39
+ except self.backend.AuthError as e:
40
+ raise self.AuthFailedError(e.msg)
41
+
42
+ if not claims:
43
+ return None
44
+
45
+ user = self.get_or_create_user(claims=claims)
46
+ return user, None
47
+
48
+ def authenticate_header(self, request) -> str:
49
+ return self.keyword
File without changes
@@ -0,0 +1,95 @@
1
+ import typing
2
+
3
+ from ..errors import JWTDecodeError, KeycloakError
4
+ from ..verifier.base import BaseTokenVerifier
5
+
6
+
7
+ def _safe_decode(s: typing.Union[bytes, str]) -> str:
8
+ try:
9
+ return s.decode()
10
+ except AttributeError:
11
+ return s
12
+
13
+
14
+ class BaseKCAuthBackend:
15
+ kc_host: str
16
+ kc_realm: str
17
+ kc_algorithms: list[str]
18
+ kc_audience: str
19
+
20
+ verifier: typing.Type[BaseTokenVerifier]
21
+ AuthError = KeycloakError
22
+ token_type = "Bearer"
23
+
24
+ def __init__(
25
+ self,
26
+ request,
27
+ host: typing.Optional[str] = None,
28
+ realm: typing.Optional[str] = None,
29
+ algorithms: typing.Optional[list[str]] = None,
30
+ audience: typing.Optional[str] = None,
31
+ *args,
32
+ **kwargs,
33
+ ):
34
+ self.request = request
35
+ self.kc_host = host or self.kc_host
36
+ self.kc_realm = realm or self.kc_realm
37
+ self.kc_algorithms = algorithms or self.kc_algorithms
38
+ self.kc_audience = audience or self.kc_audience
39
+
40
+ def get_auth_header(self) -> bytes:
41
+ try:
42
+ # Django/DRF
43
+ return self.request.META.get("HTTP_AUTHORIZATION", b"")
44
+ except AttributeError:
45
+ # FastAPI
46
+ return self.request.headers.get("Authorization", b"")
47
+
48
+ def validate_auth_headers(self) -> typing.Optional[str]:
49
+ headers = self.get_auth_header().split()
50
+ if len(headers) == 0:
51
+ return None
52
+ elif len(headers) == 1:
53
+ msg = "Invalid token header. No credentials provided."
54
+ raise self.AuthError(msg)
55
+ elif len(headers) > 2:
56
+ msg = "Invalid token header. Token string should not contain spaces."
57
+ raise self.AuthError(msg)
58
+
59
+ token_type, token = headers
60
+ # decode
61
+ token_type, token = _safe_decode(token_type), _safe_decode(token)
62
+ if token_type.lower() != self.token_type.lower():
63
+ msg = "Invalid token type. Token type should be Bearer."
64
+ raise self.AuthError(msg)
65
+
66
+ return token
67
+
68
+ def post_authenticate_hooks(self, claims: dict) -> dict:
69
+ """
70
+ This method is called after obtaining the claims from the token.
71
+ """
72
+ return claims
73
+
74
+ def verify_access_token(self, token: str) -> dict:
75
+ try:
76
+ verifier = self.verifier(
77
+ access_token=token,
78
+ host=self.kc_host,
79
+ realm=self.kc_realm,
80
+ algorithms=self.kc_algorithms,
81
+ audience=self.kc_audience,
82
+ )
83
+ claims = verifier.get_claims()
84
+ return self.post_authenticate_hooks(claims)
85
+ except JWTDecodeError as e:
86
+ raise self.AuthError(e)
87
+
88
+ def authenticate(self) -> typing.Optional[dict]:
89
+ token = self.validate_auth_headers()
90
+ if not token:
91
+ # Could not find token in headers,
92
+ # maybe some other authentication method is used
93
+ return None
94
+
95
+ return self.verify_access_token(token=token)
@@ -0,0 +1,6 @@
1
+ from ..verifier.fastapi import FastAPITokenVerifier
2
+ from .base import BaseKCAuthBackend
3
+
4
+
5
+ class FastAPIKeycloakAuthBackend(BaseKCAuthBackend):
6
+ verifier = FastAPITokenVerifier
@@ -0,0 +1,6 @@
1
+ from ..verifier.rest_framework import DjangoTokenVerifier
2
+ from .base import BaseKCAuthBackend
3
+
4
+
5
+ class DRFKeycloakAuthBackend(BaseKCAuthBackend):
6
+ verifier = DjangoTokenVerifier
@@ -0,0 +1,31 @@
1
+ class KeyCloakBaseError(Exception):
2
+ """
3
+ Base class for all Keycloak errors
4
+ """
5
+
6
+ def __init__(self, msg, *args, **kwargs):
7
+ self.msg = msg
8
+
9
+ def __str__(self):
10
+ return str(self.msg)
11
+
12
+ def __repr__(self):
13
+ return f"{self.__class__.__name__}({self})"
14
+
15
+
16
+ class KeycloakError(KeyCloakBaseError):
17
+ """
18
+ Base class for all Keycloak errors
19
+ """
20
+
21
+
22
+ class PublicKeyNotFound(KeycloakError):
23
+ """
24
+ Base class for all Keycloak errors
25
+ """
26
+
27
+
28
+ class JWTDecodeError(KeycloakError):
29
+ """
30
+ Error while decoding the JWT token
31
+ """
File without changes
@@ -0,0 +1,57 @@
1
+ import typing
2
+ from functools import lru_cache
3
+
4
+ import requests
5
+
6
+ from ..errors import PublicKeyNotFound
7
+
8
+
9
+ class BasePublicKeyManager:
10
+ ttl: int = 60 * 60 * 24 # 1 day
11
+ host: str
12
+ realm: str
13
+
14
+ def __init__(
15
+ self,
16
+ host: typing.Optional[str] = None,
17
+ realm: typing.Optional[str] = None,
18
+ ):
19
+ self.host = host or ""
20
+ self.realm = realm or ""
21
+
22
+ @property
23
+ def url_realm(self) -> str:
24
+ return f"{self.host}/auth/realms/{self.realm}"
25
+
26
+ def get_fresh_key_from_upstream(self) -> str:
27
+ response = requests.get(self.url_realm)
28
+ if response.status_code != 200:
29
+ raise PublicKeyNotFound("Keycloak public key not found")
30
+ return response.json().get("public_key")
31
+
32
+ def get_fresh_pem_key(self) -> str:
33
+ key = self.get_fresh_key_from_upstream()
34
+ return f"-----BEGIN PUBLIC KEY-----\n{key}\n-----END PUBLIC KEY-----"
35
+
36
+ def clear_cache(self, *args, **kwargs):
37
+ self.get_key_from_cache.cache_clear()
38
+
39
+ @lru_cache
40
+ def get_key_from_cache(self, *args, **kwargs) -> typing.Optional[str]:
41
+ return self.get_fresh_pem_key()
42
+
43
+ def set_key(self, key: str, *args, **kwargs) -> str:
44
+ ...
45
+
46
+ def get_or_set_key(self, *args, **kwargs) -> str:
47
+ key = self.get_key_from_cache(*args, **kwargs)
48
+ if key:
49
+ return key
50
+ key = self.get_fresh_pem_key()
51
+ self.set_key(key, *args, **kwargs)
52
+ return key
53
+
54
+ def get_key(self, force: bool = False, *args, **kwargs) -> str:
55
+ if force:
56
+ self.clear_cache(*args, **kwargs)
57
+ return self.get_or_set_key(*args, **kwargs)
@@ -0,0 +1,5 @@
1
+ from .base import BasePublicKeyManager
2
+
3
+
4
+ class FastAPIKeyManager(BasePublicKeyManager):
5
+ ...
@@ -0,0 +1,19 @@
1
+ import typing
2
+
3
+ from django.core.cache import cache
4
+
5
+ from .base import BasePublicKeyManager
6
+
7
+
8
+ class DjangoKeyManager(BasePublicKeyManager):
9
+ cache_key = "keycloak_public_key"
10
+
11
+ def set_key(self, key: str, *args, **kwargs) -> str:
12
+ cache.set(self.cache_key, key, timeout=self.ttl)
13
+ return key
14
+
15
+ def clear_cache(self, *args, **kwargs):
16
+ ...
17
+
18
+ def get_key_from_cache(self, *args, **kwargs) -> typing.Optional[str]:
19
+ return cache.get(self.cache_key)
@@ -0,0 +1,23 @@
1
+ import jwt
2
+
3
+ from .errors import JWTDecodeError
4
+
5
+
6
+ def verify_token(
7
+ access_token: str,
8
+ public_key: str,
9
+ algorithms: list[str],
10
+ audience: str,
11
+ ) -> dict:
12
+ """
13
+ Verifies a token with Keycloak and returns the validated claims
14
+ """
15
+ try:
16
+ return jwt.decode(
17
+ access_token,
18
+ key=public_key,
19
+ algorithms=algorithms,
20
+ audience=audience,
21
+ )
22
+ except jwt.InvalidTokenError as e:
23
+ raise JWTDecodeError(str(e))
File without changes
@@ -0,0 +1,37 @@
1
+ import typing
2
+ from functools import lru_cache
3
+
4
+ from ..manager.base import BasePublicKeyManager
5
+ from ..utils import verify_token
6
+
7
+
8
+ class BaseTokenVerifier:
9
+ manager: typing.Type[BasePublicKeyManager]
10
+
11
+ def __init__(
12
+ self,
13
+ access_token: str,
14
+ host: str,
15
+ realm: str,
16
+ algorithms: list[str],
17
+ audience: str,
18
+ ):
19
+ self.access_token = access_token
20
+ self.host = host
21
+ self.realm = realm
22
+ self.algorithms = algorithms
23
+ self.audience = audience
24
+
25
+ @lru_cache
26
+ def get_claims(self, force=False, *args, **kwargs) -> dict:
27
+ """
28
+ Verify the token using Public Key
29
+ """
30
+ manager = self.manager(host=self.host, realm=self.realm)
31
+ public_key = manager.get_key(force=force)
32
+ return verify_token(
33
+ access_token=self.access_token,
34
+ public_key=public_key,
35
+ algorithms=self.algorithms,
36
+ audience=self.audience,
37
+ )
@@ -0,0 +1,6 @@
1
+ from ..manager.fastapi import FastAPIKeyManager
2
+ from .base import BaseTokenVerifier
3
+
4
+
5
+ class FastAPITokenVerifier(BaseTokenVerifier):
6
+ manager = FastAPIKeyManager
@@ -0,0 +1,6 @@
1
+ from ..manager.rest_framework import DjangoKeyManager
2
+ from .base import BaseTokenVerifier
3
+
4
+
5
+ class DjangoTokenVerifier(BaseTokenVerifier):
6
+ manager = DjangoKeyManager
@@ -0,0 +1,137 @@
1
+ Metadata-Version: 2.1
2
+ Name: keycloak-utils
3
+ Version: 0.0.1
4
+ Summary: Helper classes for keycloak authentication in Django and FastAPI
5
+ Author-email: Jerin Peter George <jerinpetergeorge@gmail.com>
6
+ Project-URL: Homepage, https://github.com/jerinpetergeorge/keycloak-auth-utils
7
+ Classifier: Environment :: Web Environment
8
+ Classifier: Environment :: Console
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python
12
+ Classifier: Programming Language :: Python :: 3.7
13
+ Classifier: Programming Language :: Python :: 3.8
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Topic :: Utilities
17
+ Requires-Python: >=3.7
18
+ Description-Content-Type: text/markdown
19
+ Requires-Dist: requests (<2.31.0)
20
+ Requires-Dist: pyjwt[crypto] (<2.7.0)
21
+ Provides-Extra: all
22
+ Requires-Dist: keycloak-utils[django,fastapi] ; extra == 'all'
23
+ Provides-Extra: dev
24
+ Requires-Dist: keycloak-utils[lint-and-formatting,test] ; extra == 'dev'
25
+ Provides-Extra: django
26
+ Requires-Dist: djangorestframework (>=3.12.0) ; extra == 'django'
27
+ Provides-Extra: fastapi
28
+ Requires-Dist: fastapi (>=0.68.0) ; extra == 'fastapi'
29
+ Provides-Extra: fastapi-test
30
+ Requires-Dist: fastapi[test] (>=0.68.0) ; extra == 'fastapi-test'
31
+ Provides-Extra: lint-and-formatting
32
+ Requires-Dist: black ; extra == 'lint-and-formatting'
33
+ Requires-Dist: flake8 ; extra == 'lint-and-formatting'
34
+ Requires-Dist: flake8-print ; extra == 'lint-and-formatting'
35
+ Requires-Dist: isort ; extra == 'lint-and-formatting'
36
+ Requires-Dist: pre-commit ; extra == 'lint-and-formatting'
37
+ Provides-Extra: test
38
+ Requires-Dist: keycloak-utils[django,fastapi-test] ; extra == 'test'
39
+ Requires-Dist: pytest-django (~=4.5.2) ; extra == 'test'
40
+
41
+ # keycloak auth utils
42
+
43
+ ## Installation
44
+
45
+ ### 1. Django/DRF
46
+
47
+ ```bash
48
+ pip install git+https://github.com/ottuco/keycloak-auth-utils#egg=keycloak-utils[django]
49
+ ```
50
+
51
+ ### 2. FastAPI
52
+
53
+ ```bash
54
+ pip install git+https://github.com/ottuco/keycloak-auth-utils#egg=keycloak-utils[fastapi]
55
+ ````
56
+
57
+ ## Usage
58
+
59
+ ### 1. Django/DRF
60
+
61
+ ```python
62
+ # authentication.py
63
+ from django.contrib.auth import get_user_model
64
+ from keycloak_utils.authentication.rest_framework import BaseDRFKCAuthentication
65
+
66
+ User = get_user_model()
67
+
68
+
69
+ class KeycloakDRFAuthentication(BaseDRFKCAuthentication):
70
+ kc_host = "http://localhost:8080"
71
+ kc_realm = "your-realm-nae"
72
+ kc_algorithms = ["RS256"]
73
+ kc_audience = "account"
74
+
75
+ def get_or_create_user(self, claims: dict):
76
+ # override this method to get or create user
77
+ # return User.objects.get_or_create(email=claims["email"])
78
+ return user_instance
79
+
80
+
81
+ # views.py
82
+ from rest_framework.views import APIView
83
+
84
+ class TestView(APIView):
85
+ authentication_classes = [KeycloakDRFAuthentication] # Add authentication class here
86
+
87
+ def get(self, request):
88
+ return Response({"message": "Hello, world!"})
89
+ ```
90
+
91
+ ### 2. FastAPI
92
+
93
+ ```python
94
+ # middlewares.py
95
+ import typing
96
+
97
+ from fastapi import Request
98
+ from keycloak_utils.authentication.fastapi import BaseFastAPIKCAuthentication
99
+
100
+
101
+ class AuthenticationMiddleware(BaseFastAPIKCAuthentication):
102
+ kc_host = "http://localhost:8080"
103
+ kc_realm = "your-realm-nae"
104
+ kc_algorithms = ["RS256"]
105
+ kc_audience = "account"
106
+
107
+ def post_process_claims(
108
+ self,
109
+ claims: typing.Optional[dict],
110
+ request: Request,
111
+ ) -> Request:
112
+ # do something with `claims` here
113
+ return request
114
+
115
+
116
+ # main.py
117
+ from fastapi import FastAPI
118
+
119
+ app = FastAPI()
120
+
121
+ app.add_middleware(AuthenticationMiddleware) # Add middleware here
122
+
123
+
124
+ @app.get("/")
125
+ def read_root():
126
+ return {"Hello": "World"}
127
+
128
+ ```
129
+ ## Test
130
+
131
+ ```bash
132
+ # Install the dependencies
133
+ pip install .[test]
134
+
135
+ # Run tests
136
+ python -m pytest
137
+ ```
@@ -0,0 +1,22 @@
1
+ keycloak_utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ keycloak_utils/errors.py,sha256=yuJT64jDvN6Or_HLGXUtuFW37tYw8YP1CQcFAIl4R4U,579
3
+ keycloak_utils/utils.py,sha256=0H5d9hS3c6eO9F_wyP0KpZqbONATFhrlx9H0apc4xRU,494
4
+ keycloak_utils/authentication/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ keycloak_utils/authentication/fastapi.py,sha256=5Q7sB1f_noddcsf1uQRCh36Zy800KZP3Hg25lbUWFCU,1761
6
+ keycloak_utils/authentication/rest_framework.py,sha256=-qs3Ywa7vqu04AR2ZvW17IAjcMf1fS4-94ybKXhhTMw,1371
7
+ keycloak_utils/backend/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ keycloak_utils/backend/base.py,sha256=uhTAbI5aiDq6bnu9v-LwRc6dl0DDS94HFEENLnMQWag,2992
9
+ keycloak_utils/backend/fastapi.py,sha256=SZ1mhJB0L-cvKuHsB66Fx7fX-0Y3Z8yKanFNtgDhxxM,179
10
+ keycloak_utils/backend/rest_framework.py,sha256=QH0asqxUn9sbGtr-punRSY31l6skg1ykeyJPrZ55OGQ,180
11
+ keycloak_utils/manager/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ keycloak_utils/manager/base.py,sha256=h8jxH-twnL0O5MvHSX9kZygCJSyfjFzcJkQgE30FBmk,1644
13
+ keycloak_utils/manager/fastapi.py,sha256=TSh4iuKWFyC2_oTlVwFU6Rgn7I0Xn-oHFm_zojrsqhA,96
14
+ keycloak_utils/manager/rest_framework.py,sha256=a2JZi0VUrIj5B1hFvdyU6-FjZWT7c0UciFEAk7UZPZU,485
15
+ keycloak_utils/verifier/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ keycloak_utils/verifier/base.py,sha256=OWpxrt_6bZ_ET4g1q5Sjx074OJiZ-MM7fClMYZD_A9s,980
17
+ keycloak_utils/verifier/fastapi.py,sha256=hQgrbJ7KY-cEPB5tHvDN7juUAOHVXRchN6xLFOvEnPE,165
18
+ keycloak_utils/verifier/rest_framework.py,sha256=UqSL1QLavG3xAwZB8Z8Ubu9eHs93q2zHzoko86hvOTo,169
19
+ keycloak_utils-0.0.1.dist-info/METADATA,sha256=pENT1L0hwL_eLLrmZ1PkFoWMbEw9vKTnuGsstGtQiZ8,3744
20
+ keycloak_utils-0.0.1.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92
21
+ keycloak_utils-0.0.1.dist-info/top_level.txt,sha256=audYEg09zM65NAEVBvY5eS0xSfclGb1BilPvYMLWv0Q,15
22
+ keycloak_utils-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.40.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ keycloak_utils