本文默认认为你已经看完了上面所有的文章
settings.py
SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5), # token有效期5分钟 'REFRESH_TOKEN_LIFETIME': timedelta(days=1) # 刷新后token有效期延长1天}# 是的 这里对比起使用默认的simplejwt,可以不用在drf渲染器中增加'DEFAULT_AUTHENTICATION_CLASSES': (# ...# 'rest_framework_simplejwt.authentication.JWTAuthentication',# ),因为我在上面的文章中自定义了一个AUTHENTICATION
serializers.py
from rest_framework_simplejwt.serializers import TokenObtainPairSerializerfrom rest_framework.exceptions import AuthenticationFailed# 重写simplejwt中的获取tokenclass MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): """ 登录返回token和refresh :param attrs: :return: """ try: data = super().validate(attrs) response = { 'success': True, 'token': data['access'], 'refresh': data['refresh'], 'username': self.user.username # 具体返回什么自己决定 } return response except AuthenticationFailed as atf: print(atf) # 可以看具体是什么错误 return { 'success': 'false', 'errorMsg': 'username or password is error' }
view.py
from User.serializers import MyTokenObtainPairSerializerfrom rest_framework_simplejwt.views import TokenObtainPairViewclass MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer
urls.py