Code Monkey home page Code Monkey logo

django-jwt-authentication's Introduction

Django JWT authentication with simple jwt (Refresh and Access tokens)

This is a boiler plate code to get started with Django authentication. This project can be used in 2 ways:

  1. Using this project as boiler plate code to get started with your project. It has users app already integrated which has JWT authentication configured with main project.

  2. Take users app from this project, then plug and play it with your project.

Frontend

Optional Boiler plate frontend for this project is available at frontend. It is made on Angular, and it has complete user authentication with this project's APIs.

Running the application

1. Using this project as boiler plate code.

  1. Clone this repository.

  2. Create a virtual environment inside root of the project.

$ python -m venv .venv

(Make sure you have pyenv installed)

  1. Activate virtual environment
$ source .venv/bin/activate

For later if you want to exit virtual env $ deactivate

  1. Install dependencies from requirements.txt
$ pip install -r requirements.txt

upgrade the pip if you are asked to in terminal.

  1. Make migrations and run server
$ python manage.py makemigrations
$ python manage.py migrate --run-syncdb
$ python manage.py runserver

2. Plug and play "users" app

  1. Copy users folder from this project and paste it in root of your own project.

  2. Install the following libraries:

$ pip install djangorestframework
$ pip install djangorestframework-simplejwt
  1. In project's main app's urls.py file add:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('auth/', include('users.urls')),
    ...
]
  1. In settings.py of project's main app, add following:
INSTALLED_APPS = [
    ...
    # These needs to be added
    'rest_framework',
    'rest_framework_simplejwt',
    'rest_framework_simplejwt.token_blacklist',
    'users'
]

DATABASES={...}
...
# This needs to be added
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}
...

DEFAULT_AUTO_FIELD = ...
# This needs to be added
AUTH_USER_MODEL = 'users.User'
  1. Now you can make migrations and run the app.

Endpoints available

1. User signup

POST /auth/register

This request doesn't need authorization header.

Creates new user. Body data:

{
   "first_name": "ऋषभ",
   "last_name": "बहल",
   "username": "abc",
   "email": "[email protected]",
   "password": "abc123"
}

Request response:

{
   "id": 47,
   "first_name": "ऋषभ",
   "last_name": "बहल",
   "username": "abc",
   "email": "[email protected]",
}

2. User login

POST /auth/token/

This request doesn't need authorization header.

Body data:

{
   "email": "[email protected]",
   "password": "abc123"
}

Request response:

{
   "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY1MzUwNjYyNiwiaWF0IjoxNjUzNDIwMjI2LCJqdGkiOiI0YTViMWM1NmY4ZWM0MjdiODRjMjZiZmU1MTljZDI1YyIsInVzZXJfaWQiOjJ9.b4dFB9EXDVzVk_PC_-YRLkqAHNkYSUXH16PO4FhIErg",
   "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjUzNDIwNTI2LCJpYXQiOjE2NTM0MjAyMjYsImp0aSI6IjRjZWNiOWFmNTRhNDRkYTE4NzE5ODgyNGFlYmE4ZWE0IiwidXNlcl9pZCI6Mn0.Zm8-iER46HtSlSfJf2Sz6cew2Jagj1OC1kC1rznm_mE"
}

3. User token from refresh token

POST /auth/token/refresh/

This request doesn't need authorization header.

Body data:

{
    "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY1MzQ2MjIwMiwiaWF0IjoxNjUzMzc1ODAyLCJqdGkiOiIzYzVhYWI3ZGM3MTc0ZWRhYmI0MzM3ZGU0OGJiMGYxOCIsInVzZXJfaWQiOjJ9.slznJK7HmcFVu0nYmfgGHhqsuEZxOOFbmgvHmKJP81s"
}

Request response:

{
    "access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjUzNDIwODIwLCJpYXQiOjE2NTM0MjA1MDcsImp0aSI6IjBlNzk1NDA0YWVkZDRhZTI5ZjEyYjA0MTQwYWQ3YzkzIiwidXNlcl9pZCI6Mn0.HbaNex9mBflz7XrAJcZ3tqdl6ikZlxb47eueOz29f3U"
}

4. Get logged in user details from authentication token

GET /auth/user

This request needs to have authorization header.

Body data: None

Request response:

{
   "id": 47,
   "first_name": "ऋषभ",
   "last_name": "बहल",
   "username": "abc",
   "email": "[email protected]",
}

5. Test to see if protected routes are working

GET /auth/test

This request needs to have authorization header.

Body data: None

Request response:

{
    "message": "Test, Successful"
}

6. Logout user

POST /auth/logout

This request needs to have authorization header.

Body data:

{
    "refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTY1MzQ2MjQ3OSwiaWF0IjoxNjUzMzc2MDc5LCJqdGkiOiJjYjA1OWYwNWY1YmY0OWM3OTNiMjc2NzhjMTNhZWQ1NSIsInVzZXJfaWQiOjJ9.x303spZ5d7Nd_kE2rCJS8okOsUnQdMV00afNQDlM7xY"
}

Request response: None (Status 205)

Logout end point blacklists the refresh token. Now this refresh token can't be used again.

The blacklist app also provides a management command, flushexpiredtokens, which will delete any tokens from the outstanding list and blacklist that have expired. You should set up a cron job on your server or hosting platform which runs this command daily.

How to authenticate rest of the routes in app?

In the endpoint definition in views.py add the following:

...
# Add below line
from rest_framework.permissions import IsAuthenticated
...

class TestView(APIView):
    # Add below line
    permission_classes = (IsAuthenticated, )

    def get(self, request):
        content = {'message': 'Test, Successful'}
        return Response(content)

How to fix Django cors error

https://dzone.com/articles/how-to-fix-django-cors-error

Testing

To run tests:

python manage.py test

For test coverage report

coverage run --source='users' manage.py test && coverage report && coverage html

For test coverage report of multiple apps

coverage run --source='users, your_app, your_app2' manage.py test && coverage report && coverage html

References

  1. https://django-rest-framework-simplejwt.readthedocs.io/en/latest/
  2. https://medium.com/django-rest/logout-django-rest-framework-eb1b53ac6d35
  3. https://www.youtube.com/watch?v=PUzgZrS_piQ

django-jwt-authentication's People

Contributors

rishabbahal9 avatar

Stargazers

 avatar Larissa Lunguinho avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.