I’m currently working on a Django project where I need to implement a mock authorization service to simulate the integration of an authentication system. The goal is to ensure that each API request is authenticated and authorized using tokens from the mock authorization provider.
Here are the details of my current setup:
urls.py:
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from rest_framework.authtoken import views as authtoken_views
from security.views import SecurityRecordViewSet, UserCreate
router = routers.DefaultRouter()
router.register(r'security-records', SecurityRecordViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include(router.urls)),
path('api-token-auth/', authtoken_views.obtain_auth_token),
path('register/', UserCreate.as_view(), name='user-create'),
]
models.py:
from django.db import models
class SecurityRecord(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.name
serializers.py:
from django.contrib.auth.models import User
from rest_framework import serializers
from .models import SecurityRecord
class SecurityRecordSerializer(serializers.ModelSerializer):
class Meta:
model = SecurityRecord
fields = ['id', 'name', 'description']
def validate(self, attrs):
name = attrs.get('name', '')
if len(name) < 5:
raise serializers.ValidationError('Name must be at least 5 characters long.')
description = attrs.get('description', '')
if len(description) < 10:
raise serializers.ValidationError('Description must be at least 10 characters long.')
return super().validate(attrs)
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'password', 'email']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User.objects.create_user(
username=validated_data['username'],
email=validated_data['email'],
password=validated_data['password'],
)
return user
views.py:
from rest_framework import generics, viewsets, status, permissions
from rest_framework.response import Response
from django.contrib.auth.models import User
from .models import SecurityRecord
from .serializers import SecurityRecordSerializer, UserSerializer
class UserCreate(generics.CreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class SecurityRecordViewSet(viewsets.ModelViewSet):
queryset = SecurityRecord.objects.all()
serializer_class = SecurityRecordSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
settings.py:
...
INSTALLED_APPS = [
.....
'rest_framework',
'security',
'rest_framework.authtoken',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
],
}
...
I want to create a mock authorization service to issue tokens and validate them for authentication and authorization in my API requests. How can I achieve this in my Django project?
What I have tried so far:
- Created a new app mockauth to handle mock token issuance and validation.
- Defined a serializer for tokens.
- Created views to issue and validate tokens.
- Updated urls.py to include endpoints for token operations.