使用jwt身份验证的django rest api正在请求csrf令牌

时间:2018-01-13 10:41:43

标签: django authentication django-rest-framework jwt

我是django rest api框架的新手。我正在使用基于JWT令牌的身份验证为其余的api进行以下设置 -

classB(QWidget):
def __init__(self, parent = None):
    super(classB, self).__init__(parent)
    self.lineLayout = QGridLayout()
    self.textbox    = QLineEdit("")
    self.lineLayout.addWidget(self.textbox, 0, 0)
    self.setLayout(self.lineLayout)

def setInt(self,intVal):
    # The shell displays this value perfectly
    print(intVal)
    # it does not display the change in QWidget that lives in  MainWidget
    self.textbox.setText("val: " + str(intVal))

def paintEvent(self, event):    
    painter = QPainter()
    painter.begin(self)

现在基于此,我在chrome中使用postman插件并尝试使用以下步骤测试我的web api进行身份验证 -

  1. 我使用带有凭据的网址http://127.0.0.1:8000/webs/auth-jwt/来获取令牌。

  2. 我使用了网址http://127.0.0.1:8000/webs/testspsearch/并将步骤1中生成的令牌作为授权承载传递。这被定义为POST方法

  3. 但是当我这样做时,我收到了错误 - > CSRF验证失败。请求中止。 HTTP 403错误。

    你能告诉我这件事我做错了吗?

2 个答案:

答案 0 :(得分:0)

因为您正在从提供数据的同一台机器发出请求,所以(相当恼人地)会导致CSRF异常。您需要在请求中包含CSRF令牌cookie,以表明请求正常。

所以你可以做以下两件事之一:

  • 使端点 crsf免除
  • (推荐)获取crsf令牌并将其作为标题附加到您的HTTP POST请求

CSRF豁免

您可以通过添加装饰器

来使各种端点成为csrf扩展
from django.views.decorators.csrf import csrf_exempt
class SomeView(APIView):

    @csrf_exempt
    def post(self, request):
        serializer = RegisterUserSerializer(data=request.data)

请求令牌

这一点有点痛苦(在我的意见中),因为你必须使用javascript:

// using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

For more info check the docs

答案 1 :(得分:0)

使用django-cors-middleware允许跨源请求。步骤如下

  1. 在已安装的应用中添加corsheaders
  2. 在中间件中添加corsheaders.middleware.CorsMiddleware
  3. 在设置中添加CORS_ORIGIN_ALLOW_ALL = False
  4. 可以在文档中看到进一步的设置。

相关问题