### Install Development Dependencies Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/_sources/development_and_contributing.rst.txt Install the latest pip, setuptools, and the project in editable mode with development dependencies. This is the initial setup step for contributing. ```bash pip install --upgrade pip setuptools pip install -e .[dev] ``` -------------------------------- ### Install Django REST Framework Simple JWT Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/_sources/getting_started.rst.txt Install the library using pip. This is the basic installation command. ```console pip install djangorestframework-simplejwt ``` -------------------------------- ### Install with Cryptographic Dependencies Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/_sources/getting_started.rst.txt Install the library with optional cryptographic dependencies for RSA and ECDSA token encoding/decoding. This is recommended for requirements files. ```console pip install djangorestframework-simplejwt[crypto] ``` -------------------------------- ### Install Simple JWT Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html Install the djangorestframework-simplejwt package using pip. ```bash pip install djangorestframework-simplejwt ``` -------------------------------- ### Install Development Dependencies (Mac/zsh) Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/_sources/development_and_contributing.rst.txt For users on macOS or using zsh, escape the brackets in the installation command to correctly install development dependencies. ```bash pip install -e .[dev] ``` -------------------------------- ### Install Simple JWT with Crypto Dependencies Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/getting_started.html Install Simple JWT with optional cryptographic dependencies for RSA and ECDSA algorithms. This is recommended for requirements files. ```bash pip install djangorestframework-simplejwt[crypto] ``` -------------------------------- ### Install Python Versions with Pyenv Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/_sources/development_and_contributing.rst.txt Install specific Python minor versions using pyenv, which is a prerequisite for running tests across multiple Python environments with tox. ```bash pyenv install 3.10.x ``` -------------------------------- ### Run Tests with Tox Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/_sources/development_and_contributing.rst.txt Execute the test suite across all supported Python environments using tox. Ensure pyenv is installed and configured with the necessary Python versions. ```bash tox ``` -------------------------------- ### Access Protected View with Access Token Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/_sources/getting_started.rst.txt Use curl to send a GET request with an Authorization header containing the access token to access a protected view. ```bash curl \ -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiY29sZF9zdHVmZiI6IuKYgyIsImV4cCI6MTIzNDU2LCJqdGkiOiJmZDJmOWQ1ZTFhN2M0MmU4OTQ5MzVlMzYyYmNhOGJjYSJ9.NHlztMGER7UADHZJlxNG0WSi22a2KaYSfd1S-AuT7lU" \ http://localhost:8000/api/some-protected-view/ ``` -------------------------------- ### Configure Simple JWT Settings Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/_sources/settings.rst.txt Customize Simple JWT behavior by defining the SIMPLE_JWT dictionary in your Django project's settings.py. This example shows default values for various settings. ```python # Django project settings.py from datetime import timedelta ... SIMPLE_JWT = { "ACCESS_TOKEN_LIFETIME": timedelta(minutes=5), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": False, "BLACKLIST_AFTER_ROTATION": False, "UPDATE_LAST_LOGIN": False, "ALGORITHM": "HS256", "SIGNING_KEY": settings.SECRET_KEY, "VERIFYING_KEY": "", "AUDIENCE": None, "ISSUER": None, "JSON_ENCODER": None, "JWK_URL": None, "LEEWAY": 0, "AUTH_HEADER_TYPES": ("Bearer",), "AUTH_HEADER_NAME": "HTTP_AUTHORIZATION", "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "USER_AUTHENTICATION_RULE": "rest_framework_simplejwt.authentication.default_user_authentication_rule", "ON_LOGIN_SUCCESS": "rest_framework_simplejwt.serializers.default_on_login_success", "ON_LOGIN_FAILED": "rest_framework_simplejwt.serializers.default_on_login_failed", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", "TOKEN_USER_CLASS": "rest_framework_simplejwt.models.TokenUser", "JTI_CLAIM": "jti", "SLIDING_TOKEN_REFRESH_EXP_CLAIM": "refresh_exp", "SLIDING_TOKEN_LIFETIME": timedelta(minutes=5), "SLIDING_TOKEN_REFRESH_LIFETIME": timedelta(days=1), "TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainPairSerializer", "TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSerializer", "TOKEN_VERIFY_SERIALIZER": "rest_framework_simplejwt.serializers.TokenVerifySerializer", "TOKEN_BLACKLIST_SERIALIZER": "rest_framework_simplejwt.serializers.TokenBlacklistSerializer", "SLIDING_TOKEN_OBTAIN_SERIALIZER": "rest_framework_simplejwt.serializers.TokenObtainSlidingSerializer", "SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer", "CHECK_REVOKE_TOKEN": False, "REVOKE_TOKEN_CLAIM": "hash_password", "CHECK_USER_IS_ACTIVE": True, } ``` -------------------------------- ### Add Simple JWT to Installed Apps Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/_sources/getting_started.rst.txt Add 'rest_framework_simplejwt' to your Django project's INSTALLED_APPS in settings.py if you wish to use localizations/translations. ```python INSTALLED_APPS = [ ... 'rest_framework_simplejwt', ... ] ``` -------------------------------- ### Create .python-version file Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/_sources/development_and_contributing.rst.txt Create a .python-version file in the project directory to specify the Python versions for pyenv and tox to use for testing. ```bash cat > .python-version < .python-version < dict[str, str] Validates the provided attributes and returns a dictionary containing the sliding token. ``` -------------------------------- ### TokenBlacklistSerializer Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/rest_framework_simplejwt.html Serializer for blacklisting tokens. It inherits from the base Serializer and provides a validate method for token validation. ```APIDOC ## TokenBlacklistSerializer ### Description Serializer for blacklisting tokens. It inherits from the base Serializer and provides a validate method for token validation. ### Class rest_framework_simplejwt.serializers.TokenBlacklistSerializer ### Methods #### validate(attrs: dict[str, Any]) -> dict[Any, Any] Validates the provided attributes, typically used for token blacklisting operations. ``` -------------------------------- ### TokenVerifySerializer Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/rest_framework_simplejwt.html Serializer for verifying the validity of a token. It inherits from Serializer and provides a validate method for token verification. ```APIDOC ## TokenVerifySerializer ### Description Serializer for verifying the validity of a token. It inherits from Serializer and provides a validate method for token verification. ### Class rest_framework_simplejwt.serializers.TokenVerifySerializer ### Methods #### validate(attrs: dict[str, None]) -> dict[Any, Any] Validates the provided attributes to check token validity. ``` -------------------------------- ### Refresh Access Token with Refresh Token Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/_sources/getting_started.rst.txt Use curl to send a POST request with the refresh token to obtain a new JWT access token when the current one expires. ```bash curl \ -X POST \ -H "Content-Type: application/json" \ -d '{"refresh":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImNvbGRfc3R1ZmYiOiLimIMiLCJleHAiOjIzNDU2NywianRpIjoiZGUxMmY0ZTY3MDY4NDI3ODg5ZjE1YWMyNzcwZGEwNTEifQ.aEoAYkSJjoWH1boshQAaTkf8G3yn0kapko6HFRt7Rh4"}' \ http://localhost:8000/api/token/refresh/ ``` -------------------------------- ### TokenObtainSerializer Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/rest_framework_simplejwt.html Base serializer for obtaining tokens. It defines default error messages and provides methods for token retrieval. ```APIDOC ## TokenObtainSerializer ### Description Base serializer for obtaining tokens. It defines default error messages and provides methods for token retrieval. ### Class rest_framework_simplejwt.serializers.TokenObtainSerializer ### Attributes - **default_error_messages** (dict[str, str]): Default error messages for authentication failures. - **token_class** (type[Token] | None): The token class to be used for token generation. - **username_field** (str): The field name for the username. ### Methods #### get_token(user: AuthUser) -> Token Class method to generate a token for a given user. #### validate(attrs: dict[str, Any]) -> dict[Any, Any] Validates the provided attributes and returns a dictionary containing token-related information. ``` -------------------------------- ### JWTAuthentication Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/rest_framework_simplejwt.html Authenticates requests using a JSON web token provided in a request header. It handles token validation and user retrieval. ```APIDOC ## Class: JWTAuthentication ### Description An authentication plugin that authenticates requests through a JSON web token provided in a request header. ### Methods - **authenticate(request)**: Authenticate the request and return a two-tuple of (user, token). - **authenticate_header(request)**: Return a string for the WWW-Authenticate header or None. - **get_header(request)**: Extracts the header containing the JSON web token. - **get_raw_token(header)**: Extracts an unvalidated JSON web token from the "Authorization" header. - **get_user(validated_token)**: Attempts to find and return a user using the given validated token. - **get_validated_token(raw_token)**: Validates an encoded JSON web token and returns a validated token wrapper object. ### Attributes - **default_error_messages**: Dictionary of default error messages. - **media_type**: The media type for JSON. - **www_authenticate_realm**: The realm for WWW-Authenticate header. ``` -------------------------------- ### TokenUser Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/rest_framework_simplejwt.html A dummy user class used with JWTStatelessUserAuthentication for stateless user objects backed by validated tokens. ```APIDOC ## Class: TokenUser ### Description A dummy user class modeled after django.contrib.auth.models.AnonymousUser. Used in conjunction with the JWTStatelessUserAuthentication backend to implement single sign-on functionality across services which share the same secret key. JWTStatelessUserAuthentication will return an instance of this class instead of a User model instance. Instances of this class act as stateless user objects which are backed by validated tokens. ### Methods - **check_password(raw_password)**: Checks if the provided raw password matches. - **delete()**: Deletes the user. - **get_all_permissions(obj=None)**: Returns all permissions for the user. - **get_group_permissions(obj=None)**: Returns group permissions for the user. - **get_username()**: Returns the username. - **has_module_perms(module)**: Checks if the user has module permissions. - **has_perm(perm, obj=None)**: Checks if the user has a specific permission. - **has_perms(perm_list, obj=None)**: Checks if the user has a list of permissions. - **save()**: Saves the user. - **set_password(raw_password)**: Sets the user's password. ### Properties - **groups**: Returns the user's groups. - **id**: The user's ID. - **is_anonymous**: Boolean indicating if the user is anonymous. - **is_authenticated**: Boolean indicating if the user is authenticated. - **is_staff**: Boolean indicating if the user is staff. - **is_superuser**: Boolean indicating if the user is a superuser. - **pk**: The primary key of the user. - **user_permissions**: Returns the user's permissions. - **username**: The user's username. ### Initialization - **__init__(token)**: Initializes the TokenUser with a validated token. ``` -------------------------------- ### Decorate JWT Views for drf-yasg Schema Generation Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/drf_yasg_integration.html Use this code to decorate your JWT views when integrating with `drf-yasg`. It ensures correct OpenAPI schema generation by defining custom response serializers for each token view. ```python from drf_yasg.utils import swagger_auto_schema from rest_framework import serializers, status from rest_framework_simplejwt.views import ( TokenBlacklistView, TokenObtainPairView, TokenRefreshView, TokenVerifyView, ) class TokenObtainPairResponseSerializer(serializers.Serializer): access = serializers.CharField() refresh = serializers.CharField() def create(self, validated_data): raise NotImplementedError() def update(self, instance, validated_data): raise NotImplementedError() class DecoratedTokenObtainPairView(TokenObtainPairView): @swagger_auto_schema( responses={ status.HTTP_200_OK: TokenObtainPairResponseSerializer, } ) def post(self, request, *args, **kwargs): return super().post(request, *args, **kwargs) class TokenRefreshResponseSerializer(serializers.Serializer): access = serializers.CharField() def create(self, validated_data): raise NotImplementedError() def update(self, instance, validated_data): raise NotImplementedError() class DecoratedTokenRefreshView(TokenRefreshView): @swagger_auto_schema( responses={ status.HTTP_200_OK: TokenRefreshResponseSerializer, } ) def post(self, request, *args, **kwargs): return super().post(request, *args, **kwargs) class TokenVerifyResponseSerializer(serializers.Serializer): def create(self, validated_data): raise NotImplementedError() def update(self, instance, validated_data): raise NotImplementedError() class DecoratedTokenVerifyView(TokenVerifyView): @swagger_auto_schema( responses={ status.HTTP_200_OK: TokenVerifyResponseSerializer, } ) def post(self, request, *args, **kwargs): return super().post(request, *args, **kwargs) class TokenBlacklistResponseSerializer(serializers.Serializer): def create(self, validated_data): raise NotImplementedError() def update(self, instance, validated_data): raise NotImplementedError() class DecoratedTokenBlacklistView(TokenBlacklistView): @swagger_auto_schema( responses={ status.HTTP_200_OK: TokenBlacklistResponseSerializer, } ) def post(self, request, *args, **kwargs): return super().post(request, *args, **kwargs) ``` -------------------------------- ### TokenRefreshView Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/rest_framework_simplejwt.html Provides an endpoint for refreshing an access token using a refresh token. ```APIDOC ## POST /token/refresh/ ### Description Refresh an access token using a valid refresh token. ### Method POST ### Endpoint /token/refresh/ ### Parameters #### Request Body - **refresh** (string) - Required - The refresh token. ### Request Example { "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." } ### Response #### Success Response (200) - **access** (string) - A new access token. #### Response Example { "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." } ``` -------------------------------- ### JWTStatelessUserAuthentication Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/rest_framework_simplejwt.html A stateless authentication plugin that authenticates requests via a JSON web token without database lookups. ```APIDOC ## Class: JWTStatelessUserAuthentication ### Description An authentication plugin that authenticates requests through a JSON web token provided in a request header without performing a database lookup to obtain a user instance. ### Methods - **get_user(validated_token)**: Returns a stateless user object backed by the given validated token. ### Inheritance Bases: `JWTAuthentication` ``` -------------------------------- ### TokenRefreshView Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/rest_framework_simplejwt.html This view takes a refresh token and returns a new access token if the refresh token is valid. ```APIDOC ## POST /token/refresh/ ### Description Refresh an access token using a valid refresh token. ### Method POST ### Endpoint /token/refresh/ ### Parameters #### Request Body - **refresh** (string) - Required - The refresh token. ### Response #### Success Response (200) - **access** (string) - The new access token. ``` -------------------------------- ### TokenRefreshSlidingView Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/rest_framework_simplejwt.html This view takes a sliding token and returns a new, refreshed version if the token's refresh period has not expired. ```APIDOC ## POST /token/sliding/refresh/ ### Description Refresh a sliding token if its refresh period has not expired. ### Method POST ### Endpoint /token/sliding/refresh/ ### Parameters #### Request Body - **token** (string) - Required - The sliding token to refresh. ### Response #### Success Response (200) - **token** (string) - The refreshed sliding token. ``` -------------------------------- ### TokenRefreshSerializer Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/rest_framework_simplejwt.html Serializer for refreshing an existing access token. It inherits from Serializer and provides validation for token refresh. ```APIDOC ## TokenRefreshSerializer ### Description Serializer for refreshing an existing access token. It inherits from Serializer and provides validation for token refresh. ### Class rest_framework_simplejwt.serializers.TokenRefreshSerializer ### Attributes - **default_error_messages** (dict[str, str]): Default error messages for token refresh failures. ### Methods #### validate(attrs: dict[str, Any]) -> dict[str, str] Validates the provided attributes and returns a dictionary containing the new access token. ``` -------------------------------- ### UntypedToken Class Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/rest_framework_simplejwt.html Represents a token without a specific type, useful for general signature validation. ```APIDOC ## class rest_framework_simplejwt.tokens.UntypedToken ### Description Represents a token without a specific type, useful for general validation of signature and other properties not related to token type. ### Attributes - **lifetime**: `datetime.timedelta` - Set to 0, indicating no specific lifetime. - **token_type**: `str` - The type of the token, set to 'untyped'. ### Methods - **verify_token_type()**: Untyped tokens do not verify the 'token_type' claim. ``` -------------------------------- ### Decorate JWT Views for drf-yasg Schema Generation Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/_sources/drf_yasg_integration.rst.txt Use this code to decorate your JWT View definitions when using drf-yasg to generate correct OpenAPI schemas. This is necessary because simplejwt serializers are not symmetric. It includes custom serializers and decorated views for TokenObtainPairView, TokenRefreshView, TokenVerifyView, and TokenBlacklistView. ```python from drf_yasg.utils import swagger_auto_schema from rest_framework import serializers, status from rest_framework_simplejwt.views import ( TokenBlacklistView, TokenObtainPairView, TokenRefreshView, TokenVerifyView, ) class TokenObtainPairResponseSerializer(serializers.Serializer): access = serializers.CharField() refresh = serializers.CharField() def create(self, validated_data): raise NotImplementedError() def update(self, instance, validated_data): raise NotImplementedError() class DecoratedTokenObtainPairView(TokenObtainPairView): @swagger_auto_schema( responses={ status.HTTP_200_OK: TokenObtainPairResponseSerializer, } ) def post(self, request, *args, **kwargs): return super().post(request, *args, **kwargs) class TokenRefreshResponseSerializer(serializers.Serializer): access = serializers.CharField() def create(self, validated_data): raise NotImplementedError() def update(self, instance, validated_data): raise NotImplementedError() class DecoratedTokenRefreshView(TokenRefreshView): @swagger_auto_schema( responses={ status.HTTP_200_OK: TokenRefreshResponseSerializer, } ) def post(self, request, *args, **kwargs): return super().post(request, *args, **kwargs) class TokenVerifyResponseSerializer(serializers.Serializer): def create(self, validated_data): raise NotImplementedError() def update(self, instance, validated_data): raise NotImplementedError() class DecoratedTokenVerifyView(TokenVerifyView): @swagger_auto_schema( responses={ status.HTTP_200_OK: TokenVerifyResponseSerializer, } ) def post(self, request, *args, **kwargs): return super().post(request, *args, **kwargs) class TokenBlacklistResponseSerializer(serializers.Serializer): def create(self, validated_data): raise NotImplementedError() def update(self, instance, validated_data): raise NotImplementedError() class DecoratedTokenBlacklistView(TokenBlacklistView): @swagger_auto_schema( responses={ status.HTTP_200_OK: TokenBlacklistResponseSerializer, } ) def post(self, request, *args, **kwargs): return super().post(request, *args, **kwargs) ``` -------------------------------- ### Custom Token Claims Serializer Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/customizing_token_claims.html Subclass TokenObtainPairSerializer to add custom claims to the generated token. This method is called by the view to create the token. ```python 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 ``` -------------------------------- ### TokenObtainPairSerializer Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/rest_framework_simplejwt.html Serializer for obtaining a pair of access and refresh tokens. It inherits from TokenObtainSerializer and customizes token generation. ```APIDOC ## TokenObtainPairSerializer ### Description Serializer for obtaining a pair of access and refresh tokens. It inherits from TokenObtainSerializer and customizes token generation. ### Class rest_framework_simplejwt.serializers.TokenObtainPairSerializer ### Methods #### validate(attrs: dict[str, Any]) -> dict[str, str] Validates the provided attributes and returns a dictionary containing the access and refresh tokens. ``` -------------------------------- ### TokenRefreshSlidingSerializer Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/rest_framework_simplejwt.html Serializer for refreshing a sliding token. It inherits from Serializer and provides validation for sliding token refresh. ```APIDOC ## TokenRefreshSlidingSerializer ### Description Serializer for refreshing a sliding token. It inherits from Serializer and provides validation for sliding token refresh. ### Class rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer ### Attributes - **default_error_messages** (dict[str, str]): Default error messages for sliding token refresh failures. ### Methods #### validate(attrs: dict[str, Any]) -> dict[str, str] Validates the provided attributes and returns a dictionary containing the new sliding token. ``` -------------------------------- ### Custom Token Claims Serializer Source: https://django-rest-framework-simplejwt.readthedocs.io/en/latest/_sources/customizing_token_claims.rst.txt Subclass TokenObtainPairSerializer to add custom claims to the generated token. This method is called when a new token is created. ```python 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 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.