django-admin startproject miapiNext, install Django Rest Framework and djangorestframework_simplejwt, which will be our base tools for creating and managing the API and secure handling using JWT:
pip install djangorestframework djangorestframework-simplejwtCreating the User Model
Our project will need a basic model to manage users. We can extend the User model provided by Django or create a completely new one. In our case, let\'s extend the base model:
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
passRemember to register this model in the admin panel to facilitate its management and perform the necessary migrations.
Building the API
With the model ready, we proceed to create an application within the project to handle the logic related to users.
python manage.py startapp usersAdd it to the installed applications in the settings.py file and configure the necessary paths to generate functional endpoints:
etc.
# urls.py
from django.urls import path
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),
]
Secure Handling with JWT
This is where JWT comes into play. Token-based authentication offers not only security but also flexibility by enabling stateless sessions, which are ideal for APIs.
| Traditional System | JWT System |
|---|---|
| Session stored on the server. | Session represented by a token stored on the client. |
| Efficient but not scalable. | Efficient and scalable. |
Make sure to define Properly set the necessary permissions within the system to restrict access to your API to only those users who are correctly authenticated. This is done in each view or in a dedicated views.py file.
Continuous Maintenance
Django greatly facilitates maintaining a healthy lifecycle for our applications thanks to its ability to integrate with various tools such as web maintenance tools. Don\'t forget to add unit tests, monitor logs, and set up early warnings for potential vulnerabilities.
Comments
0Be the first to comment