1.settings
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,接口对接需要设置为true
'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',
}
2.utils.py
def jwt_response_payload_handler(token, user=None, request=None, role=None):
"""
自定义jwt认证成功返回数据
:token 返回的jwt
:user 当前登录的用户信息[对象]
:request 当前本次客户端提交过来的数据
:role 角色
"""
if user.first_name:
name = user.first_name
else:
name = user.username
return {
'authenticated': 'true',
'id': user.id,
"role": role,
'name': name,
'username': user.username,
'email': user.email,
'token': token,
}
3.serializer.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class UserSerializer(serializers.ModelSerializer):
'''
用户序列化器
'''
#显示多对多字段
roles = serializers.SerializerMethodField(required=False)
name = serializers.CharField(source='username',required=False)
class Meta:
model = User #具体对那个表进行序列化
fields = '__all__' #要操作的字段 __all__代表所有
read_only_fields = ('id',)
extra_kwargs = {
'password':{
'min_length':3, #给密码设置最小长度
'default':'123' #默认值为123
}
}
def create(self,data):
print(data)
username = data.get('username')
password = data.get('password')
mobile = data.get('mobile')
email = data.get('email')
user = User(username=username,mobile=mobile,email=email)
user.set_password(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
serializer.py
4.urls.py
from rest_framework_jwt.views import obtain_jwt_token,refresh_jwt_token
urlpatterns = [
path('login/', obtain_jwt_token), # 获取token,登录视图
path('refresh/', refresh_jwt_token), # 刷新token
]