Rest Api With Django Using Bearer Token

Rest Api With Django Using Bearer Token

Run this command to create api folder

python manage.py startapp api

Step 1.  Add this code in a setting.py file

INSTALLED_APPS = [
   // other packages
    'api.apps.ApiConfig',  # or just 'api' if you don't need custom AppConfig
    'rest_framework',
    'rest_framework.authtoken',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'api.auth.BearerTokenAuthentication',  # Use our custom class
    ]
}

Step 2. Create auth_decorators.py file in api folder

from rest_framework.decorators import authentication_classes, permission_classes
from rest_framework.authentication import TokenAuthentication


from rest_framework.permissions import IsAuthenticated

def protected(view_func):
    """Decorator to add token authentication to any view"""
    return authentication_classes([TokenAuthentication])(
        permission_classes([IsAuthenticated])(view_func)
    )

Step 3. create auth.py file in api folder

# api/auth.py (create this new file)
from rest_framework.authentication import TokenAuthentication

class BearerTokenAuthentication(TokenAuthentication):
    keyword = 'Bearer'  # This changes "Token" to "Bearer" in headers

step 4. create auth_view.py file in views folder

# api/views/auth_view.py
from rest_framework import status
from rest_framework.authtoken.models import Token
from django.contrib.auth import authenticate
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny

@api_view(['POST'])
@permission_classes([AllowAny])
def auth_login(request):
    username = request.POST.get('username')
    password = request.POST.get('password')

    if not username or not password:
        return Response(
            {'error': 'Please provide both username and password'},
            status=status.HTTP_400_BAD_REQUEST
        )

    user = authenticate(username=username, password=password)

    if not user:
        return Response(
            {'error': 'Invalid Credentials'},
            status=status.HTTP_401_UNAUTHORIZED
        )

    token, created = Token.objects.get_or_create(user=user)
    return Response({
        'access': token.key,  # Changed from 'token' to 'access' (JWT-style)
        'user_id': user.pk,
        'email': user.email,
        'username': user.username
    })

Step 5. add this file __init__.py in views folder

# from .user_view import UserListView
from .auth_view import auth_login

Step 6. make user_view.py file in views folder

from rest_framework.views import APIView
from rest_framework.response import Response
# from api.models.user_model import User  # Explicit import
# from api.serializers.user_serializer import UserSerializer  # Explicit import

class UserListView(APIView):
    def post(self, request):
        # users = User.objects.all()
        # serializer = UserSerializer(users, many=True)
        # return Response(serializer.data)
        return Response({})

Step 7. add this code in urls.py

from django.urls import path
from api.views.user_view import UserListView
from api.views.auth_view import auth_login  # Import the function directly

from .auth_decorators import protected

urlpatterns = [
    path('login/', auth_login, name='login'),
    path('users/', protected(UserListView.as_view()), name='user-list'),
]

This is file structure

djangoapi/
├─ api/
│    ├── __pycache__/
│    ├── models/
│    ├── serializers/
│    ├── views/
│           ├── __pycache__/
│           ├── __init__.py
│           ├── auth_view.py
│           ├── user_view.py
│    ├── apps.py
│    ├── auth.py
│    ├── auth_decorators.py
│    └── urls.py
├── djangoapi/ (inner project folder)
├── db.sqlite3
└── manage.py

0 Comments

Leave a Reply

You must be logged in to post a comment.