Skip to main content

JWT-based authentication for Django REST Framework

Project description

jwtauth

A JWT-based authentication system for Django REST Framework.

🪄 Installation

This package is not available on the pip registry yet. To install it, download the compressed package from here, extract it and then run:

python3 -m pip install jwtauth-0.0.1.tar.gz

⚙️ Configuration

Add jwtauth to your INSTALLED_APPS:

INSTALLED_APPS = [
    'jwtauth',
]

Add jwtauth.JwtAuthentication to the REST framework list of authentication classes in your settings file:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'jwtauth.JwtAuthentication',
        # ...
    ],
    # ...
}

Then, add jwtauth.middleware.AuthenticationMiddleware to the list of middleware classes:

MIDDLEWARE = [
    'jwtauth.middleware.AuthenticationMiddleware',
    # ...
]

You can now run python manage.py migrate to create the models.

📕 Usage

Use the login method to create a JWT token for the user and store it in the cookies, so that in the next requests the user will be authenticated. For example:

from jwtauth import login


@api_view(['POST'])
def login_view(request):
    body = JSONParser().parse(request)

    # use an authentication backend to validate the credentials
    user = authenticate(
        username=body['username'],
        password=body['password']
    )

    if user is None:
        # credentials are not valid
        raise AuthenticationFailed('Invalid username or password.', 403)

    # login the user
    login(request, user)
    
    return Response(status=204)

To invalidate the tokens and logout the user, simply invoke the logout method, passing the request:

from jwtauth import logout

@api_view(['DELETE'])
def logout_view(request):
    # logout the user
    logout(request)
    
    return Response(status=204)

To check if a user is logged in, you can use REST framework's permissions:

from rest_framework.permissions import IsAuthenticated


# function view with permission decorator
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def logged_view(request):
    # only for logged users, otherwise a 403 Forbidden response is returned
    return Response(status=204)

Equivalently, using class views:

from rest_framework.permissions import IsAuthenticated


# class view with permission attribute
class LoggedView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # only for logged users, otherwise a 403 Forbidden response is returned
        return Response(status=204)

You can also rely on the request.user attribute to access the logged user (or Django's AnonymousUser if the user is not logged in):

@api_view(['GET'])
def my_view(request):

    if request.user.is_authenticated:
        # do something with the logged user
        # ...

    # user is not logged in
    # ...

🚫 Limitations

  • This is a prototype, not ready to be used in production.
  • Active tokens and blacklisted tokens are not automatically deleted from the database after they expire.
  • Authentication through header Authorization: Bearer is not yet supported.
  • Tokens are not encrypted in the database.

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_cookie_jwtauth-0.0.1.tar.gz (10.3 kB view details)

Uploaded Source

Built Distribution

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

drf_cookie_jwtauth-0.0.1-py3-none-any.whl (10.1 kB view details)

Uploaded Python 3

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