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.3.tar.gz (16.5 kB view details)

Uploaded Source

Built Distribution

django_jwt_oidc-0.2.3-py3-none-any.whl (20.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: django-jwt-oidc-0.2.3.tar.gz
  • Upload date:
  • Size: 16.5 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.63.0 importlib-metadata/4.11.2 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.3.tar.gz
Algorithm Hash digest
SHA256 18ac36fdf8f2acfb04db65635464e034425bdc579b2cb0c76f5adc7badef7933
MD5 6adeb1bdb83b5b4f3ea079b7bb4b9c0b
BLAKE2b-256 818a2575f26aa9692bc891024c8b5434a1b3ab378dd01930c31efb6c2d7d4b9c

See more details on using hashes here.

File details

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

File metadata

  • Download URL: django_jwt_oidc-0.2.3-py3-none-any.whl
  • Upload date:
  • Size: 20.5 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.63.0 importlib-metadata/4.11.2 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.3-py3-none-any.whl
Algorithm Hash digest
SHA256 469449e5650f55f2c6155db223586feccaf6a4a197b220ad86c2bc35f68ef1af
MD5 83a89d532596071f9899ddd121e41a88
BLAKE2b-256 45a0eda3db3f5e72bda81e7788ffce9e964ed341936f5f1220cfec7c101d68aa

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