rest_framework_simplejwt实现无感知刷新token, 且自定义token信息及能更改刷新token逻辑
1.生成token方式及自定义荷载信息
from rest_framework_simplejwt.tokens import RefreshToken def _generate_jwt_token_for_jobseeker(self): refresh = RefreshToken.for_user(self) refresh["id"] = self.id refresh["role"] = "jobseeker" return { 'refresh': str(refresh), 'access': str(refresh.access_token), } def _generate_jwt_token_for_recruiter(self): refresh = RefreshToken.for_user(self) refresh['id'] = self.id refresh['role'] = "recruiter" return { 'refresh': str(refresh), 'access': str(refresh.access_token), }
2.自定义刷新token的逻辑
from rest_framework_simplejwt.tokens import RefreshToken class TokenRefreshApiView(APIView): def post(self, request, **kwargs): try: token = RefreshToken(request.data["refresh"]).access_token access_token = str(token) payload = jwt.decode( access_token, settings.SECRET_KEY, algorithms=settings.SIMPLE_JWT["ALGORITHM"] ) user_id = payload["id"] source = request.data["source"] if user_id and source == "web": payload["token"] = access_token set_auth_cache(payload, user_id, "jobseeker", source=source) if user_id and source == "mobile": payload["token"] = access_token set_auth_cache(payload, user_id, source=source) return Response({"access": access_token}, status=status.HTTP_200_OK) except: return Response({"data": "refreshtoken expiration of identity"}, status=status.HTTP_200_OK)
每天逼着自己写点东西,终有一天会为自己的变化感动的。这是一个潜移默化的过程,每天坚持编编故事,自己不知不觉就会拥有故事人物的特质的。 Explicit is better than implicit.(清楚优于含糊)