JSON Web Token Authentication support for Django REST Framework

Overview

REST framework JWT Auth

Build Status Coverage

JSON Web Token Authentication support for Django REST Framework

Overview

This package provides JSON Web Token Authentication support for Django REST framework.

If you want to know more about JWT, check out the following resources:

Requirements

  • Python 2.7, 3.4+
  • Django 1.11+
  • Django REST Framework 3.7+

Installation

$ pip install drf-jwt

Documentation & Support

Full documentation for the project is available at docs.

Comments
  • Add multi key and key id support.

    Add multi key and key id support.

    This PR consists of two patches:

    • The first adds support for accepting multiple keys
    • The second adds support for named keys (with key ids)

    Please refer to the individual commit messages and the updated documentation.

    A changelog will be added to the PR if/when otherwise accepted.

    opened by nigoroll 31
  • Django 4.0 Support

    Django 4.0 Support

    Django 4.0 dropped today which removed django.conf.urls.url(). It looks like we're getting an import error here and subsequently here e.g.

    ImportError: Could not import 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'url' from 'django.urls' (/usr/local/lib/python3.8/dist-packages/django/urls/__init__.py).
    

    I did a bit of searching through the codebase and it looks like we could switch to re_path or path for this project but I'm not 100% sure. Wanted to file an issue to get the ball rolling on a solution.

    opened by acc248 13
  • Management command to obtain JWT token for a user

    Management command to obtain JWT token for a user

    I needed a simple management command to use during development, in order to obtain JWT token for my test user easier, I thought it might be helpful to open a PR on the main repo.

    opened by MahdiZareie 7
  • add JWT_AUTH_COOKIE_* settings paralleling django SESSION_COOKIE_*

    add JWT_AUTH_COOKIE_* settings paralleling django SESSION_COOKIE_*

    We add settings analogous to SESSION_COOKIE_* for the JWT cookie:

    'JWT_AUTH_COOKIE_DOMAIN': None
    'JWT_AUTH_COOKIE_PATH': None
    'JWT_AUTH_COOKIE_SECURE': True
    'JWT_AUTH_COOKIE_SAMESITE': 'Lax'
    

    with the following differences to django:

    • The HttpOnly attribute remains hardcoded as True in order to avoid unintended access from client code with addition of the Domain attribute.

    BREAKING CHANGES with this patch:

    This changes the default Secure attribute from False (actually None as in not present in Set-Cookie) to True. Users wishing to use JWT cookies over http (as in no TLS) need to set JWT_AUTH_COOKIE_SECURE to False.

    This change is intentional to follow common best common practice.

    CHANGES:

    Adds the default Samesite attribute Lax

    opened by nigoroll 6
  • custom JWT_RESPONSE_PAYLOAD_HANDLER negated by second call to view serializer

    custom JWT_RESPONSE_PAYLOAD_HANDLER negated by second call to view serializer

    https://github.com/Styria-Digital/django-rest-framework-jwt/blob/9d97eab9ad3df81e7418b20b6f2a9dea6e489a0b/src/rest_framework_jwt/views.py#L40

    The call to self.get_serializer at line 40 in BaseJSONWebTokenAPIView causes the payload created by api_settings.JWT_RESPONSE_PAYLOAD_HANDLER to be run back through the JSONWebTokenSerializer, effectively eliminating anything added to the payload by a custom handler other than the fields in JSONWebTokenSerializer. For example, the custom payload handler, that I wrote and have been successfully using with the original GetBlimp package, uses "authentication_token", rather than "token" to return the token, and includes some additional pieces of data, but with the new view, the only thing returned by the response is "email".

    opened by fablet 6
  • Fix buggy migration for 'blacklisted' token ids

    Fix buggy migration for 'blacklisted' token ids

    Fix decode call for migration.

    I don't care about verifying the token value here; if it got as far as the database, it's reasonable to expect it was valid when it was inserted.

    This was my mistake in Styria-Digital/django-rest-framework-jwt#84, which was released in v1.18.0, where I didn't test the migration properly with real data.

    opened by ashokdelphia 5
  • get_token_from_request can raise DjangoUnicodeDecodeError

    get_token_from_request can raise DjangoUnicodeDecodeError

    Python 3.6 and Django 2.2 , if there is some strange authentication header like Bearer \x9d

    Traceback (most recent call last):
      File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 493, in dispatch
        self.initial(request, *args, **kwargs)
      File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 410, in initial
        self.perform_authentication(request)
      File "/usr/local/lib/python3.6/site-packages/rest_framework/views.py", line 324, in perform_authentication
        request.user
      File "/usr/local/lib/python3.6/site-packages/rest_framework/request.py", line 220, in user
        self._authenticate()
      File "/usr/local/lib/python3.6/site-packages/rest_framework/request.py", line 373, in _authenticate
        user_auth_tuple = authenticator.authenticate(self)
      File "/usr/local/lib/python3.6/site-packages/rest_framework_jwt/authentication.py", line 66, in authenticate
        token = self.get_token_from_request(request)
      File "/usr/local/lib/python3.6/site-packages/rest_framework_jwt/authentication.py", line 91, in get_token_from_request
        authorization_header = force_str(get_authorization_header(request))
      File "/usr/local/lib/python3.6/site-packages/django/utils/encoding.py", line 69, in force_text
        raise DjangoUnicodeDecodeError(s, *e.args)
    django.utils.encoding.DjangoUnicodeDecodeError: 'utf-8' codec can't decode byte 0x9d in position 7: invalid start byte. You passed in b'Bearer \x9d' (<class 'bytes'>)
    
    opened by jayvdb 5
  • Deprecation Warnings In Django 3

    Deprecation Warnings In Django 3

    We recently updated from Django 2 to Django 3 and are now seeing quite a few deprecation warnings regarding RemovedInDjango40Warning: django.utils.translation.ugettext() is deprecated in favor of django.utils.translation.gettext() coming from this package.

    I believe this is caused by the try-catch block in compat.py being "reused" for multiple imports where the first line seems to fail in Django 3:

    https://github.com/Styria-Digital/django-rest-framework-jwt/blob/master/src/rest_framework_jwt/compat.py#L12

    It looks like url is not part of django.conf and therefore always raises ImportError:

    https://docs.djangoproject.com/en/3.0/ref/urls/

    I believe the following should fix the problem in compat.py, I'm just not completely sure if the middle block even makes sense or of it should be completely removed:

    try:
        from django.urls import include
    except ImportError:
        from django.conf.urls import include  # noqa: F401
    
    try:
      from django.urls import url
    except ImportError:
      from django.conf.urls import url
    
    try:
        from django.utils.translation import gettext as gettext_lazy
    except ImportError:
        from django.utils.translation import ugettext as gettext_lazy
    
    opened by dominik-bln 5
  • Fix/custom username payload

    Fix/custom username payload

    Basically this PR introduces two fixes when JWT_GET_USER_SECRET_KEY method is overridden,

    • If the payload contains a non-existent user, a validation error will be raised (same as when the method is not overridden). Previously, when this happened, an uncatched error from Django.
    • The jwt_get_secret_key method will now use the JWT_PAYLOAD_GET_USERNAME_HANDLER configuration.
    opened by paolodamico 5
  • Migrations fail on MySQL

    Migrations fail on MySQL

    The migrations for the new blacklist app fail because TextField can't have a unique constraint in MySQL: https://docs.djangoproject.com/en/2.2/ref/databases/#textfield-limitations . It fails with:

    BLOB/TEXT column 'token' used in key specification without a key length

    For now we can downgrade to 0.14.0 as we don't need the blacklist functionality yet, but this is a blocker for upgrading until not only a new migration fixes the problem, but the existing migration changes to not blow up on MySQL.

    bug good first issue 
    opened by jmbowman 5
  • Pass request to django's authenticate

    Pass request to django's authenticate

    Ciao, MR to fix upstream issue: https://github.com/jpadilla/django-rest-framework-jwt/issues/455 Also django-axes requires request in authenticate "RequestParameterRequired: AxesModelBackend requires calls to authenticate to pass request as an argument."

    opened by drozdowsky 5
  • Axes Authentication backend

    Axes Authentication backend

    I use Axes as authentication backend, but when set AXES_FAILURE_LIMIT ==2 in first login attempt the obtain-jwt-token return 403, while it must return 400 and if I call obtain-jwt-token again, it must return 403. I do not have this problem with https://github.com/jpadilla/django-rest-framework-jwt !

    opened by samaneh-kamalian 2
  • Session management

    Session management

    What is the best practice for restrict sessions in django-rest-framework-jwt? I mean admin restrict active session that means for example if userA login in computerA then when userA login from computerB, jwt in computerA is no longer valid and must login again.

    opened by samaneh-kamalian 0
  • How to set primary key for

    How to set primary key for "blacklist.BlacklistedToken"

    I included 'rest_framework_jwt.blacklist' in INSTALLED_APPS as mentioned in the official documentation. However, I am getting the following warning about auto-created primary key every time I run or migrate the DRF app:

    blacklist.BlacklistedToken:` (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
    	HINT: Configure the DEFAULT_AUTO_FIELD setting or the BlacklistedTokenConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'
    

    Simply removing the blacklist app from INSTALLED_APPS will no longer show this warning, but wanted to make sure to avoid any DB issues. How can I manually configure the primary key for the blacklist app?

    opened by tylertaewook 0
  • Async Support

    Async Support

    I'm dealing with a problem that seems related with this library (full traceback at the end)

     File "/home/gsp/.local/lib/python3.8/site-packages/rest_framework_jwt/authentication.py", line 86, in authenticate
        if BlacklistedToken.is_blocked(token, payload):
      File "/home/gsp/.local/lib/python3.8/site-packages/rest_framework_jwt/blacklist/models.py", line 58, in is_blocked
        return BlacklistedToken.objects.filter(query).exists()
    

    My project is web application that receives astronomical images and automatically triggers the reduction process and displays them in the browser. So the django views run synchronously with gunicorn as the server. There is also a websocket service that runs independently with daphne (async). Same container and django app though. The problem happens when the backend sends a notification via websockets that a new file has "arrived" into the system and the frontend (react) requests /gsp/api/files/ to get an updated list of files.

    I was wondering if there are plans to support async requests in the near future.

    Here is the full traceback.

    ERROR [2021-11-03 12:43:53,125] log Internal Server Error: /gsp/api/files/
    Traceback (most recent call last):
      File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
        response = get_response(request)
      File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
      File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
        return view_func(*args, **kwargs)
      File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
        return self.dispatch(request, *args, **kwargs)
      File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
        response = self.handle_exception(exc)
      File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
        self.raise_uncaught_exception(exc)
      File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
        raise exc
      File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 497, in dispatch
        self.initial(request, *args, **kwargs)
      File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 414, in initial
        self.perform_authentication(request)
      File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 324, in perform_authentication
        request.user
      File "/usr/local/lib/python3.8/site-packages/rest_framework/request.py", line 227, in user
        self._authenticate()
      File "/usr/local/lib/python3.8/site-packages/rest_framework/request.py", line 380, in _authenticate
        user_auth_tuple = authenticator.authenticate(self)
      File "/home/gsp/.local/lib/python3.8/site-packages/rest_framework_jwt/authentication.py", line 86, in authenticate
        if BlacklistedToken.is_blocked(token, payload):
      File "/home/gsp/.local/lib/python3.8/site-packages/rest_framework_jwt/blacklist/models.py", line 58, in is_blocked
        return BlacklistedToken.objects.filter(query).exists()
      File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 808, in exists
        return self.query.has_results(using=self.db)
      File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/query.py", line 552, in has_results
        return compiler.has_results()
      File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1145, in has_results
        return bool(self.execute_sql(SINGLE))
      File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1173, in execute_sql
        cursor = self.connection.cursor()
      File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 24, in inner
        raise SynchronousOnlyOperation(message)
    django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.
    
    opened by simontorres 0
  • Impersonation Token

    Impersonation Token

    Hello,

    Thank you for the awesome token authentication plugin.

    I need to implement the api where super user can become anyone and debug the issue. I found the documentation on the token impersonation, however, It doesn't explain much on how to setup the api. Could you please provide more details on the same preferably example?
    https://styria-digital.github.io/django-rest-framework-jwt/#impersonation-token

    Please let me know if you need anything else.

    Thank you

    opened by NiraliSupe 1
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Simple JWT 3.3k Jan 1, 2023
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Jazzband 3.2k Dec 29, 2022
A JSON Web Token authentication plugin for the Django REST Framework.

Simple JWT Abstract Simple JWT is a JSON Web Token authentication plugin for the Django REST Framework. For full documentation, visit django-rest-fram

Jazzband 3.2k Dec 28, 2022
CheckList-Api - Created with django rest framework and JWT(Json Web Tokens for Authentication)

CheckList Api created with django rest framework and JWT(Json Web Tokens for Aut

shantanu nimkar 1 Jan 24, 2022
This app makes it extremely easy to build Django powered SPA's (Single Page App) or Mobile apps exposing all registration and authentication related functionality as CBV's (Class Base View) and REST (JSON)

Welcome to django-rest-auth Repository is unmaintained at the moment (on pause). More info can be found on this issue page: https://github.com/Tivix/d

Tivix 2.4k Jan 3, 2023
Django CAS 1.0/2.0/3.0 client authentication library, support Django 2.0, 2.1, 2.2, 3.0 and Python 3.5+

django-cas-ng django-cas-ng is Django CAS (Central Authentication Service) 1.0/2.0/3.0 client library to support SSO (Single Sign On) and Single Logou

django-cas-ng 347 Dec 18, 2022
Authentication for Django Rest Framework

Dj-Rest-Auth Drop-in API endpoints for handling authentication securely in Django Rest Framework. Works especially well with SPAs (e.g React, Vue, Ang

Michael 1.1k Jan 3, 2023
Authentication for Django Rest Framework

Dj-Rest-Auth Drop-in API endpoints for handling authentication securely in Django Rest Framework. Works especially well with SPAs (e.g React, Vue, Ang

Michael 1.1k Jan 3, 2023
Django Rest Framework App wih JWT Authentication and other DRF stuff

Django Queries App with JWT authentication, Class Based Views, Serializers, Swagger UI, CI/CD and other cool DRF stuff API Documentaion /swagger - Swa

Rafael Salimov 4 Jan 29, 2022
Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication.

Welcome to django-allauth! Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (soc

Raymond Penners 7.7k Jan 1, 2023
Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication.

Welcome to django-allauth! Integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (soc

Raymond Penners 7.7k Jan 3, 2023
Django-react-firebase-auth - A web app showcasing OAuth2.0 + OpenID Connect using Firebase, Django-Rest-Framework and React

Demo app to show Django Rest Framework working with Firebase for authentication

Teshank Raut 6 Oct 13, 2022
User-related REST API based on the awesome Django REST Framework

Django REST Registration User registration REST API, based on Django REST Framework. Documentation Full documentation for the project is available at

Andrzej Pragacz 399 Jan 3, 2023
python-social-auth and oauth2 support for django-rest-framework

Django REST Framework Social OAuth2 This module provides OAuth2 social authentication support for applications in Django REST Framework. The aim of th

null 1k Dec 22, 2022
python-social-auth and oauth2 support for django-rest-framework

Django REST Framework Social OAuth2 This module provides OAuth2 social authentication support for applications in Django REST Framework. The aim of th

null 1k Dec 22, 2022
REST implementation of Django authentication system.

djoser REST implementation of Django authentication system. djoser library provides a set of Django Rest Framework views to handle basic actions such

Sunscrapers 2.2k Jan 1, 2023
Authentication Module for django rest auth

django-rest-knox Authentication Module for django rest auth Knox provides easy to use authentication for Django REST Framework The aim is to allow for

James McMahon 878 Jan 4, 2023
JSON Web Token implementation in Python

PyJWT A Python implementation of RFC 7519. Original implementation was written by @progrium. Sponsor If you want to quickly add secure token-based aut

José Padilla 4.5k Jan 9, 2023
Mock authentication API that acceccpts email and password and returns authentication result.

Mock authentication API that acceccpts email and password and returns authentication result.

Herman Shpryhau 1 Feb 11, 2022