Aug. 29, 2024

Django Rest Framework Authentication With Jwt

By Admin Timpat
  • 5k
  • 5k
  • 5k

To create a Django API endpoint for registering a user and generating a JSON Web Token (JWT) using function-based views, you can follow these steps:

  1. Install the required packages:

    pip install django djangorestframework djangorestframework-simplejwt
  2. Create a Django project and app
    django-admin startproject myproject
    cd myproject
    python manage.py startapp myapp
    ​
  3. Configure Django settings in settings.py:

    INSTALLED_APPS = [
        ...
        'rest_framework',
        'myapp',
    ]
    
    REST_FRAMEWORK = {
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'rest_framework_simplejwt.authentication.JWTAuthentication',
        ],
    }
    
    SIMPLE_JWT = {
        'AUTH_HEADER_TYPES': ('JWT',),
    }
    

     

  4. Define the user registration and authentication endpoints in myapp/views.py:

    from rest_framework.decorators import api_view
    from rest_framework.response import Response
    from rest_framework import status
    from django.contrib.auth.models import User
    from rest_framework_simplejwt.tokens import RefreshToken
    
    @api_view(['POST'])
    def register_user(request):
        username = request.data.get('username')
        password = request.data.get('password')
    
        if not username or not password:
            return Response({'error': 'Please provide both username and password.'}, status=status.HTTP_400_BAD_REQUEST)
    
        try:
            user = User.objects.create_user(username=username, password=password)
            refresh = RefreshToken.for_user(user)
            return Response({'token': str(refresh.access_token)}, status=status.HTTP_201_CREATED)
        except:
            return Response({'error': 'Unable to register the user.'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    @api_view(['POST'])
    def authenticate_user(request):
        username = request.data.get('username')
        password = request.data.get('password')
    
        if not username or not password:
            return Response({'error': 'Please provide both username and password.'}, status=status.HTTP_400_BAD_REQUEST)
    
        try:
            user = User.objects.get(username=username)
            if user.check_password(password):
                refresh = RefreshToken.for_user(user)
                return Response({'token': str(refresh.access_token)}, status=status.HTTP_200_OK)
            else:
                return Response({'error': 'Invalid credentials.'}, status=status.HTTP_401_UNAUTHORIZED)
        except User.DoesNotExist:
            return Response({'error': 'Invalid credentials.'}, status=status.HTTP_401_UNAUTHORIZED)
    

    5. Define the API endpoints in myapp/urls.py:

    from django.urls import path
    from myapp import views
    
    urlpatterns = [
        path('register/', views.register_user, name='register_user'),
        path('authenticate/', views.authenticate_user, name='authenticate_user'),
    ]
    

    6.  Include the app URLs in the project urls.py:

    from django.urls import path, include
    
    urlpatterns = [
        ...
        path('api/', include('myapp.urls')),
    ]
    
     7.  Run the development server:
     
    python manage.py runserver
    ​

    Now you should be able to send POST requests to the following endpoints:

    Remember to replace localhost:8000 with the appropriate URL if you are running the server on a different host or port.

Prev Post
Next Post

Related Post

Leave a Comment

Comments

BACK TO TOP