keycloak-utils 0.0.1__tar.gz
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.
- keycloak-utils-0.0.1/PKG-INFO +123 -0
- keycloak-utils-0.0.1/README.md +97 -0
- keycloak-utils-0.0.1/pyproject.toml +70 -0
- keycloak-utils-0.0.1/setup.cfg +4 -0
- keycloak-utils-0.0.1/src/keycloak_utils/__init__.py +0 -0
- keycloak-utils-0.0.1/src/keycloak_utils/authentication/__init__.py +0 -0
- keycloak-utils-0.0.1/src/keycloak_utils/authentication/fastapi.py +56 -0
- keycloak-utils-0.0.1/src/keycloak_utils/authentication/rest_framework.py +49 -0
- keycloak-utils-0.0.1/src/keycloak_utils/backend/__init__.py +0 -0
- keycloak-utils-0.0.1/src/keycloak_utils/backend/base.py +95 -0
- keycloak-utils-0.0.1/src/keycloak_utils/backend/fastapi.py +6 -0
- keycloak-utils-0.0.1/src/keycloak_utils/backend/rest_framework.py +6 -0
- keycloak-utils-0.0.1/src/keycloak_utils/errors.py +31 -0
- keycloak-utils-0.0.1/src/keycloak_utils/manager/__init__.py +0 -0
- keycloak-utils-0.0.1/src/keycloak_utils/manager/base.py +57 -0
- keycloak-utils-0.0.1/src/keycloak_utils/manager/fastapi.py +5 -0
- keycloak-utils-0.0.1/src/keycloak_utils/manager/rest_framework.py +19 -0
- keycloak-utils-0.0.1/src/keycloak_utils/utils.py +23 -0
- keycloak-utils-0.0.1/src/keycloak_utils/verifier/__init__.py +0 -0
- keycloak-utils-0.0.1/src/keycloak_utils/verifier/base.py +37 -0
- keycloak-utils-0.0.1/src/keycloak_utils/verifier/fastapi.py +6 -0
- keycloak-utils-0.0.1/src/keycloak_utils/verifier/rest_framework.py +6 -0
- keycloak-utils-0.0.1/src/keycloak_utils.egg-info/PKG-INFO +123 -0
- keycloak-utils-0.0.1/src/keycloak_utils.egg-info/SOURCES.txt +25 -0
- keycloak-utils-0.0.1/src/keycloak_utils.egg-info/dependency_links.txt +1 -0
- keycloak-utils-0.0.1/src/keycloak_utils.egg-info/requires.txt +28 -0
- keycloak-utils-0.0.1/src/keycloak_utils.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,123 @@
|
|
|
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
|
+
Provides-Extra: django
|
|
20
|
+
Provides-Extra: fastapi
|
|
21
|
+
Provides-Extra: all
|
|
22
|
+
Provides-Extra: fastapi-test
|
|
23
|
+
Provides-Extra: test
|
|
24
|
+
Provides-Extra: lint-and-formatting
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
|
|
27
|
+
# keycloak auth utils
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
### 1. Django/DRF
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install git+https://github.com/ottuco/keycloak-auth-utils#egg=keycloak-utils[django]
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### 2. FastAPI
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install git+https://github.com/ottuco/keycloak-auth-utils#egg=keycloak-utils[fastapi]
|
|
41
|
+
````
|
|
42
|
+
|
|
43
|
+
## Usage
|
|
44
|
+
|
|
45
|
+
### 1. Django/DRF
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
# authentication.py
|
|
49
|
+
from django.contrib.auth import get_user_model
|
|
50
|
+
from keycloak_utils.authentication.rest_framework import BaseDRFKCAuthentication
|
|
51
|
+
|
|
52
|
+
User = get_user_model()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class KeycloakDRFAuthentication(BaseDRFKCAuthentication):
|
|
56
|
+
kc_host = "http://localhost:8080"
|
|
57
|
+
kc_realm = "your-realm-nae"
|
|
58
|
+
kc_algorithms = ["RS256"]
|
|
59
|
+
kc_audience = "account"
|
|
60
|
+
|
|
61
|
+
def get_or_create_user(self, claims: dict):
|
|
62
|
+
# override this method to get or create user
|
|
63
|
+
# return User.objects.get_or_create(email=claims["email"])
|
|
64
|
+
return user_instance
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# views.py
|
|
68
|
+
from rest_framework.views import APIView
|
|
69
|
+
|
|
70
|
+
class TestView(APIView):
|
|
71
|
+
authentication_classes = [KeycloakDRFAuthentication] # Add authentication class here
|
|
72
|
+
|
|
73
|
+
def get(self, request):
|
|
74
|
+
return Response({"message": "Hello, world!"})
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### 2. FastAPI
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
# middlewares.py
|
|
81
|
+
import typing
|
|
82
|
+
|
|
83
|
+
from fastapi import Request
|
|
84
|
+
from keycloak_utils.authentication.fastapi import BaseFastAPIKCAuthentication
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class AuthenticationMiddleware(BaseFastAPIKCAuthentication):
|
|
88
|
+
kc_host = "http://localhost:8080"
|
|
89
|
+
kc_realm = "your-realm-nae"
|
|
90
|
+
kc_algorithms = ["RS256"]
|
|
91
|
+
kc_audience = "account"
|
|
92
|
+
|
|
93
|
+
def post_process_claims(
|
|
94
|
+
self,
|
|
95
|
+
claims: typing.Optional[dict],
|
|
96
|
+
request: Request,
|
|
97
|
+
) -> Request:
|
|
98
|
+
# do something with `claims` here
|
|
99
|
+
return request
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
# main.py
|
|
103
|
+
from fastapi import FastAPI
|
|
104
|
+
|
|
105
|
+
app = FastAPI()
|
|
106
|
+
|
|
107
|
+
app.add_middleware(AuthenticationMiddleware) # Add middleware here
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@app.get("/")
|
|
111
|
+
def read_root():
|
|
112
|
+
return {"Hello": "World"}
|
|
113
|
+
|
|
114
|
+
```
|
|
115
|
+
## Test
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
# Install the dependencies
|
|
119
|
+
pip install .[test]
|
|
120
|
+
|
|
121
|
+
# Run tests
|
|
122
|
+
python -m pytest
|
|
123
|
+
```
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# keycloak auth utils
|
|
2
|
+
|
|
3
|
+
## Installation
|
|
4
|
+
|
|
5
|
+
### 1. Django/DRF
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install git+https://github.com/ottuco/keycloak-auth-utils#egg=keycloak-utils[django]
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
### 2. FastAPI
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install git+https://github.com/ottuco/keycloak-auth-utils#egg=keycloak-utils[fastapi]
|
|
15
|
+
````
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
### 1. Django/DRF
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
# authentication.py
|
|
23
|
+
from django.contrib.auth import get_user_model
|
|
24
|
+
from keycloak_utils.authentication.rest_framework import BaseDRFKCAuthentication
|
|
25
|
+
|
|
26
|
+
User = get_user_model()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class KeycloakDRFAuthentication(BaseDRFKCAuthentication):
|
|
30
|
+
kc_host = "http://localhost:8080"
|
|
31
|
+
kc_realm = "your-realm-nae"
|
|
32
|
+
kc_algorithms = ["RS256"]
|
|
33
|
+
kc_audience = "account"
|
|
34
|
+
|
|
35
|
+
def get_or_create_user(self, claims: dict):
|
|
36
|
+
# override this method to get or create user
|
|
37
|
+
# return User.objects.get_or_create(email=claims["email"])
|
|
38
|
+
return user_instance
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# views.py
|
|
42
|
+
from rest_framework.views import APIView
|
|
43
|
+
|
|
44
|
+
class TestView(APIView):
|
|
45
|
+
authentication_classes = [KeycloakDRFAuthentication] # Add authentication class here
|
|
46
|
+
|
|
47
|
+
def get(self, request):
|
|
48
|
+
return Response({"message": "Hello, world!"})
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### 2. FastAPI
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
# middlewares.py
|
|
55
|
+
import typing
|
|
56
|
+
|
|
57
|
+
from fastapi import Request
|
|
58
|
+
from keycloak_utils.authentication.fastapi import BaseFastAPIKCAuthentication
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class AuthenticationMiddleware(BaseFastAPIKCAuthentication):
|
|
62
|
+
kc_host = "http://localhost:8080"
|
|
63
|
+
kc_realm = "your-realm-nae"
|
|
64
|
+
kc_algorithms = ["RS256"]
|
|
65
|
+
kc_audience = "account"
|
|
66
|
+
|
|
67
|
+
def post_process_claims(
|
|
68
|
+
self,
|
|
69
|
+
claims: typing.Optional[dict],
|
|
70
|
+
request: Request,
|
|
71
|
+
) -> Request:
|
|
72
|
+
# do something with `claims` here
|
|
73
|
+
return request
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# main.py
|
|
77
|
+
from fastapi import FastAPI
|
|
78
|
+
|
|
79
|
+
app = FastAPI()
|
|
80
|
+
|
|
81
|
+
app.add_middleware(AuthenticationMiddleware) # Add middleware here
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@app.get("/")
|
|
85
|
+
def read_root():
|
|
86
|
+
return {"Hello": "World"}
|
|
87
|
+
|
|
88
|
+
```
|
|
89
|
+
## Test
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
# Install the dependencies
|
|
93
|
+
pip install .[test]
|
|
94
|
+
|
|
95
|
+
# Run tests
|
|
96
|
+
python -m pytest
|
|
97
|
+
```
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
[tool.black]
|
|
2
|
+
line_length = 88
|
|
3
|
+
force_exclude = """
|
|
4
|
+
(.github/*)
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
[tool.isort]
|
|
8
|
+
profile = "black"
|
|
9
|
+
quiet = "True"
|
|
10
|
+
skip_glob = ".github/*"
|
|
11
|
+
skip_gitignore = "True"
|
|
12
|
+
combine_as_imports = "True"
|
|
13
|
+
line_length = 88
|
|
14
|
+
|
|
15
|
+
[build-system]
|
|
16
|
+
requires = ["setuptools>=61.0"]
|
|
17
|
+
build-backend = "setuptools.build_meta"
|
|
18
|
+
|
|
19
|
+
[project]
|
|
20
|
+
name = "keycloak-utils"
|
|
21
|
+
version = "0.0.1"
|
|
22
|
+
authors = [
|
|
23
|
+
{ name = "Jerin Peter George", email = "jerinpetergeorge@gmail.com" },
|
|
24
|
+
]
|
|
25
|
+
description = "Helper classes for keycloak authentication in Django and FastAPI"
|
|
26
|
+
readme = "README.md"
|
|
27
|
+
requires-python = ">=3.7"
|
|
28
|
+
classifiers = [
|
|
29
|
+
"Environment :: Web Environment",
|
|
30
|
+
"Environment :: Console",
|
|
31
|
+
"Intended Audience :: Developers",
|
|
32
|
+
"Operating System :: OS Independent",
|
|
33
|
+
"Programming Language :: Python",
|
|
34
|
+
"Programming Language :: Python :: 3.7",
|
|
35
|
+
"Programming Language :: Python :: 3.8",
|
|
36
|
+
"Programming Language :: Python :: 3.9",
|
|
37
|
+
"Programming Language :: Python :: 3.10",
|
|
38
|
+
"Topic :: Utilities",
|
|
39
|
+
]
|
|
40
|
+
dependencies = [
|
|
41
|
+
"requests<2.31.0",
|
|
42
|
+
"pyjwt[crypto]<2.7.0",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
[project.urls]
|
|
46
|
+
"Homepage" = "https://github.com/jerinpetergeorge/keycloak-auth-utils"
|
|
47
|
+
|
|
48
|
+
[project.optional-dependencies]
|
|
49
|
+
django = ["djangorestframework>=3.12.0"]
|
|
50
|
+
fastapi = ["fastapi>=0.68.0"]
|
|
51
|
+
all = ["keycloak-utils[django,fastapi]"]
|
|
52
|
+
|
|
53
|
+
fastapi-test = ["fastapi[test]>=0.68.0"]
|
|
54
|
+
test = [
|
|
55
|
+
"keycloak-utils[django,fastapi-test]",
|
|
56
|
+
"pytest-django~=4.5.2"
|
|
57
|
+
]
|
|
58
|
+
lint-and-formatting = [
|
|
59
|
+
"black",
|
|
60
|
+
"flake8",
|
|
61
|
+
"flake8-print",
|
|
62
|
+
"isort",
|
|
63
|
+
"pre-commit",
|
|
64
|
+
]
|
|
65
|
+
dev = ["keycloak-utils[test, lint-and-formatting]"]
|
|
66
|
+
|
|
67
|
+
[tool.pytest.ini_options]
|
|
68
|
+
DJANGO_SETTINGS_MODULE = "tests.test_rest_framework.settings"
|
|
69
|
+
testpaths = ["tests"]
|
|
70
|
+
markers = ["django_db"]
|
|
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,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,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,123 @@
|
|
|
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
|
+
Provides-Extra: django
|
|
20
|
+
Provides-Extra: fastapi
|
|
21
|
+
Provides-Extra: all
|
|
22
|
+
Provides-Extra: fastapi-test
|
|
23
|
+
Provides-Extra: test
|
|
24
|
+
Provides-Extra: lint-and-formatting
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
|
|
27
|
+
# keycloak auth utils
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
### 1. Django/DRF
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install git+https://github.com/ottuco/keycloak-auth-utils#egg=keycloak-utils[django]
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
### 2. FastAPI
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install git+https://github.com/ottuco/keycloak-auth-utils#egg=keycloak-utils[fastapi]
|
|
41
|
+
````
|
|
42
|
+
|
|
43
|
+
## Usage
|
|
44
|
+
|
|
45
|
+
### 1. Django/DRF
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
# authentication.py
|
|
49
|
+
from django.contrib.auth import get_user_model
|
|
50
|
+
from keycloak_utils.authentication.rest_framework import BaseDRFKCAuthentication
|
|
51
|
+
|
|
52
|
+
User = get_user_model()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class KeycloakDRFAuthentication(BaseDRFKCAuthentication):
|
|
56
|
+
kc_host = "http://localhost:8080"
|
|
57
|
+
kc_realm = "your-realm-nae"
|
|
58
|
+
kc_algorithms = ["RS256"]
|
|
59
|
+
kc_audience = "account"
|
|
60
|
+
|
|
61
|
+
def get_or_create_user(self, claims: dict):
|
|
62
|
+
# override this method to get or create user
|
|
63
|
+
# return User.objects.get_or_create(email=claims["email"])
|
|
64
|
+
return user_instance
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# views.py
|
|
68
|
+
from rest_framework.views import APIView
|
|
69
|
+
|
|
70
|
+
class TestView(APIView):
|
|
71
|
+
authentication_classes = [KeycloakDRFAuthentication] # Add authentication class here
|
|
72
|
+
|
|
73
|
+
def get(self, request):
|
|
74
|
+
return Response({"message": "Hello, world!"})
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### 2. FastAPI
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
# middlewares.py
|
|
81
|
+
import typing
|
|
82
|
+
|
|
83
|
+
from fastapi import Request
|
|
84
|
+
from keycloak_utils.authentication.fastapi import BaseFastAPIKCAuthentication
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class AuthenticationMiddleware(BaseFastAPIKCAuthentication):
|
|
88
|
+
kc_host = "http://localhost:8080"
|
|
89
|
+
kc_realm = "your-realm-nae"
|
|
90
|
+
kc_algorithms = ["RS256"]
|
|
91
|
+
kc_audience = "account"
|
|
92
|
+
|
|
93
|
+
def post_process_claims(
|
|
94
|
+
self,
|
|
95
|
+
claims: typing.Optional[dict],
|
|
96
|
+
request: Request,
|
|
97
|
+
) -> Request:
|
|
98
|
+
# do something with `claims` here
|
|
99
|
+
return request
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
# main.py
|
|
103
|
+
from fastapi import FastAPI
|
|
104
|
+
|
|
105
|
+
app = FastAPI()
|
|
106
|
+
|
|
107
|
+
app.add_middleware(AuthenticationMiddleware) # Add middleware here
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
@app.get("/")
|
|
111
|
+
def read_root():
|
|
112
|
+
return {"Hello": "World"}
|
|
113
|
+
|
|
114
|
+
```
|
|
115
|
+
## Test
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
# Install the dependencies
|
|
119
|
+
pip install .[test]
|
|
120
|
+
|
|
121
|
+
# Run tests
|
|
122
|
+
python -m pytest
|
|
123
|
+
```
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
src/keycloak_utils/__init__.py
|
|
4
|
+
src/keycloak_utils/errors.py
|
|
5
|
+
src/keycloak_utils/utils.py
|
|
6
|
+
src/keycloak_utils.egg-info/PKG-INFO
|
|
7
|
+
src/keycloak_utils.egg-info/SOURCES.txt
|
|
8
|
+
src/keycloak_utils.egg-info/dependency_links.txt
|
|
9
|
+
src/keycloak_utils.egg-info/requires.txt
|
|
10
|
+
src/keycloak_utils.egg-info/top_level.txt
|
|
11
|
+
src/keycloak_utils/authentication/__init__.py
|
|
12
|
+
src/keycloak_utils/authentication/fastapi.py
|
|
13
|
+
src/keycloak_utils/authentication/rest_framework.py
|
|
14
|
+
src/keycloak_utils/backend/__init__.py
|
|
15
|
+
src/keycloak_utils/backend/base.py
|
|
16
|
+
src/keycloak_utils/backend/fastapi.py
|
|
17
|
+
src/keycloak_utils/backend/rest_framework.py
|
|
18
|
+
src/keycloak_utils/manager/__init__.py
|
|
19
|
+
src/keycloak_utils/manager/base.py
|
|
20
|
+
src/keycloak_utils/manager/fastapi.py
|
|
21
|
+
src/keycloak_utils/manager/rest_framework.py
|
|
22
|
+
src/keycloak_utils/verifier/__init__.py
|
|
23
|
+
src/keycloak_utils/verifier/base.py
|
|
24
|
+
src/keycloak_utils/verifier/fastapi.py
|
|
25
|
+
src/keycloak_utils/verifier/rest_framework.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
requests<2.31.0
|
|
2
|
+
pyjwt[crypto]<2.7.0
|
|
3
|
+
|
|
4
|
+
[all]
|
|
5
|
+
keycloak-utils[django,fastapi]
|
|
6
|
+
|
|
7
|
+
[dev]
|
|
8
|
+
keycloak-utils[lint-and-formatting,test]
|
|
9
|
+
|
|
10
|
+
[django]
|
|
11
|
+
djangorestframework>=3.12.0
|
|
12
|
+
|
|
13
|
+
[fastapi]
|
|
14
|
+
fastapi>=0.68.0
|
|
15
|
+
|
|
16
|
+
[fastapi-test]
|
|
17
|
+
fastapi[test]>=0.68.0
|
|
18
|
+
|
|
19
|
+
[lint-and-formatting]
|
|
20
|
+
black
|
|
21
|
+
flake8
|
|
22
|
+
flake8-print
|
|
23
|
+
isort
|
|
24
|
+
pre-commit
|
|
25
|
+
|
|
26
|
+
[test]
|
|
27
|
+
keycloak-utils[django,fastapi-test]
|
|
28
|
+
pytest-django~=4.5.2
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
keycloak_utils
|