Skip to main content

JWT Authentication for Django Rest Framework and MongoDB

Project description

Mango-JWT is a minimal JWT User Authentication tool for Django Rest Framework and MongoDB. Recommended for developers using django-rest-framework and pymongo. Not supported in versions below Django 2.0.

pip install mango-jwt

Quick start

  1. Add “mongo_auth” to your INSTALLED_APPS setting below “rest_framework”:

    INSTALLED_APPS = [
        ...
        'rest_framework',
        'mongo_auth',
    ]
  2. Include the mongo_auth URLconf in your project urls.py like this:

    path('mongo_auth/', include('mongo_auth.urls')),
  3. Add DB config in settings.py :-

    # Minimal settings (all mandatory)
    MANGO_JWT_SETTINGS = {
        "db_host": "some_db_host", # Use srv host if connecting with MongoDB Atlas Cluster
        "db_port": "some_db_port", # Don't include this field if connecting with MongoDB Atlas Cluster
        "db_name": "for_example_auth_db",
        "db_user": "username",
        "db_pass": "password"
    }
    
    
    # Or use Advanced Settings (including optional settings)
    MANGO_JWT_SETTINGS = {
        "db_host": "some_db_host",
        "db_port": "some_db_port",
        "db_name": "for_example_auth_db",
        "db_user": "username",
        "db_pass": "password",
        "auth_collection": "name_your_auth_collection", # default is "user_profile"
        "fields": ("email", "password"), # default
        "jwt_secret": "secret", # default
        "jwt_life": 7, # default (in days)
        "secondary_username_field": "mobile" # default is None
    }

PLEASE NOTE: If you are connecting MongoDB Atlas Cluster, don’t include “db_port” and use srv host in “db_host” e.g. if your host is showing mongodb+srv://something.mongodb.net/test in your account, then use “something.mongodb.net” as your host.

  1. If secondary_username_field is provided, users will be able to login with this field as well as “email”. This is best for scenarios where you want users to login with either of their unique fields.

    For example, you may want users to login with “email” or “mobile”.

  2. You may or may not include “secondary_username_field” in “fields”.

    Note: “secondary_username_field” cannot be “email” as its “primary_username” and “secondary_username_field” will be set to None instead.

  3. Make a POST request on http://127.0.0.1:8000/mongo_auth/signup/ with body as :-

    {
        "email": "some_email@email.com",
        "password": "some_password",
        other_fields
        ...
    }
  4. Now login with these credentials at http://127.0.0.1:8000/mongo_auth/login/ :-

    {
        "username": "some_email@email.com or secondary_username_field_value",
        "password": "some_password"
    }
  5. This will return a JWT. Pass this JWT in your request in “Authorization” header.

AuthenticatedOnly

The AuthenticatedOnly permission class will only allow authenticated users to access your endpoint.

from rest_framework.views import APIView
from mongo_auth.permissions import AuthenticatedOnly
from rest_framework.response import Response
from rest_framework import status

class GetTest(APIView):

    permission_classes = [AuthenticatedOnly]

    def get(self, request, format=None):
        try:
            print(request.user)  # This is where magic happens
            return Response(status=status.HTTP_200_OK,
                            data={"data": {"msg": "User Authenticated"}})
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)

Or, if you’re using the @api_view decorator with function based views.

from mongo_auth.permissions import AuthenticatedOnly
from rest_framework.decorators import permission_classes
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status

@api_view(["GET"])
@permission_classes([AuthenticatedOnly])
def get_test(request):
    try:
        print(request.user)
        return Response(status=status.HTTP_200_OK,
                        data={"data": {"msg": "User Authenticated"}})
    except:
        return Response(status=status.HTTP_404_NOT_FOUND)

Don’t forget to pass “Authorization” Header in your requests while using your views with “AuthenticatedOnly” Permission Class.

mongo_auth.db.database

As the Mongo Connection Object has already been initialised in the package, you can use it directly:

from mongo_auth.db import database

print(list(database["collection_name"].find({}, {"_id": 0}).limit(10)))

More Info

  1. Passlib is used for password encryption with default scheme as “django_pbkdf2_sha256”.

  2. Only for Django 2.0 and above.

  3. Dependent on “django-rest-framework” and “pymongo”.

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

mango-jwt-1.3.2.tar.gz (6.2 kB view details)

Uploaded Source

Built Distribution

mango_jwt-1.3.2-py3-none-any.whl (7.8 kB view details)

Uploaded Python 3

File details

Details for the file mango-jwt-1.3.2.tar.gz.

File metadata

  • Download URL: mango-jwt-1.3.2.tar.gz
  • Upload date:
  • Size: 6.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.21.0 setuptools/39.0.1 requests-toolbelt/0.9.1 tqdm/4.42.0 CPython/3.7.1

File hashes

Hashes for mango-jwt-1.3.2.tar.gz
Algorithm Hash digest
SHA256 bda2164f7efba0644c707d3bc1638c66e5a1f76ada33eb8ad2890860a6776f39
MD5 1a5fbb59464dfbaa7d2ee8c14daa69b1
BLAKE2b-256 3398f7d6137aafbd7738f55bec1f46486be5190e882accafa33790615927fb05

See more details on using hashes here.

File details

Details for the file mango_jwt-1.3.2-py3-none-any.whl.

File metadata

  • Download URL: mango_jwt-1.3.2-py3-none-any.whl
  • Upload date:
  • Size: 7.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.21.0 setuptools/39.0.1 requests-toolbelt/0.9.1 tqdm/4.42.0 CPython/3.7.1

File hashes

Hashes for mango_jwt-1.3.2-py3-none-any.whl
Algorithm Hash digest
SHA256 8b9ff6581efbae38b148386e86963ee4fa3875d2d2ac4f682cc67759413ddf81
MD5 56c0a2fe0a25b3dc5c909e8341de5ecb
BLAKE2b-256 06bd5e1f237972abea0812a5332f4b51a406bf1353ea42e8c28212039d03b070

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page