While there are many answers to this question, none of the answers (as of my writing) addresses the critical security concern, the password validation that is defined in settings.AUTH_PASSWORD_VALIDATORS
. So it is possible to create a password like '1'
which must not be acceptable. So I have fixed this major security issue. Here is my solution:
In serializers.py:
from django.contrib.auth import get_user_model
from django.contrib.auth.password_validation import validate_password
from rest_framework import serializers
class SignupSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ['username', 'first_name', 'last_name', 'email', 'password', ]
extra_kwargs = {
'password': {'write_only': True}
}
def validate_password(self, value):
validate_password(value)
return value
def create(self, validated_data):
user = get_user_model()(**validated_data)
user.set_password(validated_data['password'])
user.save()
return user
In views.py:
from rest_framework import mixins, viewsets
from rest_framework.permissions import AllowAny, IsAuthenticated
from . import forms, serializers
class SignupViewSet(mixins.CreateModelMixin,
viewsets.GenericViewSet):
permission_classes = [AllowAny]
serializer_class = serializers.SignupSerializer
API Response:
Now, if you try with a simple password like '1'
, this response will be returned automatically:
{
"password": [
"This password is too short. It must contain at least 8 characters.",
"This password is too common.",
"This password is entirely numeric."
]
}
In case of a password like '12345678'
, the response is:
{
"password": [
"This password is too common.",
"This password is entirely numeric."
]
}
In this way, the end-client will know exactly what else are required for the password to be valid.