Token Authentication part 2 (Registration)

Token Authentication(registration):

Token Authentication is commonly used to provide a secure way for clients to authenticate and access protected resources. Here’s how to implement user registration with token generation.

1. Install djangorestframework-authtoken

pip install djangorestframework-authtoken

2. Add Installed Apps (in settings.py)

INSTALLED_APPS = [

    ‘django.contrib.admin’,

    ‘django.contrib.auth’,

    ‘django.contrib.contenttypes’,

    ‘django.contrib.sessions’,

    ‘django.contrib.messages’,

    ‘django.contrib.staticfiles’,

    ‘rest_framework’,

    ‘rest_framework.authtoken’,  # Add this for token authentication

    ‘books’,  # Your app

]

3. Set Up REST Framework Authentication (in settings.py)

REST_FRAMEWORK = {

    ‘DEFAULT_AUTHENTICATION_CLASSES’: [

        ‘rest_framework.authentication.TokenAuthentication’,

    ],

    ‘DEFAULT_PERMISSION_CLASSES’: [

        ‘rest_framework.permissions.IsAuthenticated’,

    ],

}

4. Create User Registration View

books/views.py

from rest_framework import status

from rest_framework.response import Response

from rest_framework.decorators import api_view

from django.contrib.auth.models import User

from rest_framework.authtoken.models import Token

 

from rest_framework import status

from rest_framework.response import Response

from rest_framework.decorators import api_view, permission_classes

from rest_framework.permissions import AllowAny  # Import AllowAny permission

from django.contrib.auth.models import User

from rest_framework.authtoken.models import Token

 

@api_view([‘POST’])

@permission_classes([AllowAny])  # Allow access to everyone

def register(request):

    username = request.data.get(‘username’)

    password = request.data.get(‘password’)

    

    if not username or not password:

        return Response({“error”: “Username and password are required.”}, status=status.HTTP_400_BAD_REQUEST)

    

    if User.objects.filter(username=username).exists():

        return Response({“error”: “User with this username already exists.”}, status=status.HTTP_400_BAD_REQUEST)

    

    user = User.objects.create_user(username=username, password=password)

    token, created = Token.objects.get_or_create(user=user)

    

    return Response({

        “message”: “User registered successfully.”,

        “token”: token.key

    }, status=status.HTTP_201_CREATED)

Explanation:

from rest_framework import status

Imports the status module from rest_framework, which provides useful HTTP status codes like HTTP_200_OK, HTTP_201_CREATED, HTTP_400_BAD_REQUEST, etc.

 

from rest_framework.response import Response

Imports the Response class used to create HTTP responses in Django REST Framework (DRF).

 

It formats the response as JSON by default.

 

from rest_framework.decorators import api_view, permission_classes

api_view: A decorator that restricts allowed request methods to a particular view. For example, if you pass [‘POST’], only POST requests will be allowed.

 

permission_classes: A decorator used to override the default permission settings for a particular view.

 

from rest_framework.permissions import AllowAny

Imports the AllowAny permission class, which grants unrestricted access to a view.

 

Without this, the global IsAuthenticated permission would block unauthenticated users from accessing this view.

 

from django.contrib.auth.models import User

Imports the User model from Django’s authentication system.

 

You will use this model to create and query user accounts.

 

from rest_framework.authtoken.models import Token

Imports the Token model from rest_framework.authtoken.

 

A Token object is created for each user and serves as an authentication credential.

 

 View Function: register()

 

@api_view([‘POST’])

@permission_classes([AllowAny])

@api_view([‘POST’]): Ensures the view only accepts POST requests.

 

@permission_classes([AllowAny]): Overrides the global IsAuthenticated permission to allow unauthenticated users to access this view.

 

Necessary because this view handles user registration, which requires open access.

 

def register(request):

Defines the register function, which accepts a request object as a parameter.

 

The request object contains information about the HTTP request sent by the client.

 

    username = request.data.get(‘username’)

    password = request.data.get(‘password’)

Extracts the username and password from the request body.

 

request.data is a DRF feature that works for POST, PUT, and PATCH requests, parsing the incoming JSON data.

 

  if not username or not password:

        return Response({“error”: “Username and password are required.”}, status=status.HTTP_400_BAD_REQUEST)

Validates that both username and password are provided.

 

Returns a 400 Bad Request response if either field is missing.

 

  if User.objects.filter(username=username).exists():

        return Response({“error”: “User with this username already exists.”}, status=status.HTTP_400_BAD_REQUEST)

Checks if a user with the given username already exists in the database.

 

Returns a 400 Bad Request response if the username is already taken.

 

    user = User.objects.create_user(username=username, password=password)

Creates a new user in the database using Django’s create_user() method.

 

This method automatically hashes the password before saving it.

 

    token, created = Token.objects.get_or_create(user=user)

Generates a token for the newly created user using Token.objects.get_or_create().

 

If the user already has a token, it returns the existing one.

 

Otherwise, it creates a new token.

 

  return Response({

        “message”: “User registered successfully.”,

        “token”: token.key

    }, status=status.HTTP_201_CREATED)

Returns a JSON response with a success message and the token associated with the user.

 

The status code 201 CREATED indicates that the registration process was successful.

Summary:

  • The view allows anyone to access it (AllowAny).

 

  • It validates the incoming data (username and password).

 

  • Checks for username duplication.

 

  • Creates a new user if validation passes.

 

  • Generates a token for that user.

 

  • Returns the token to the user.

5. Create URL for Registration

books/urls.py

from django.urls import path

from . import views

urlpatterns = [

    path(‘register/’, views.register, name=’register’),

]

Explanation:

from django.urls import path

from . import views

Imports the path function from django.urls, used to define URL patterns.

 

Imports your views module to connect your URL patterns with view functions.

 

urlpatterns = [

    path(‘register/’, views.register, name=’register’),

]

Defines a list called urlpatterns which holds all URL patterns for your app.

 

This is the standard way Django maps URLs to views.

 

path() function:

 

The first argument (‘register/’) is the URL pattern. When you access http://127.0.0.1:8000/api/register/, this view will be triggered.

 

The second argument (views.register) is the view function that will handle requests to this URL. In this case, it’s your register() function from books/views.py.

 

The third argument (name=’register’) gives a name to this URL pattern for easier reference in templates or when using reverse URL lookup.

 

✅ What This Achieves

By adding this URL pattern, you have made your register() view accessible through the endpoint: http://127.0.0.1:8000/api/register/

 

You can now send POST requests to this endpoint to register new users.

6. Migrate Database to Create Token Model

python manage.py makemigrations

python manage.py migrate

7. Testing Registration with Postman

URL:

POST http://127.0.0.1:8000/api/register/

 

Request Body: (JSON)

{

    “username”: “newuser”,

    “password”: “newpassword123”

}

 

Response: (Successful Registration)

{

    “message”: “User registered successfully.”,

    “token”: “abcd1234efgh5678ijkl9101….”

}

8. Explanation

  • User Creation: Creates a new user with a username and password.

  • Token Generation: Generates a unique token for the user after successful registration.

  • Token Storage: The token is stored in the authtoken_token table in the database.

  • Security: The token must be included in the headers to access protected endpoints.

Exercise:

  • Create a register/ endpoint to register users.

  • Register a new user and verify login via token works.

Course Video in English