赞
踩
在现代 Web 开发中,用户认证和授权是一个非常重要的功能。为了提供一个安全且易于管理的用户系统,Django 提供了丰富的工具和功能。然而,随着前后端分离架构的流行,传统的会话认证方式逐渐被 JWT(JSON Web Token)所取代。JWT 是一种紧凑且自包含的方式,用于在各方之间安全地传输信息。本文将详细介绍如何使用 Django 和 JWT 实现一个完整的用户注册、登录和邮箱验证系统,帮助开发者快速构建一个安全可靠的用户认证机制。
首先,确保已经安装了 Django、Django REST framework 和 djangorestframework-simplejwt。
pip install django djangorestframework djangorestframework-simplejwt
创建一个新的 Django 项目和一个应用程序。
- django-admin startproject myproject
- cd myproject
- django-admin startapp myapp
在 myproject/settings.py
中,添加以下配置:
- INSTALLED_APPS = [
- ...
- 'rest_framework',
- 'myapp',
- 'rest_framework_simplejwt',
- 'django.contrib.sites',
- 'allauth',
- 'allauth.account',
- 'allauth.socialaccount',
- 'dj_rest_auth',
- 'dj_rest_auth.registration',
- 'rest_framework.authtoken',
- ]
-
- SITE_ID = 1
-
- REST_FRAMEWORK = {
- 'DEFAULT_AUTHENTICATION_CLASSES': (
- 'rest_framework_simplejwt.authentication.JWTAuthentication',
- ),
- }
-
- EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' # For testing email sending in console
在 myproject/urls.py
中,添加以下内容:
- from django.contrib import admin
- from django.urls import path, include
-
- urlpatterns = [
- path('admin/', admin.site.urls),
- path('api/', include('myapp.urls')),
- path('api/auth/', include('dj_rest_auth.urls')),
- path('api/auth/registration/', include('dj_rest_auth.registration.urls')),
- ]
在 myapp/models.py
中,定义用户模型(如果需要自定义用户模型):
- from django.contrib.auth.models import AbstractUser
- from django.db import models
-
- class CustomUser(AbstractUser):
- pass
在 myapp/serializers.py
中,创建序列化器:
- from rest_framework import serializers
- from django.contrib.auth.models import User
- from rest_framework_simplejwt.tokens import RefreshToken
-
- class RegisterSerializer(serializers.ModelSerializer):
- class Meta:
- model = User
- fields = ['username', 'password', 'email']
- extra_kwargs = {'password': {'write_only': True}}
-
- def create(self, validated_data):
- user = User.objects.create_user(
- username=validated_data['username'],
- password=validated_data['password'],
- email=validated_data['email']
- )
- return user
-
- class LoginSerializer(serializers.Serializer):
- username = serializers.CharField()
- password = serializers.CharField()
-
- def validate(self, data):
- user = authenticate(**data)
- if user and user.is_active:
- return user
- raise serializers.ValidationError("Incorrect Credentials")
在 myapp/views.py
中,定义视图:
- from rest_framework import generics
- from django.contrib.auth.models import User
- from rest_framework.response import Response
- from rest_framework_simplejwt.tokens import RefreshToken
- from .serializers import RegisterSerializer, LoginSerializer
-
- class RegisterView(generics.CreateAPIView):
- queryset = User.objects.all()
- serializer_class = RegisterSerializer
-
- class LoginView(generics.GenericAPIView):
- serializer_class = LoginSerializer
-
- def post(self, request, *args, **kwargs):
- serializer = self.get_serializer(data=request.data)
- serializer.is_valid(raise_exception=True)
- user = serializer.validated_data
- refresh = RefreshToken.for_user(user)
- return Response({
- 'refresh': str(refresh),
- 'access': str(refresh.access_token),
- })
在 myapp/urls.py
中,配置路由:
- from django.urls import path
- from .views import RegisterView, LoginView
-
- urlpatterns = [
- path('register/', RegisterView.as_view(), name='register'),
- path('login/', LoginView.as_view(), name='login'),
- ]
- python manage.py makemigrations
- python manage.py migrate
- python manage.py createsuperuser
python manage.py runserver
现在,可以通过以下 API 端点进行测试:
POST /api/register/
POST /api/login/
POST /api/auth/registration/
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。