安装配置
pip install djangorestframework-jwt
配置Setting.py
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(days=1), }
在序列化器中添加token属性 并且生成token
from rest_framework_jwt.settings import api_settings class CreateUserSerializer(serializers.ModelSerializer): """ 创建用户序列化器 """ ... token = serializers.CharField(label='登录状态token', read_only=True) # 增加token字段 class Meta: ... fields = ('id', 'username', 'password', 'password2', 'sms_code', 'mobile', 'allow', 'token') # 增加token ... def create(self, validated_data): """ 创建用户 """ # 移除数据库模型类中不存在的属性 del validated_data['password2'] del validated_data['sms_code'] del validated_data['allow'] user = super().create(validated_data) # 调用django的认证系统加密密码 user.set_password(validated_data['password']) user.save() # 补充生成记录登录状态的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) user.token = token return user
在js前端 保存token
var vm = new Vue({ ... methods: { on_submit: function(){ axios.post(...) .then(response => { // 记录用户的登录状态 sessionStorage.clear(); localStorage.clear(); localStorage.token = response.data.token; localStorage.username = response.data.username; localStorage.user_id = response.data.user_id; location.href = '/index.html'; }) .catch(...) } }
未完待续