Package: django-keycloak-auth
Django Keycloak AuthDjango Keycloak AuthWhat is it?Buy me a coffeeInstallationVia Pypi Package:ManuallyDependenciesTest dependencesHow to contributeLicenceCreditsUsageHow to apply on your ViewsClass-based ViewsModelViewSetViewSetAPIViewFunction Based ViewsLocal developmentRun tests for this libUpload this package to PypiRun local API test using this libraryWhat 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 seehttps://github.com/marcelo225/django-keycloak-authPackage link:https://pypi.org/project/django-keycloak-auth/Buy me a coffeeIf you have recognized my effort in this initiative, please buy me a coffee when possible.InstallationVia Pypi Package:$ pip install django-keycloak-authManually$ python setup.py installDependenciesPython 3requestsDjangoDjango Rest FrameworkTest dependencesunittestHow to contributePlease report bugs and feature requests athttps://github.com/marcelo225/django-keycloak-auth/issuesLicenceThe MIT License (MIT)Copyright (c) 2020 Marcelo ViníciusPermission 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.CreditsLead Developer - Marcelo ViniciusCo-authored-by:chmoderUsageIn your applicationsettings.pyfile, add following Middleware: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# keysKEYCLOAK_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 ViewsClass-based ViewsModelViewSetfromrest_frameworkimportviewsets,viewsfrom.importmodels,serializersfromrest_frameworkimportstatusfromdjango.http.responseimportJsonResponsefromrest_framework.exceptionsimportPermissionDeniedclassBankViewSet(viewsets.ModelViewSet):"""Bank endpointThis endpoint has all configured keycloak roles"""serializer_class=serializers.BankSerializerqueryset=models.Bank.objects.all()keycloak_roles={'GET':['director','judge','employee'],'POST':['director','judge',],'UPDATE':['director','judge',],'DELETE':['director','judge',],'PATCH':['director','judge','employee'],}deflist(self,request):"""Overwrite methodYou can specify your rules inside each methodusing the variable 'request.roles' that means alist of roles that came from authenticated token.See the following example bellow:"""# list of token rolesprint(request.roles)# Optional: get userinfo (SUB attribute from JWT)print(request.userinfo)returnsuper().list(self,request)ViewSetclassCarViewSet(viewsets.ViewSet):"""Car endpointThis endpoint has not configured keycloak roles.That means all methods will be allowed to access."""deflist(self,request):returnJsonResponse({"detail":"success"},status=status.HTTP_200_OK)APIViewclassJudgementView(views.APIView):"""Judgement endpointThis endpoint has configured keycloak roles only GET method.Other HTTP methods will be allowed."""keycloak_roles={'GET':['judge'],}defget(self,request,format=None):"""Overwrite methodYou can specify your rules inside each methodusing the variable 'request.roles' that means alist of roles that came from authenticated token.See the following example bellow:"""# list of token rolesprint(request.roles)# Optional: get userinfo (SUB attribute from JWT)print(request.userinfo)returnsuper().get(self,request)When you don't putkeycloak_rolesattribute in the Views that means all methods authorizations will be allowed.Function Based ViewsWhen if you useapi_viewdecorator, you would write a very simple@keycloak_rolesdecorator like this:fromdjango_keycloak_auth.decoratorsimportkeycloak_roles...@keycloak_roles(['director','judge','employee'])@api_view(['GET'])defloans(request):"""List loan endpointThis endpoint has configured keycloak roles onlyespecific GET method will be accepted in api_view."""returnJsonResponse({"message":request.roles})Local developmentRun tests for this libBefore everything, you must install VirtualEnv.# Install venv in root project folder$python3-mvenvenv&&sourceenv/bin/activate# Install dependencies$pipinstall-rrequirements.txt# Run tests$pythonmanage.pytestUpload this package to PypiWarning: before you update this package, certifies if you'll change the
version insetup.pyfile.If you interested contribute to developing this project, it was prepared a tiny tutorial to install the environment before you begin:# Install venv in root project folder$python3-mvenvenv&&sourceenv/bin/activate# Update packages for development$python-mpipinstall--upgrade-rrequirements.txt# Generate distribution -> it's on me for while ;)$pythonsetup.pysdist# Checks if the package has no errors$twinecheckdist/*# Upload package -> it's on me for while ;)$twineupload--repository-urlhttps://upload.pypi.org/legacy/dist/*Run local API test using this libraryRun following command on terminal to upKeycloakdocker container:# in root project folder$docker-composeupOpenhttp://localhost:8080/in your web browserCreate the following steps:realm,client(as confidential) and yourclient secretaccording thesettings.pyfileClient Roles:director,judge,employeeCreate a new user accountVinculate Client Roles into above user accountRun following command on another terminal:# Install venv in root project folder$python3-mvenvenv&&sourceenv/bin/activate# Install dependencies for this library$python-mpipinstall--upgrade-rrequirements.txt# Generate a local distribution for django-keyclaok-auth# Change the version of this library if necessary$pythonsetup.pysdist# Generate a local dist (verify version)$pipinstalldist/*# Create migrations, fixtures and run django server$pythonmanage.pymakemigrations&&\pythonmanage.pymigrate&&\pythonmanage.pyloaddatabanks.json&&\pythonmanage.pyrunserverStarting development server athttp://127.0.0.1:8000/UseInsonminaorPostmanto test API's endpoints using Oauth2 as authentication mode.