Django--JWT认证
目录
1.安装配置
1.1 下载
pip install djangorestframework-jwt
1.2配置settings.py
- 注册应用
INSTALLED_APPS = [
'rest_framework_jwt',
]
1.3配置JWT验证
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_jwt.authentication.JSONWebTokenAuthentication', # 在 DRF中配置JWT认证
],
}
# jwt载荷中的有效期设置
JWT_AUTH = {
# token前缀:headers中 Authorization 值的前缀
'JWT_AUTH_HEADER_PREFIX': 'JWT',
# token有效期:一天有效
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1),
}
2.注册用户
2.1重写User表
from django.contrib.auth.models import AbstractUser
# 用户表
class User(AbstractUser):
email = models.CharField(max_length=255,null=True,blank=True)
phone = models.CharField(max_length=255,null=True,blank=True)
class Meta:
db_table = 'tb_user'
2.2生成Token
- 创建
MybaseView.py
from rest_framework_jwt.settings import api_settings
def creare_token(user):
# 生成jwt_token
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
print(token)
return token
2.3序列化器
from .models import *
from rest_framework import serializers
from django.contrib.auth.hashers import make_password
from .MybaseView import creare_token
# 注册用户
class CreateUserSerializers(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField()
email = serializers.CharField()
phone = serializers.CharField()
token = serializers.CharField(read_only=True)
def create(self, validated_data):
user = User.objects.create(**validated_data)
# 密码加密
password = make_password(validated_data.get('password'))
user.password = password
user.save()
token = creare_token(user)
user.token = token
return user
2.4views.py
# 注册用户
class UserView(APIView):
def post(self, request):
data = request.data
# print(data)
if not all(['username', 'password', 'password2', 'email', 'phone']):
return Response({'code': 202, 'msg': '参数不全'})
if data['password'] != data['password2']:
return Response({'code': 204, 'msg': '两次密码不一致'})
try:
user = CreateUserSerializers(data=data)
user.is_valid()
print(user.errors)
user.save()
return Response({'code': 200, 'msg': '创建用户成功', 'data': user.data})
except Exception as e:
return Response({'code': 201, 'msg': '创建失败,请重试'})
2.5 配置路由
urlpatterns = [
path('user/', views.UserView.as_view()),
]
2.6Postman测试
3.用户登录
3.1views.py
# 用户登录返回数据
def jwt_response_payload_handler(token, user=None, request=None):
return {
'userid': user.id,
'user': user.username,
'phone': user.phone,
'token': token
}
3.2配置路由
om rest_framework_jwt.views import obtain_jwt_token
urlpatterns = [
path('user/', views.UserView.as_view()), # 注册
path('login/', obtain_jwt_token), # 登录
]
3.3Postman测试
4.测试携带token才可访问接口
4.1views.py
# 登录状态才可查询用户
class UserInfoView(APIView):
permission_classes = [IsAuthenticated] # 接口中加权限
authentication_classes = [JSONWebTokenAuthentication]
def get(self, request):
user = User.objects.all()
obj = UserInfoSerializers(user, many=True)
return Response({'code': 200, 'msg': '查询成功', "data": obj.data})
4.2序列化器
class UserInfoSerializers(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id','username','phone','email')
4.3配置路由
urlpatterns = [
path('user/', views.UserView.as_view()), # 注册
path('login/', obtain_jwt_token), # 登录
path('get_user/', views.UserInfoView.as_view()), # 测试登录状态访问接口
]