Django 配置JWT验证

1.setting.py配置

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',  # 配置验证方式为Token验证
    ),
}
JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),  # Token 过期时间为一周
    'JWT_ALLOW_REFRESH': False,
    'JWT_AUTH_HEADER_PREFIX': 'JWT'  # Token的头为:JWT adfefdfajei342323423
}
@staticmethod
def generate_jwt_token(user):
   """生成Jwt验证码"""
   jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
   jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
   payload = jwt_payload_handler(user)
   return jwt_encode_handler(payload)

token = self.generate_jwt_token(user)  # 获取Token,并返回给前端
serializer = self.get_serializer(user)
return Response({'user': serializer.data, 'token': token})

这样配置之后,用户只需要每次登陆之后获取JWT验证码,然后每次前端请求的时候在请求头带JWT验证码就可以

Authorization: JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjobGciOiJIbmFtZSI6InJvb3QiLCJleHAiOjE1Q4OTMsNjc5OTImVtYWlsIjoiIn0.vvOno44OHCJODu1GV_Zq8t7MqRqJneP1Qkp--4Xklgq

 

posted @ 2019-09-03 09:55 前方、有光 阅读(...) 评论(...) 编辑 收藏