1 JWT安装
pip install djangorestframework-jwt==1.11.0
2 syl/settings.py 配置jwt载荷中的有效设置
import datetime # jwt载荷中的有效期设置 JWT_AUTH = { # 1.token前缀:headers中 Authorization 值的前缀 'JWT_AUTH_HEADER_PREFIX': 'JWT', # 2.token有效期:一天有效 ' 'JWT_EXPIRATION_DELTA':datetime.timedelta(days=1), # 3.刷新token:允许使用旧的token换新token 'JWT_ALLOW_REFRESH':True, # 4.token有效期:token在24小时内过期, 可续期token 'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(hours=24), # 5.自定义JWT载荷信息:自定义返回格式,需要手工创建 ' 'JWT_RESPONSE_PAYLOAD_HANDLER': 'user.utils.jwt_response_payload_handler', }
3 syl/settings.py JWT结合DRF进行认证权限配置
# 在DRF配置文件中开启认证和权限
REST_FRAMEWORK = { # 1.认证器(全局) 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication',# 使用session时的认证器 # 'rest_framework.authentication.BasicAuthentication'# 提交表单时的认证器 # 'rest_framework_jwt.authentication.JSONWebTokenAuthentication',# 在DRF中配置JWT认证 ], # 2.权限配置(全局): 顺序靠上的严格 'DEFAULT_PERMISSION_CLASSES': [ # 'rest_framework.permissions.IsAdminUser', # 管理员可以访问 'rest_framework.permissions.IsAuthenticated', # 认证用户可以访问 # 'rest_framework.permissions.IsAuthenticatedOrReadOnly', # 认证用户可以访问, 否则只能读取 'rest_framework.permissions.AllowAny', # 所有用户都可以访问 ], }
http://192.168.56.100:8888/user/login/