Mastering Django: Building a Secure User Authentication API from Scratch

mayowa-kalejaiye - Aug 23 - - Dev Community

``## 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:

  1. Setup a Django project and configure essential packages
  2. Create and customize serializers for user data
  3. Build views to handle user registration and authentication
  4. Implement token-based authentication for secure API access
  5. 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! πŸ’»βœ¨

Final result

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:
Python installation on macOS/Linux
or
Python installation on macOS/Linux
If needed, install Python via Homebrew (macOS) or package manager (Linux):
Image description

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:

Setting Up Virtual Environment

Windows:

Create and activate a virtual environment:

Setting Up 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:

Installing Django and Packages
Explanation:
`

  1. djangorestframework: This is a powerful and flexible toolkit for building Web APIs with Django.
  2. 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:

Image description
let us simplify the necessary things:

  1. 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.
  2. 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

Update Project Settings

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

Creating Serializers

Explanation:

  1. **Serializers**: In Django REST Framework, serializers are used to convert complex data types (like Django models) into JSON, and vice versa.
  2. **RegisterSerializer**: This custom serializer handles user registration. It includes fields like username, password, email, etc.
  3. **validate_password**: Ensures the password meets certain security criteria.
  4. **validate method**: Custom validation to check if the two password fields match.
  5. **create** method: This method is responsible for creating and saving the new user.

Step 7: Creating Views

File: users/views.py

Creating Views
Explanation:

  1. **Views**: In Django, views handle the logic for processing user requests.
  2. **RegisterView**: This view handles user registration.
  3. **CreateAPIView**: A built-in view for handling the creation of new records. Here, it’s used to create a new user.
  4. **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

Setting Up URLs

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...😁

Setting Up URLs

Explanation:

  1. **include('users.urls')**: This includes the users app's URLs.
  2. 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.
  3. **TokenObtainPairView**: This view returns a pair of access and refresh tokens.
  4. **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:

Running Migrations

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:

Running the Server and Testing

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

  1. Open Postman (or any API testing tool you prefer).

  2. Set up a new request

  1. In the Body tab, select raw and JSON format.

  2. Enter the following JSON data:
    Body:

Testing with Postman

  1. 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:

  1. Set up a new request: Method: POST URL: http://127.0.0.1:8000/api/token/
  2. In the Body tab, select raw and JSON format.
  3. Enter the following JSON data

Using Postman

4, Click Send.
You should receive a JSON response with access and refresh tokens:

Image description

**

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.

. . . .
Terabox Video Player