``## Day 1
It's already four days into the #100daysofMiva coding challenge. ๐๐๐ป
๐ Dive into Django: Building a Secure User Authentication API from Scratch!
Are you ready to take your Django skills to the next level? ๐ In this tutorial, Iโll be guiding you through creating a robust user authentication API using Django. Whether you're a seasoned developer or just starting, this step-by-step guide will walk you through setting up user registration, login, and token-based authentication.
By the end of this session, you'll have a solid understanding of how to:
- Setup a Django project and configure essential packages
- Create and customize serializers for user data
- Build views to handle user registration and authentication
- Implement token-based authentication for secure API access
- Join us as we transform a blank canvas into a powerful authentication system, and unlock new possibilities in your Django journey! ๐๐
Letโs get coding! ๐ปโจ
Step 1: Set up your Django environment:
To do this you need to have python installed: Ensure Python is installed by running:
macOS/Linux:
Python is often pre-installed. You can check by running:
or
If needed, install Python via Homebrew (macOS) or package manager (Linux):
Windows:
- Download and install Python from python.org.
- Ensure you check the box to add Python to your PATH during installation.
Step 2. Set Up a Virtual Environment:
macOS/Linux:
Create and activate a virtual environment:
Windows:
Create and activate a virtual environment:
Step 3. Install Django and Packages
Now what is a framework without its packages๐คจ...let's install the packages we will need.๐
With the virtual environment activated, the commands to install Django and additional packages are the same across all operating systems:
-
djangorestframework
: This is a powerful and flexible toolkit for building Web APIs with Django. -
djangorestframework-simplejwt
: This package provides JSON Web Token (JWT) authentication, which is commonly used for secure API authentication.
Step 4. Create and Configure the Django Project
macOS/Linux/Windows:
Create a Django project and app:
let us simplify the necessary things:
-
startproject1
: This command creates a new Django project. A project is a collection of settings for an instance of Django, including database configuration, Django-specific options, and application-specific settings. -
startapp
: This creates a new app within the project. Apps are components of your project that handle specific functionality (e.g., user management).
Step 5. Update Project Settings
All OS:
Modify settings.py to include your app and installed packages.
File: auth_project/settings.py
Explanation shall we๐:
INSTALLED_APPS
: This is where you register your apps and third-party packages. Here, you add rest_framework for the API functionality, rest_framework_simplejwt for JWT authentication, and users (the app you created) for managing user-related tasks.
It's okay not to know all the steps at once...it just takes practice, you'll get it right
I hope you're following...it's not hard it's complex๐
(I don't know if that worked๐)...
moving on...๐ช
Keep your eyes up from here on guys๐
Step 6. Creating Serializers
File: users/serializers.py
Explanation:
-
**Serializers**
: In Django REST Framework, serializers are used to convert complex data types (like Django models) into JSON, and vice versa. -
**RegisterSerializer**
: This custom serializer handles user registration. It includes fields like username, password, email, etc. -
**validate_password**
: Ensures the password meets certain security criteria. -
**validate method**
: Custom validation to check if the two password fields match. -
**create**
method: This method is responsible for creating and saving the new user.
Step 7: Creating Views
File: users/views.py
-
**Views**
: In Django, views handle the logic for processing user requests. -
**RegisterView**
: This view handles user registration. -
**CreateAPIView**
: A built-in view for handling the creation of new records. Here, itโs used to create a new user. -
**permission_classes**
: AllowAny means that this endpoint is accessible to anyone, even unauthenticated users, which is necessary for registration.
Step 8: Setting Up URLs
File: users/urls.py
This code is written in the app's URL
Explanation:
URL Patterns: These define the paths that map to the views.
**register/**
: This URL will handle user registration.
Then go to your Project's File: **auth_project/urls.py**
and type this...๐
Explanation:
-
**include('users.urls')**
: This includes the users app's URLs. - JWT Views:
TokenObtainPairView
: This view returns a pair of access and refresh tokens.TokenRefreshView
: This view allows clients to refresh the access token using the refresh token. -
**TokenObtainPairView**
: This view returns a pair of access and refresh tokens. -
**TokenRefreshView**
: This view allows clients to refresh the access token using the refresh token.
Unto the next here you can rest well๐...no pressure from here onward hehe..
Step 9: Running Migrations
Command:
The function/ purpose of doing this is that it applies changes to your database schema based on the models and fields you've defined in your project. the ones we've orchestrated above๐
In other words, it keeps the project up to date
Step 10: Running the Server and Testing
Command:
This command starts the Django development server, making your project accessible locally. (your local port)
Now let's see what we've done so far...
Testing with Postman or cURL(you can download this extension from your IDE)
Using Postman
Open Postman (or any API testing tool you prefer).
Set up a new request
- 1. URL: http://127.0.0.1:8000/api/auth/register/
- 2. Method: POST
In the Body tab, select raw and JSON format.
Enter the following JSON data:
Body:
- Click Send.
For this part, the Django-Rest Framework has a friendly user interface so it's easier to navigate here than others
If successful, you should receive a response with HTTP status code 201 Created and a JSON response containing the user data.
Test the Token Authentication Endpoint
To ensure JWT authentication is working, test the token endpoint.
Using Postman:
- Set up a new request: Method: POST URL: http://127.0.0.1:8000/api/token/
- In the Body tab, select raw and JSON format.
- Enter the following JSON data
4, Click Send.
You should receive a JSON response with access and refresh tokens:
**
Troubleshooting Tips
**
Server Not Starting: Ensure you're in the correct directory and have activated your virtual environment.
Endpoint Errors: Double-check your URL paths and ensure your Django app is correctly set up with the URLs.
Invalid Responses: Verify that your API endpoints and serializers are correctly configured.
By following these steps, you should be able to successfully run your Django development server, test the registration endpoint, and verify token-based authentication.
Top comments (5)
Awesome!
Thnx๐ซฑ๐ปโ๐ซฒ๐พ
Why not use django-oauth-toolkit and get a more secure implementation?
thnx for the suggestion by the way...really appeciate
I want to proceed slowly so that others can understand and follow along smoothly with me.