首先,我的项目结构是这样的
1.安装djangorestframework-jwt
pip install djangorestframework-jwt
2.setting.py配置
#rest_framework配置
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
# 'rest_framework_simplejwt.authentication.JWTAuthentication', # JWT认证,在前面的认证方案优先
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
),
}
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), # JWT_EXPIRATION_DELTA 指明token的有效期
'JWT_AUTH_HEADER_PREFIX': 'JWT', # 默认的
}
# from apps import bjnews
AUTH_USER_MODEL = 'bjnews.UserModel' #自定义user类,一定要配置,否则就是drf默认的
AUTHENTICATION_BACKENDS=(
"bjnews.views.CustomBackend", #自定义登录验证
)
3.User类的继承(迁移至数据库)
#之所以继承AbstractBaseUser是因为它的字段比其他的感觉少一些
#如果继承AbstractBaseUser不继承PermissionsMixin,登录能正常登录,但是再次使用token时回报失效,具体底层我也不是特别清楚,感觉是权限问题;只有继承PermissionsMixin才能使用django的用户权限模块
from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin,AbstractUser
from .UserManage import UserManager
# Create your models here.
class UserModel(AbstractBaseUser,PermissionsMixin):
"""用户表"""
# password = models.CharField(max_length=128,null=False,verbose_name="密码")
objects = UserManager()
phone_num = models.CharField(max_length=16,null=False,verbose_name="电话号")
company = models.CharField(max_length=32,verbose_name="公司名")
username = models.CharField(max_length=32,verbose_name="姓名",null=False)
email = models.CharField(max_length=24,verbose_name="邮箱",null=False)
userID = models.IntegerField(verbose_name="用户ID