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)

  

posted @ 2023-02-22 18:37  Οo白麒麟оΟ  阅读(647)  评论(0编辑  收藏  举报