# Django Keycloak Auth
- [Django Keycloak Auth](#django-keycloak-auth)
- [What is it?](#what-is-it)
- [Buy me a coffee](#buy-me-a-coffee)
- [Installation](#installation)
- [Via Pypi Package:](#via-pypi-package)
- [Manually](#manually)
- [Dependencies](#dependencies)
- [Test dependences](#test-dependences)
- [How to contribute](#how-to-contribute)
- [Licence](#licence)
- [Credits](#credits)
- [Usage](#usage)
- [How to apply on your Views](#how-to-apply-on-your-views)
- [Class-based Views](#class-based-views)
- [ModelViewSet](#modelviewset)
- [ViewSet](#viewset)
- [APIView](#apiview)
- [Function Based Views](#function-based-views)
- [Local development](#local-development)
- [Run tests for this lib](#run-tests-for-this-lib)
- [Upload this package to Pypi](#upload-this-package-to-pypi)
- [Run local API test using this library](#run-local-api-test-using-this-library)
## What is it?
Django Keycloak Auth is a simple library that authorizes your application's resources using Django Rest Framework.
This package is used to perform authorization by keycloak roles from JWT token. Both realm roles and client roles are
supported.
For example, the following token indicates that the user has the realm role "manager" and the client
roles "director" and "employer" :
```
...
"realm_access": {
"roles": [
"manager"
]
},
"resource_access": {
"first-api": {
"roles": [
"director",
"employer",
]
}
},
...
```
For review see https://github.com/marcelo225/django-keycloak-auth
Package link: https://pypi.org/project/django-keycloak-auth/
## Buy me a coffee
If you have recognized my effort in this initiative, please buy me a coffee when possible.
![coffee](qr_code.png)
## Installation
### Via Pypi Package:
`$ pip install django-keycloak-auth`
### Manually
`$ python setup.py install`
## Dependencies
- [Python 3](https://www.python.org/)
- [requests](https://requests.readthedocs.io/en/master/)
- [Django](https://www.djangoproject.com/)
- [Django Rest Framework](https://www.django-rest-framework.org/)
## Test dependences
- [unittest](https://docs.python.org/3/library/unittest.html)
## How to contribute
Please report bugs and feature requests at
https://github.com/marcelo225/django-keycloak-auth/issues
## Licence
The MIT License (MIT)
Copyright (c) 2020 Marcelo VinÃcius
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## Credits
Lead Developer - Marcelo Vinicius
Co-authored-by:
- [chmoder](https://github.com/chmoder)
## Usage
1. In your application `settings.py` file, add following Middleware:
```python
MIDDLEWARE = [
#...
'django_keycloak_auth.middleware.KeycloakMiddleware',
#...
]
#...
# Exempt URIS
# For example: ['core/banks', 'swagger']
KEYCLOAK_EXEMPT_URIS = []
# LOCAL_DECODE: is optional and False by default. If True
# tokens will be decoded locally. Instead of on the keycloak
# server using the introspection endpoint.
# KEYCLOAK_CACHE_TTL: number of seconds to cache keyclaok public
# keys
KEYCLOAK_CONFIG = {
'KEYCLOAK_SERVER_URL': 'http://localhost:8080',
'KEYCLOAK_REALM': 'TEST',
'KEYCLOAK_CLIENT_ID': 'client-backend',
'KEYCLOAK_CLIENT_SECRET_KEY': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
'KEYCLOAK_CACHE_TTL': 60,
'LOCAL_DECODE': False
}
```
## How to apply on your Views
### Class-based Views
#### ModelViewSet
```python
from rest_framework import viewsets, views
from . import models, serializers
from rest_framework import status
from django.http.response import JsonResponse
from rest_framework.exceptions import PermissionDenied
class BankViewSet(viewsets.ModelViewSet):
"""
Bank endpoint
This endpoint has all configured keycloak roles
"""
serializer_class = serializers.BankSerializer
queryset = models.Bank.objects.all()
keycloak_roles = {
'GET': ['director', 'judge', 'employee'],
'POST': ['director', 'judge', ],
'UPDATE': ['director', 'judge', ],
'DELETE': ['director', 'judge', ],
'PATCH': ['director', 'judge', 'employee'],
}
def list(self, request):
"""
Overwrite method
You can specify your rules inside each method
using the variable 'request.roles' that means a
list of roles that came from authenticated token.
See the following example bellow:
"""
# list of token roles
print(request.roles)
# Optional: get userinfo (SUB attribute from JWT)
print(request.userinfo)
return super().list(self, request)
```
#### ViewSet
```python
class CarViewSet(viewsets.ViewSet):
"""
Car endpoint
This endpoint has not configured keycloak roles.
That means all methods will be allowed to access.
"""
def list(self, request):
return JsonResponse({"detail": "success"}, status=status.HTTP_200_OK)
```
#### APIView
```python
class JudgementView(views.APIView):
"""
Judgement endpoint
This endpoint has configured keycloak roles only GET method.
Other HTTP methods will be allowed.
"""
keycloak_roles = {
'GET': ['judge'],
}
def get(self, request, format=None):
"""
Overwrite method
You can specify your rules inside each method
using the variable 'request.roles' that means a
list of roles that came from authenticated token.
See the following example bellow:
"""
# list of token roles
print(request.roles)
# Optional: get userinfo (SUB attribute from JWT)
print(request.userinfo)
return super().get(self, request)
```
When you don't put **keycloak_roles** attribute in the Views that means all methods authorizations will be allowed.
### Function Based Views
When if you use `api_view` decorator, you would write a very simple `@keycloak_roles` decorator like this:
```python
from django_keycloak_auth.decorators import keycloak_roles
...
@keycloak_roles(['director', 'judge', 'employee'])
@api_view(['GET'])
def loans(request):
"""
List loan endpoint
This endpoint has configured keycloak roles only
especific GET method will be accepted in api_view.
"""
return JsonResponse({"message": request.roles})
```
## Local development
### Run tests for this lib
Before everything, you must install VirtualEnv.
```bash
# Install venv in root project folder
$ python3 -m venv env && source env/bin/activate
# Install dependencies
$ pip install -r requirements.txt
# Run tests
$ python manage.py test
```
### Upload this package to Pypi
> **Warning**: before you update this package, certifies if you'll change the
> version in `setup.py` file.
If you interested contribute to developing this project, it was prepared a tiny tutorial to install the environment before you begin:
```bash
# Install venv in root project folder
$ python3 -m venv env && source env/bin/activate
# Update packages for development
$ python -m pip install --upgrade -r requirements.txt
# Generate distribution -> it's on me for while ;)
$ python setup.py sdist
# Checks if the package has no errors
$ twine check dist/*
# Upload package -> it's on me for while ;)
$ twine upload --repository-url https://upload.pypi.org/legacy/ dist/*
```
### Run local API test using this library
1. Run following command on terminal to up [Keycloak](https://www.keycloak.org/) docker container:
```bash
# in root project folder
$ docker-compose up
```
2. Open http://localhost:8080/ in your web browser
3. Create the following steps:
1. `realm`, `client` (as confidential) and your `client secret` according the [settings.py](/django-keycloak-auth/settings.py#L148) file
2. Client Roles: `director`, `judge`, `employee`
3. Create a new user account
4. Vinculate Client Roles into above user account
4. Run following command on another terminal:
```bash
# Install venv in root project folder
$ python3 -m venv env && source env/bin/activate
# Install dependencies for this library
$ python -m pip install --upgrade -r requirements.txt
# Generate a local distribution for django-keyclaok-auth
# Change the version of this library if necessary
$ python setup.py sdist
# Generate a local dist (verify version)
$ pip install dist/*
# Create migrations, fixtures and run django server
$ python manage.py makemigrations && \
python manage.py migrate && \
python manage.py loaddata banks.json && \
python manage.py runserver
```
5. Starting development server at http://127.0.0.1:8000/
6. Use [Insonmina](https://insomnia.rest/) or [Postman](https://www.postman.com/) to test API's endpoints using Oauth2 as authentication mode.
Raw data
{
"_id": null,
"home_page": "https://github.com/marcelo225/django-keycloak-auth",
"name": "django-keycloak-auth",
"maintainer": "",
"docs_url": null,
"requires_python": "",
"maintainer_email": "",
"keywords": "keycloak django roles authentication authorization",
"author": "Marcelo Vinicius",
"author_email": "mr.225@hotmail.com",
"download_url": "https://files.pythonhosted.org/packages/01/b6/135bdd7755f476042dd1c37eafcfe999761a7c8d1006ed55741821260d85/django-keycloak-auth-1.0.0.tar.gz",
"platform": null,
"description": "# Django Keycloak Auth\n\n- [Django Keycloak Auth](#django-keycloak-auth)\n - [What is it?](#what-is-it)\n - [Buy me a coffee](#buy-me-a-coffee)\n - [Installation](#installation)\n - [Via Pypi Package:](#via-pypi-package)\n - [Manually](#manually)\n - [Dependencies](#dependencies)\n - [Test dependences](#test-dependences)\n - [How to contribute](#how-to-contribute)\n - [Licence](#licence)\n - [Credits](#credits)\n - [Usage](#usage)\n - [How to apply on your Views](#how-to-apply-on-your-views)\n - [Class-based Views](#class-based-views)\n - [ModelViewSet](#modelviewset)\n - [ViewSet](#viewset)\n - [APIView](#apiview)\n - [Function Based Views](#function-based-views)\n - [Local development](#local-development)\n - [Run tests for this lib](#run-tests-for-this-lib)\n - [Upload this package to Pypi](#upload-this-package-to-pypi)\n - [Run local API test using this library](#run-local-api-test-using-this-library)\n\n## What is it?\n\nDjango Keycloak Auth is a simple library that authorizes your application's resources using Django Rest Framework.\n\nThis package is used to perform authorization by keycloak roles from JWT token. Both realm roles and client roles are\nsupported.\n\nFor example, the following token indicates that the user has the realm role \"manager\" and the client\nroles \"director\" and \"employer\" :\n\n```\n...\n\n \"realm_access\": {\n \"roles\": [\n \"manager\"\n ]\n },\n \"resource_access\": {\n \"first-api\": {\n \"roles\": [\n \"director\",\n \"employer\",\n ]\n }\n },\n ...\n```\n\nFor review see https://github.com/marcelo225/django-keycloak-auth\n\nPackage link: https://pypi.org/project/django-keycloak-auth/\n\n## Buy me a coffee\n\nIf you have recognized my effort in this initiative, please buy me a coffee when possible.\n\n![coffee](qr_code.png)\n\n## Installation\n\n### Via Pypi Package:\n\n`$ pip install django-keycloak-auth`\n\n### Manually\n\n`$ python setup.py install`\n\n## Dependencies\n\n- [Python 3](https://www.python.org/)\n- [requests](https://requests.readthedocs.io/en/master/)\n- [Django](https://www.djangoproject.com/)\n- [Django Rest Framework](https://www.django-rest-framework.org/)\n\n## Test dependences\n\n- [unittest](https://docs.python.org/3/library/unittest.html)\n\n## How to contribute\n\nPlease report bugs and feature requests at\nhttps://github.com/marcelo225/django-keycloak-auth/issues\n\n## Licence\n\nThe MIT License (MIT)\n\nCopyright (c) 2020 Marcelo Vin\u00edcius\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n## Credits\n\nLead Developer - Marcelo Vinicius\n\nCo-authored-by:\n\n- [chmoder](https://github.com/chmoder)\n\n## Usage\n\n1. In your application `settings.py` file, add following Middleware:\n\n```python\nMIDDLEWARE = [\n #...\n 'django_keycloak_auth.middleware.KeycloakMiddleware',\n #...\n]\n\n#...\n\n# Exempt URIS\n# For example: ['core/banks', 'swagger']\nKEYCLOAK_EXEMPT_URIS = []\n\n# LOCAL_DECODE: is optional and False by default. If True\n# tokens will be decoded locally. Instead of on the keycloak\n# server using the introspection endpoint.\n\n# KEYCLOAK_CACHE_TTL: number of seconds to cache keyclaok public\n# keys\nKEYCLOAK_CONFIG = {\n 'KEYCLOAK_SERVER_URL': 'http://localhost:8080',\n 'KEYCLOAK_REALM': 'TEST',\n 'KEYCLOAK_CLIENT_ID': 'client-backend',\n 'KEYCLOAK_CLIENT_SECRET_KEY': 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'\n 'KEYCLOAK_CACHE_TTL': 60,\n 'LOCAL_DECODE': False\n}\n```\n\n## How to apply on your Views\n\n### Class-based Views\n\n#### ModelViewSet\n\n```python\n\nfrom rest_framework import viewsets, views\nfrom . import models, serializers\nfrom rest_framework import status\nfrom django.http.response import JsonResponse\nfrom rest_framework.exceptions import PermissionDenied\n\nclass BankViewSet(viewsets.ModelViewSet):\n \"\"\"\n Bank endpoint\n This endpoint has all configured keycloak roles\n \"\"\"\n serializer_class = serializers.BankSerializer\n queryset = models.Bank.objects.all()\n keycloak_roles = {\n 'GET': ['director', 'judge', 'employee'],\n 'POST': ['director', 'judge', ],\n 'UPDATE': ['director', 'judge', ],\n 'DELETE': ['director', 'judge', ],\n 'PATCH': ['director', 'judge', 'employee'],\n }\n\n def list(self, request):\n \"\"\"\n Overwrite method\n You can specify your rules inside each method\n using the variable 'request.roles' that means a\n list of roles that came from authenticated token.\n See the following example bellow:\n \"\"\"\n # list of token roles\n print(request.roles)\n\n # Optional: get userinfo (SUB attribute from JWT)\n print(request.userinfo)\n\n return super().list(self, request)\n```\n\n#### ViewSet\n\n```python\n\nclass CarViewSet(viewsets.ViewSet):\n \"\"\"\n Car endpoint\n This endpoint has not configured keycloak roles.\n That means all methods will be allowed to access.\n \"\"\"\n def list(self, request):\n return JsonResponse({\"detail\": \"success\"}, status=status.HTTP_200_OK)\n\n```\n\n#### APIView\n\n```python\n\nclass JudgementView(views.APIView):\n \"\"\"\n Judgement endpoint\n This endpoint has configured keycloak roles only GET method.\n Other HTTP methods will be allowed.\n \"\"\"\n keycloak_roles = {\n 'GET': ['judge'],\n }\n\n def get(self, request, format=None):\n \"\"\"\n Overwrite method\n You can specify your rules inside each method\n using the variable 'request.roles' that means a\n list of roles that came from authenticated token.\n See the following example bellow:\n \"\"\"\n # list of token roles\n print(request.roles)\n\n # Optional: get userinfo (SUB attribute from JWT)\n print(request.userinfo)\n\n return super().get(self, request)\n\n```\n\nWhen you don't put **keycloak_roles** attribute in the Views that means all methods authorizations will be allowed.\n\n### Function Based Views\n\nWhen if you use `api_view` decorator, you would write a very simple `@keycloak_roles` decorator like this:\n\n```python\nfrom django_keycloak_auth.decorators import keycloak_roles\n...\n\n@keycloak_roles(['director', 'judge', 'employee'])\n@api_view(['GET'])\ndef loans(request):\n \"\"\"\n List loan endpoint\n This endpoint has configured keycloak roles only\n especific GET method will be accepted in api_view.\n \"\"\"\n return JsonResponse({\"message\": request.roles})\n```\n\n## Local development\n\n### Run tests for this lib\n\nBefore everything, you must install VirtualEnv.\n\n```bash\n# Install venv in root project folder\n$ python3 -m venv env && source env/bin/activate\n\n# Install dependencies\n$ pip install -r requirements.txt\n\n# Run tests\n$ python manage.py test\n\n```\n\n### Upload this package to Pypi\n\n> **Warning**: before you update this package, certifies if you'll change the\n> version in `setup.py` file.\n\nIf you interested contribute to developing this project, it was prepared a tiny tutorial to install the environment before you begin:\n\n```bash\n# Install venv in root project folder\n$ python3 -m venv env && source env/bin/activate\n\n# Update packages for development\n$ python -m pip install --upgrade -r requirements.txt\n\n# Generate distribution -> it's on me for while ;)\n$ python setup.py sdist\n\n# Checks if the package has no errors\n$ twine check dist/*\n\n# Upload package -> it's on me for while ;)\n$ twine upload --repository-url https://upload.pypi.org/legacy/ dist/*\n\n```\n\n### Run local API test using this library\n\n1. Run following command on terminal to up [Keycloak](https://www.keycloak.org/) docker container:\n\n```bash\n# in root project folder\n$ docker-compose up\n```\n\n2. Open http://localhost:8080/ in your web browser\n3. Create the following steps:\n\n 1. `realm`, `client` (as confidential) and your `client secret` according the [settings.py](/django-keycloak-auth/settings.py#L148) file\n 2. Client Roles: `director`, `judge`, `employee`\n 3. Create a new user account\n 4. Vinculate Client Roles into above user account\n\n4. Run following command on another terminal:\n\n```bash\n# Install venv in root project folder\n$ python3 -m venv env && source env/bin/activate\n\n# Install dependencies for this library\n$ python -m pip install --upgrade -r requirements.txt\n\n# Generate a local distribution for django-keyclaok-auth\n# Change the version of this library if necessary\n$ python setup.py sdist\n\n# Generate a local dist (verify version)\n$ pip install dist/*\n\n# Create migrations, fixtures and run django server\n$ python manage.py makemigrations && \\\n python manage.py migrate && \\\n python manage.py loaddata banks.json && \\\n python manage.py runserver\n```\n\n5. Starting development server at http://127.0.0.1:8000/\n6. Use [Insonmina](https://insomnia.rest/) or [Postman](https://www.postman.com/) to test API's endpoints using Oauth2 as authentication mode.",
"bugtrack_url": null,
"license": "",
"summary": "Django Keycloak Auth is Python package providing access to the Keycloak API.",
"version": "1.0.0",
"project_urls": {
"Funding": "https://donate.pypi.org",
"Homepage": "https://github.com/marcelo225/django-keycloak-auth",
"Say Thanks!": "https://github.com/marcelo225/django-keycloak-auth",
"Source": "https://github.com/marcelo225/django-keycloak-auth",
"Tracker": "https://github.com/marcelo225/django-keycloak-auth/issues"
},
"split_keywords": [
"keycloak",
"django",
"roles",
"authentication",
"authorization"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "01b6135bdd7755f476042dd1c37eafcfe999761a7c8d1006ed55741821260d85",
"md5": "b7cd3251ddeb885c1cb4b7a8a5aa8d07",
"sha256": "e5c9b77fa31cccfbb518d5bd375385ad2a067a5302eb6489863abaf7294399f2"
},
"downloads": -1,
"filename": "django-keycloak-auth-1.0.0.tar.gz",
"has_sig": false,
"md5_digest": "b7cd3251ddeb885c1cb4b7a8a5aa8d07",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 20312,
"upload_time": "2024-02-24T15:33:44",
"upload_time_iso_8601": "2024-02-24T15:33:44.916339Z",
"url": "https://files.pythonhosted.org/packages/01/b6/135bdd7755f476042dd1c37eafcfe999761a7c8d1006ed55741821260d85/django-keycloak-auth-1.0.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-02-24 15:33:44",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "marcelo225",
"github_project": "django-keycloak-auth",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"requirements": [],
"lcname": "django-keycloak-auth"
}