Skip to main content

Django Rest Framework JWT 2FA

Project description

This package provides a Two Factor Authentication for Django Rest Framework using JSON Web Tokens. The implementation is based on another DRF authentication library called Simple JWT.

PyPI Coverage

Overview

The authentication flow uses two JWT tokens and a verification code:

  • First a token called Code Token is requested by providing username and password. If the username and the password are correct, a random (7 digit) verification code is generated and sent by e-mail to the user’s e-mail address. This verification code is hashed with the Django’s password hasher and the hash is included to the Code Token.

  • After the verification code is received a second token called Authentication Token can be requested. The request is done by sending the Code Token and the verification code to another endpoint. If the token and the code are correct, an authentication token is returned. This authentication token can be used to authenticate the following API requests. With default configuration this authentication token is an access token and its accompanied with a refresh token. They are in the same format as the JWT tokens of the Simple JWT.

Requirements

  • Python 3.10 or newer

  • Django 2.2 or newer

  • Django Rest Framework

  • Simple JWT

Installation

Install the package from PyPI with:

pip install drf-jwt-2fa

Configuration

Configure Django Rest Framework to use the provided authentication class by adding something like this to the settings:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'drf_jwt_2fa.authentication.Jwt2faAuthentication',
    ]
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}

Note: Authentication token endpoint can return different kind of tokens based on token_class property of the class configured as the TOKEN_OBTAIN_SERIALIZER for Simple JWT.

The URLs for the authentication API endpoints can be configured with something like this in an urls.py:

import drf_jwt_2fa.urls
from django.conf.urls import include, url

urlpatterns = [
    url(r'^auth/', include(drf_jwt_2fa.urls)),
]

or by configuring each view individually:

from django.urls import include, path
from drf_jwt_2fa.views import obtain_auth_token, obtain_code_token

urlpatterns = [
    path('get-code-token/', obtain_code_token),
    path('get-auth-token/', obtain_auth_token),
]

Additional Settings

There are some additional settings that you can override. Here are all the available settings with their default values:

JWT2FA_AUTH = {
    # Length of the verification code (digits)
    'CODE_LENGTH': 7,

    # Characters used in the verification code
    'CODE_CHARACTERS': '0123456789',

    # Secret key to use for signing the Code Tokens
    'CODE_TOKEN_SECRET_KEY': hash_string('2fa-code-' + settings.SECRET_KEY),

    # Secret string to extend the verification code with
    'CODE_EXTENSION_SECRET': hash_string('2fa-ext-' + settings.SECRET_KEY),

    # How long the code token is valid
    'CODE_EXPIRATION_TIME': datetime.timedelta(minutes=5),

    # Number of bytes to use for the code token JTI (JWT ID)
    'CODE_TOKEN_JTI_BYTES': 16,  # 16 bytes = 128 bits

    # Throttle limit for code token requests from same IP
    'CODE_TOKEN_THROTTLE_RATE': '12/3h',

    # How much time must pass between verification attempts, i.e. to
    # request authentication token with a with the same code token and a
    # verification code
    'AUTH_TOKEN_RETRY_WAIT_TIME': datetime.timedelta(seconds=2),

    # Maximum number of failed verification attempts allowed per code
    # token before the token is invalidated and further attempts are
    # rejected with HTTP 403.  Set to None to disable the limit.
    'MAX_AUTH_ATTEMPTS_PER_CODE_TOKEN': 5,

    # Maximum number of unexpired code tokens a user may have at a time.
    # Requesting a new code token when the limit is reached returns
    # HTTP 429.  Set to None to disable the limit.
    'MAX_ACTIVE_CODE_TOKENS_PER_USER': 3,

    # Name of the keys for the token values in the dictionary returned
    # by the ObtainAuthToken view
    'AUTH_RESULT_ACCESS_TOKEN_KEY': 'access',
    'AUTH_RESULT_REFRESH_TOKEN_KEY': 'refresh',
    'AUTH_RESULT_OTHER_TOKEN_KEY': 'token',

    # Function that sends the verification code to the user
    'CODE_SENDER': 'drf_jwt_2fa.sending.send_verification_code_via_email',

    # From Address used by the e-mail sender
    'EMAIL_SENDER_FROM_ADDRESS': settings.DEFAULT_FROM_EMAIL,

    # Set to this to a (translated) string to override the default
    # message subject of the e-mail sender
    'EMAIL_SENDER_SUBJECT_OVERRIDE': None,

    # Set to this to a (translated) string to override the default
    # message body of the e-mail sender
    'EMAIL_SENDER_BODY_OVERRIDE': None,
}

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

drf_jwt_2fa-1.0.0.tar.gz (20.5 kB view details)

Uploaded Source

Built Distribution

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

drf_jwt_2fa-1.0.0-py3-none-any.whl (23.4 kB view details)

Uploaded Python 3

File details

Details for the file drf_jwt_2fa-1.0.0.tar.gz.

File metadata

  • Download URL: drf_jwt_2fa-1.0.0.tar.gz
  • Upload date:
  • Size: 20.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.5 {"installer":{"name":"uv","version":"0.10.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for drf_jwt_2fa-1.0.0.tar.gz
Algorithm Hash digest
SHA256 4a8c939e296599a008722aa40995ab77ecd490dc9a89e9ee0dcda75179b000b6
MD5 45b1943fb6dc56ad9029191e443ce573
BLAKE2b-256 a77652119bfc8f8459bbbb0d03cf519bd21ac60e67610d770aaca0b926f1ee9c

See more details on using hashes here.

File details

Details for the file drf_jwt_2fa-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: drf_jwt_2fa-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 23.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.5 {"installer":{"name":"uv","version":"0.10.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for drf_jwt_2fa-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5fa3d7ea49248c1f96b2979a16f9463a22e882d9ec7bac34fd877375569364a8
MD5 ad76d15873c79aa8cb1dd494db79d7f2
BLAKE2b-256 36764b4acec5b2503e379991bebdf39c4b3a18302177c53ee22b4bd909752b75

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