pipthablack / Django-Backend-basicauth

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Django JWT Authentication with Simple JWT

This project demonstrates how to implement JWT (JSON Web Tokens) authentication in a Django project using the rest_framework_simplejwt library.

Installation

  1. Install Django and Django REST framework:
pip install django djangorestframework
  1. Install rest_framework_simplejwt:
pip install djangorestframework_simplejwt
  1. Add the required apps to your INSTALLED_APPS in your Django project's settings.py file:
INSTALLED_APPS = [
    ...
    'rest_framework',
    'rest_framework_simplejwt.token_blacklist',
]
  1. Configure the authentication backend in your settings.py file:
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}
  1. Add the JWT URLs to your project's urls.py file:
from django.urls import path, include
from rest_framework_simplejwt.views import (
    TokenObtainPairView,
    TokenRefreshView,
)

urlpatterns = [
    ...
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]

Usage

  1. Create a Django user using the createsuperuser command:
python manage.py createsuperuser
  1. Start your Django development server:
python manage.py runserver
  1. Use a tool like Postman or curl to obtain a JWT token by sending a POST request to http://localhost:8000/api/token/ with the username and password of the created user.

  2. Use the obtained access token in subsequent requests to your API by including it in the Authorization header with the format Bearer <access_token>.

Additional Resources

About


Languages

Language:Python 100.0%