【问题标题】:Django: Renew and set JWTs as HttpOnly cookie using a middleware. Response() returning django.template.response.ContentNotRenderedErrorDjango:使用中间件将 JWT 更新并设置为 HttpOnly cookie。 Response() 返回 django.template.response.ContentNotRenderedError
【发布时间】:2021-05-20 17:14:56
【问题描述】:

我有一个自定义中间件,我在其中添加 SimpleJWR HTTP_AUTHORIZATION 到每个授权请求,因为我正在使用 HttpOnly cookie。另外在这里我添加了代码来检查access 令牌是否有效。如果不是,则使用requests 发送请求,该请求获取新的access 令牌并将其设置为HttpOnly cookie。到目前为止,我能够在新的access 令牌过期后获得它。但是,我发送请求的 url 返回了这个错误:

raise ContentNotRenderedError(
django.template.response.ContentNotRenderedError: The response content must be rendered before it can be accessed.

在第一次请求时它就起作用了。它返回响应并将令牌保存为HttpOnly cookie,但在令牌过期后,如果我再次发出请求,而不是(我想要发生的)将令牌保存为HttpOnly cookie 并再次返回相同的响应,它正在返回错误。

我认为问题出在response 语句中。我的中间件:

import jwt
import datetime
import requests
import json

from rest_framework.response import Response
from django.conf import settings

class AuthorizationHeaderMiddleware:
    def __init__(self, get_response=None):
        self.get_response = get_response

    def __call__(self, request):
        access_token = request.COOKIES.get('access')
        refesh_token = request.COOKIES.get('refresh')
        print(refesh_token)
        # check if the access token is valid
        # if not, send new access token to cookie
        if access_token:
            key = settings.SECRET_KEY
        try:
            decoded_access_token = jwt.decode(access_token, key, algorithms=["HS256"])
        except jwt.ExpiredSignatureError:
            # Signature has expired
            print("expired; sending for new token")
            url = 'http://127.0.0.1:8000/api/token/refresh/'
            data = {"refresh": refesh_token}
            resp = requests.post(
                url, 
                data=json.dumps(data),
                headers = {'content-type': 'application/json'}
                )
            result = resp.json()
            new_access_token = result['access']
            response = Response()
            response.set_cookie('access', new_access_token, httponly=True)
            response.set_cookie('set', 'new')
            return response

            request.META['HTTP_AUTHORIZATION'] = f'Bearer {access_token}'
        return self.get_response(request)

这个错误是怎么来的,我该如何解决?

【问题讨论】:

    标签: django django-rest-framework django-rest-framework-simplejwt cookie-httponly


    【解决方案1】:

    试试这个:

    def __call__(self, request):
        access_token = request.COOKIES.get('access')
        refesh_token = request.COOKIES.get('refresh')
        print(refesh_token)
        # check if the access token is valid
        # if not, send new access token to cookie
        if access_token is not None:
            key = settings.SECRET_KEY
        else:
            return Response({"Error" : "No token found"})
        try:
            decoded_access_token = jwt.decode(access_token, key, algorithms=["HS256"])
            request.META['HTTP_AUTHORIZATION'] = f'Bearer {access_token}'
            return self.get_response(request)
        except jwt.ExpiredSignatureError:
            # Signature has expired
            print("expired; sending for new token")
            url = 'http://127.0.0.1:8000/api/token/refresh/'
            data = {"refresh": refesh_token}
            resp = requests.post(
                url, 
                data=json.dumps(data),
                headers = {'content-type': 'application/json'}
                )
            result = resp.json()
            new_access_token = result['access']
            response = Response()
            response.set_cookie('access', new_access_token, httponly=True)
            response.set_cookie('set', 'new')
            request.META['HTTP_AUTHORIZATION'] = f'Bearer {new_access_token}'
            
            return self.get_response(request)
    

    【讨论】:

    猜你喜欢
    • 2021-06-18
    • 2017-12-04
    • 1970-01-01
    • 2017-02-04
    • 2011-04-01
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多