Skip to main content

Django library that implements the authentification for OpenId SSO with JWT from oauth2.

Project description

Django jwt

Django library that implements the authentification for OpenId SSO with JWT from oauth2. This authentification is compatible with django session workflow and the RestFramework library.

Installation

Install the library with pip

pip install django-jwt-oidc

Add the django_jwt package into your INSTALLED_APPS in your settings.py file

INSTALLED_APPS = [
    ...
    'django_jwt',
    ...
]

Django [WIP]

This is what you need to do in order that your Django application will authenticate with JWT.

RestFramework

This settings are for views inherits RestFramework library from Django. You will need to install RestFramework on your own to your app first

View setting

You can add this to your APIviews class by adding JWTTokenAuthentication to authentification_classes attribute. In this example, the view requires that all requests must have JWT Bearer Authentication.

from rest_framework import permissions, views
from django_jwt import JWTTokenAuthentication


class ExampleAPIView(view.APIView):
    authentication_classes = [JWTTokenAuthentication]
    permission_classes = [permissions.IsAuthenticated]

Global setting

If all your application can work with JWT Bearer Authentication you can add the JWTTokenAuthentication class to DEFAULT_AUTHENTICATION_CLASSES setting on settings.py of your app.

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'django_jwt.rest_framework.JWTTokenAuthentication',
    ]
}

Fake server (deployment only)

This is an extra functionality of the django_jwt app that makes a OpenId server with oauth 2.0 with implicit flow with an input to "log in" as whatever sub value you want.

Installation

  • Install django-cors-headers library into your app. Required in order to control the CORS policy from your frontend.
  • Add your frontend domain into CORS_ALLOWED_ORIGINS.
  • Change the CLIENT_JWT [ OPENID2_URL ] setting to 'fake'.
  • Set up the CLIENT_JWT [ CLIENT_ID ] setting to the same client id your frontend is targeting.
  • Include the django_jwt.urls into your urls.py.
  • Set up the DEFAULT_DOMAIN setting on your Django settings. Example:
DEFAULT_DOMAIN = 'https://localhost:8000'
  • Set up your frontend url into the path that you included in urls.py.

Server

This is an extra app of the django_jwt app that deploys a OpenId server with oauth 2.0 with implicit flow (more coming soon). The JWTs are signed by a RS256 algorithm that regenerates the rsa private keys. Access tokens expire after 1 hour kept by the Implicit Flow protocol.
Django JWT Server does not provide for a login view.

Installation

  • Install django-cors-headers library into your app. Required in order to control the CORS policy from your apps. There is no need to add the domains one by one
  • Add django_jwt.server to your installed apps.
  • Change the CLIENT_JWT [ OPENID2_URL ] setting to 'local'.
  • Migrate the database with python manage.py migrate.
  • Add your implemented Django log in into LOGIN_URL setting on settings.py.
  • Run your app in order to set up your hosts into the WebPage model.
  • (Optional) If you want to use your id_tokens in your app, set up the CLIENT_JWT [ CLIENT_ID ] setting to the same client id that you just created.

Settings

The settings are separated into 2 main Django settings JWT_CLIENT for the django_jwt app and JWT_SERVER for the django_jwt.server app.

OPENID2_URL [ JWT_CLIENT ]

There is 3 types of configurations for this field:

  • URL: The openid service url without the /.well-known/openid-configuration path.
  • Fake server: In case of development and using jwt from the fake server you need to set this to 'fake'.
  • OpenId server: If you want to deploy the openId app, you need to set to 'local' in order to validate jwt tokens. Only for RestFramework.

CLIENT_ID [ JWT_CLIENT ]

This is the client id of the openId service you are using.
If you want to validate the jwt from the OpenId server by django_jwt.server app you will need to add here the generated client_id on the admin page.

RENAME_ATTRIBUTES [ JWT_CLIENT ]

Dictionary to redirect the data and the sub attribute into the User attributes.

CREATE_USER [ JWT_CLIENT ]

Boolean that creates a Django user by default if the user doesn't exists if set to False.

DEFAULT_ATTRIBUTES [ JWT_CLIENT ]

Dictionary that sets default values to new Users created. This example sets the all the attibutes of users created by the library auto_created to True.

COOKIE_NAME [ JWT_CLIENT ]

String that represents the identification of the cookie id of the JWT.

Example of JWT_CLIENT on settings.py

JWT_CLIENT = {
    'OPENID2_URL': 'https://localhost:8000',    # Required
    'CLIENT_ID': 'client_id',                   # Required
    'RENAME_ATTRIBUTES': {'sub': 'username'},   # Optional
    'DEFAULT_ATTRIBUTES': {},                   # Optional
    'CREATE_USER': True,                        # optional
    'COOKIE_NAME': 'id_token'                   # Optional
}

JWT_EXPIRATION_TIME [ JWT_SERVER ]

This setting is to change the expiration time (in seconds) for JWT generated by the server. This not includes the fake server.

JWK_EXPIRATION_TIME [ JWT_SERVER ]

This setting is to change the expiration time (in seconds) for the JWK generated by the server. This must be grater than JWT_EXPIRATION_TIME

Example of JWT_SERVER on settings.py

JWT_SERVER = {
    'JWK_EXPIRATION_TIME': 3600,                # Optional
    'JWT_EXPIRATION_TIME': 14400                # Optional
}

Changing the values of the jwt

You can also modify attributes like adding something to the value creating a change_[attribute_name] method on the User model.
Example of changing the username attribute:

class User(AbstractBaseUser):
    def change_username(self, value):
        return value + '@jwt'

Changing the default creation of the user

You can also change the creation method of the BaseUserManager of the AbstractBaseUser model in order to customize its default creation.

class UserManager(BaseUserManager):
    def get_or_create(self, defaults=None, **kwargs):
        ...

class User(AbstractBaseUser):
    objects = UserManager()
    ...

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

django-jwt-oidc-0.2.tar.gz (16.1 kB view details)

Uploaded Source

Built Distribution

django_jwt_oidc-0.2-py3-none-any.whl (19.9 kB view details)

Uploaded Python 3

File details

Details for the file django-jwt-oidc-0.2.tar.gz.

File metadata

  • Download URL: django-jwt-oidc-0.2.tar.gz
  • Upload date:
  • Size: 16.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.1 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for django-jwt-oidc-0.2.tar.gz
Algorithm Hash digest
SHA256 4e4fe0576adff7785593447784452292529037a335174dd00926047526d0087d
MD5 c5c293d0ce821e2de283119844c941dd
BLAKE2b-256 1953cfb2a881cc336e408e30044cd9d29df5afc2af78bde009cbce0957f79add

See more details on using hashes here.

File details

Details for the file django_jwt_oidc-0.2-py3-none-any.whl.

File metadata

  • Download URL: django_jwt_oidc-0.2-py3-none-any.whl
  • Upload date:
  • Size: 19.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.1 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10

File hashes

Hashes for django_jwt_oidc-0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 32e98336f18827812b594e96e27187c12e8a2c122036c1911596efa50b50878f
MD5 6be5fcdb7c427f159a5977ad76b85af2
BLAKE2b-256 66490c1015f8195cb2536b5e0b8cd4574e3e37c93ec7de67a128994320187ec4

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page