authentication.py 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. from rest_framework.authentication import BaseAuthentication
  2. from rest_framework.exceptions import AuthenticationFailed
  3. import json
  4. from utils.util_jwt import jwt_decoding
  5. import jwt
  6. from jwt import exceptions
  7. class JwtAutentication(BaseAuthentication):
  8. def authenticate(self, request):
  9. # token = request.query_params.get('')
  10. token = None
  11. if request.method == 'POST':
  12. token = json.loads(request.body)["user_token"]
  13. elif request.method == 'GET':
  14. token = request.query_params.get('user_token')
  15. SALT = 'django-insecure-zo64fvv02msf-se7!dek5*w$17#3nh6zta#!i=79bt9d#f88@i'
  16. try:
  17. payload = jwt.decode(token, SALT, True)
  18. except exceptions.ExpiredSignatureError:
  19. raise AuthenticationFailed({'code': 1003, "error": "token已失效"})
  20. except jwt.DecodeError:
  21. raise AuthenticationFailed({'code': 1003, 'error': "token认证失败"})
  22. except jwt.InvalidTokenError:
  23. raise AuthenticationFailed({'code': 1003, 'error': "非法token"})
  24. return payload, token