本文默认认为你已经看完了上面所有的文章

settings.py

  1. SIMPLE_JWT = {
  2. 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), # token有效期5分钟
  3. 'REFRESH_TOKEN_LIFETIME': timedelta(days=1) # 刷新后token有效期延长1天
  4. }
  5. # 是的 这里对比起使用默认的simplejwt,可以不用在drf渲染器中增加'DEFAULT_AUTHENTICATION_CLASSES': (
  6. # ...
  7. # 'rest_framework_simplejwt.authentication.JWTAuthentication',
  8. # ),因为我在上面的文章中自定义了一个AUTHENTICATION

serializers.py

  1. from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
  2. from rest_framework.exceptions import AuthenticationFailed
  3. # 重写simplejwt中的获取token
  4. class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
  5. def validate(self, attrs):
  6. """
  7. 登录返回token和refresh
  8. :param attrs:
  9. :return:
  10. """
  11. try:
  12. data = super().validate(attrs)
  13. response = {
  14. 'success': True,
  15. 'token': data['access'],
  16. 'refresh': data['refresh'],
  17. 'username': self.user.username # 具体返回什么自己决定
  18. }
  19. return response
  20. except AuthenticationFailed as atf:
  21. print(atf) # 可以看具体是什么错误
  22. return {
  23. 'success': 'false',
  24. 'errorMsg': 'username or password is error'
  25. }

view.py

  1. from User.serializers import MyTokenObtainPairSerializer
  2. from rest_framework_simplejwt.views import TokenObtainPairView
  3. class MyTokenObtainPairView(TokenObtainPairView):
  4. serializer_class = MyTokenObtainPairSerializer

urls.py