Skip to main content

Facilitating microservice architecture in Django REST framework

Project description

django-rest-microservice

This package is built on the djangorestframework-simplejwt package, which provides some JWT authentication mechanisms with Django REST framework. This package offers the following features:

  • Provides refresh cookie in HttpOnly cookie, and access token in response body, for better security when implemented properly with SPA.
  • Provides an easier approach to customizing token claims than the standard mechanism described in djangorestframework-simplejwt documentation.
  • Provides a mechanism for authentication with a third-party IDP, before issuing internal JWT to your users.
  • Currently, supports authentication with AWS Cognito using OAuth 2 Code Grant with PKCE for best security practices.

Installation

Install package to environment:

pip install django-rest-microservice

In the main urls.py, include the default package url routes:

from django.urls import path, include

urlpatterns = [
    path("auth/", include("rest_framework_microservice.urls"))
]

In Django settings, include the following:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTTokenUserAuthentication',
    )
}

Settings

Settings are specified in Django settings.py under REST_FRAMEWORK_MICROSERVICE, the defaults are the following:

REST_FRAMEWORK_MICROSERVICE = {
    "REFRESH_COOKIE_NAME": "refresh_cookie",
    "IDP": {
        "PROVIDER": "aws",
        "USER_POOL": "us-west-2_abcdefg",
        "CLIENT_ID": "abcdefg",
    },
    "CUSTOM_TOKEN_USER_ATTRIBUTES": [],
    "CUSTOM_TOKEN_CALLABLE_ATTRIBUTES": [],
    "COOKIE_SALT": "extra",
    "USER_SERIALIZER_CLASS": None,
}

REFRESH_COOKIE_NAME

Name of refresh cookie to set in HTTP header.

IDP

A dictionary containing IDP attributes:

  • PROVIDER: a string identifying what IDP backend to use, defaults to 'aws' (Currently only AWS Cognito is supported.)
  • USER_POOL: user pool identifier used with the IDP.
  • CLIENT_ID: IDP client id for your application.

CUSTOM_TOKEN_USER_ATTRIBUTES

The list of Django user attributes to be copied to token as claims. i.e.: ['is_active',].

CUSTOM_TOKEN_CALLABLE_ATTRIBUTES

This is used to customize claims which cannot be done by simply using CUSTOM_TOKEN_USER_ATTRIBUTES setting. This should be a list of dictionaries containing attr_name and attr_getter. i.e. : [{'attr_name': 'preferences', 'attr_getter': 'my_module.some_file.get_user_preferences'}, ...]

The function specified in attr_getter should accept an argument of a Django user instance.

COOKIE_SALT

Salt to be used when signing cookie.

USER_SERIALIZER_CLASS

Defaults to None. If specified, the default view serializers will try to add a user object representing the user. The content of the user object is defined by USER_SERIALIZER_CLASS.

Customizing token claims

You can include additional user attributes in the token claims by specifying them in the CUSTOM_TOKEN_USER_ATTRIBUTES.

You can also specify functions to return the value for custom claims by using CUSTOM_TOKEN_CALLABLE_ATTRIBUTES.

# settings.py
REST_FRAMEWORK_MICROSERVICE = {
  ...,
  'CUSTOM_TOKEN_CALLABLE_ATTRIBUTES': [
        {'attr_name': 'user_services',
         'attr_getter': 'my_module.token_claims.get_user_subscribed_services'
         }
    ]
}

# my_module.token_claims.py
def get_user_subscribed_services(user):
  return user.subscribed_services

If you are using djangorestframework-simplejwt version <= 5.0.0, you will also need to extend the rest_framework_simplejwt.models.TokenUser to include the additional claims. This is only applicable when using older versions.

from functools import cached_property
from rest_framework_simplejwt.models import TokenUser

class CustomTokenUser(TokenUser):
    """
    Extend TokenUser and adds custom attributes to be pulled from TokenUser.
    This class should be specified in Django settings SIMPLE_JWT.TOKEN_USER_CLASS
    """

    @cached_property
    def first_name(self):
        return self.token.get('first_name', None)

and include the following Django setting:

SIMPLE_JWT = {
    'TOKEN_USER_CLASS': 'microservice.models.CustomTokenUser'
}

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-rest-microservice-1.0.tar.gz (9.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_rest_microservice-1.0-py3-none-any.whl (11.3 kB view details)

Uploaded Python 3

File details

Details for the file django-rest-microservice-1.0.tar.gz.

File metadata

  • Download URL: django-rest-microservice-1.0.tar.gz
  • Upload date:
  • Size: 9.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.6.1 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.61.2 CPython/3.9.6

File hashes

Hashes for django-rest-microservice-1.0.tar.gz
Algorithm Hash digest
SHA256 f62d1935a96abdb8a0460f4f06e628ef7fb230790a0f627f78968529f42a83aa
MD5 459baa3a5f4c72c7a3acff6d59a13d02
BLAKE2b-256 7563d9b22e77877ece7a085c36a7197e21cf4402a0fdd28d7023b6f6c702b8d1

See more details on using hashes here.

File details

Details for the file django_rest_microservice-1.0-py3-none-any.whl.

File metadata

  • Download URL: django_rest_microservice-1.0-py3-none-any.whl
  • Upload date:
  • Size: 11.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.7.1 importlib_metadata/4.6.1 pkginfo/1.8.2 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.61.2 CPython/3.9.6

File hashes

Hashes for django_rest_microservice-1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 7b3fc20b7b1b1324499de4bf74035a60d05576ccaa2e8a49284f1963cf21bafe
MD5 59ea95b0e9a9aa9e954e424036f10efc
BLAKE2b-256 f5301ce6824cff40711040cbffa1467de01a20bc6b9077e7ea6481db2e4f1a14

See more details on using hashes here.

Supported by

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