djangorestframework-simplejwt

repository·master·Indexed 26 days ago

https://github.com/jazzband/djangorestframework-simplejwt

A JSON Web Token (JWT) authentication plugin for the Django REST Framework. It provides robust JWT implementation, including support for token blacklisting, custom token claims via TokenObtainPairSerializer, and manual token generation using RefreshToken. The library includes built-in views for obtaining, refreshing, verifying, and blacklisting tokens, and offers integration guidance for drf-yasg.

Tokens
6.8K
Snippets
15
Records
39
Agent score
88%

What's inside djangorestframework-simplejwt

  1. Understand Simple JWT token types

    master

    Simple JWT uses a token_type claim (customizable via TOKEN_TYPE_CLAIM) in the token payload to distinguish between types.

    Supported types include:

    • access: The default type used to prove authentication.
    • sliding: A token that contains both an expiration claim and a refresh expiration claim.
    • refresh: Used for obtaining new tokens, but not considered valid for direct authentication.

    By default, Simple JWT expects an access token for authentication. You can control which token types are allowed for authentication by configuring the AUTH_TOKEN_CLASSES setting.

  2. Install djangorestframework-simplejwt

    master

    You can install Simple JWT using pip. If you need to use digital signature algorithms like RSA or ECDSA, it is recommended to install the [crypto] extra to include the cryptography library automatically. This ensures the dependency is correctly tracked in your requirements files.

    Standard installation:

    pip install djangorestframework-simplejwt

    Installation with cryptographic support (recommended for RSA/ECDSA):

    pip install djangorestframework-simplejwt[crypto]
    pip install djangorestframework-simplejwt[crypto]
  3. Run tests across all supported environments with tox

    master

    To ensure compatibility across multiple Python versions, use tox. This requires pyenv to manage Python versions.

    1. Install the required Python minor versions using pyenv.
    2. Create a .python-version file in the project directory containing the version(s) you wish to test against.
    3. Run tox to execute the test suite in all configured environments.
  4. Implement Sliding Tokens

    master

    Sliding tokens provide a convenient user experience by allowing a token to be used for authentication as long as its expiration claim is valid, and can be submitted to a refresh view to renew its expiration as long as its refresh expiration claim is valid.

    Note: If using the blacklist app, every authenticated request using a sliding token will be validated against the blacklist, which may impact performance.

    To use sliding tokens, you must:

    1. Update AUTH_TOKEN_CLASSES to include 'rest_framework_simplejwt.tokens.SlidingToken'.
    2. Add the sliding token specific views (TokenObtainSlidingView and TokenRefreshSlidingView) to your URL patterns.
    from rest_framework_simplejwt.views import (
        TokenObtainSlidingView,
        TokenRefreshSlidingView,
    )
    
    urlpatterns = [
        ...
        path('api/token/', TokenObtainSlidingView.as_view(), name='token_obtain'),
        path('api/token/refresh/', TokenRefreshSlidingView.as_view(), name='token_refresh'),
        ...
    ]
  5. Configure Simple JWT in Django settings

    master

    To use Simple JWT, you must add rest_framework_simplejwt.authentication.JWTAuthentication to your Django REST Framework authentication classes in settings.py.

    If you want to use localizations and translations, also add 'rest_framework_simplejwt' to your INSTALLED_APPS list.

    REST_FRAMEWORK = {
        ...
        'DEFAULT_AUTHENTICATION_CLASSES': (
            ...
            'rest_framework_simplejwt.authentication.JWTAuthentication',
        )
        ...
    }
    
    INSTALLED_APPS = [
        ...
        'rest_framework_simplejwt',
        ...
    ]
  6. Register a custom serializer in SIMPLE_JWT settings

    master

    After creating a custom serializer subclass, you must tell djangorestframework-simplejwt to use it instead of the default by updating the SIMPLE_JWT configuration dictionary in your Django settings.py. Use the TOKEN_OBTAIN_SERIALIZER key with the full Python path to your serializer class.

    # Django project settings.py
    ...
    
    SIMPLE_JWT = {
        # It will work instead of the default serializer(TokenObtainPairSerializer).
        "TOKEN_OBTAIN_SERIALIZER": "my_app.serializers.MyTokenObtainPairSerializer",
        # ...
    }
  7. Customize token claims by subclassing TokenObtainPairSerializer

    master

    To add custom claims to the JWTs generated by TokenObtainPairView or TokenObtainSlidingView, you must subclass the corresponding serializer and override the get_token class method.

    Note that claims added via get_token will be present in both the refresh and access tokens, because the access token is derived from the refresh token produced by this method.

    from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
    from rest_framework_simplejwt.views import TokenObtainPairView
    
    class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
        @classmethod
        def get_token(cls, user):
            token = super().get_token(user)
    
            # Add custom claims
            token['name'] = user.name
            # ...
    
            return token
  8. Set up a local development environment for Simple JWT

    master

    To develop on Simple JWT, fork the repository on GitHub and clone it locally. Create and activate a virtual environment, then install the package in editable mode with the development dependencies using pip install -e .[dev].

    Note for Mac/zsh users: You must escape the brackets in the install command.

    pip install --upgrade pip setuptools
    pip install -e .[dev]
    
    # For Mac/zsh users:
    pip install -e .\[dev\]
  9. Use JWTStatelessUserAuthentication for stateless authentication

    master

    To implement stateless user authentication where the backend does not perform a database lookup for a user instance, use the JWTStatelessUserAuthentication backend. Instead of a database record, the authenticate method returns a rest_framework_simplejwt.models.TokenUser instance, which is backed only by a validated token. This is useful for Single Sign-On (SSO) across separately hosted Django applications that share the same token secret key.

    Note: In version 5.1.0, JWTTokenUserAuthentication was renamed to JWTStatelessUserAuthentication, but both names remain supported for backwards compatibility.

    REST_FRAMEWORK = {
        ...
        'DEFAULT_AUTHENTICATION_CLASSES': (
            ...
            'rest_framework_simplejwt.authentication.JWTStatelessUserAuthentication',
        )
        ...
    }
  10. Enable the Token Blacklist app

    master

    To enable token blacklist functionality, add rest_framework_simplejwt.token_blacklist to your INSTALLED_APPS in settings.py and run the migrations.

    When enabled, Simple JWT automatically tracks generated refresh or sliding tokens in an outstanding tokens list and validates them against the blacklist before considering them valid.

    # Django project settings.py
    
    INSTALLED_APPS = (
        ...
        'rest_framework_simplejwt.token_blacklist',
        ...
    )