具有JWT用户身份验证的Django Rest框架(获取匿名用户)

时间:2020-01-15 15:57:56

标签: python django django-rest-framework jwt django-authentication

我正在将JWT与Django一起使用来验证来自Ajax jquery的请求。我的Jquery是

ref

当我在服务器上收到此请求时,我会像这样

进行身份验证
$.ajax({
        url: "/customerapi/get-customer-detail/",
        type: 'GET',
        // headers: {"Token": localStorage.getItem('token')},
        beforeSend: function (xhr) {
        /* Authorization header */
        xhr.setRequestHeader("Authorization", "Token " + localStorage.getItem('token'));
        xhr.setRequestHeader("X-Mobile", "false");
         },

        success: function (res) {

        }
    });

在这里,我的Request.user始终是匿名的。为什么会这样呢?

我的中间件类是

from rest_framework.permissions import IsAuthenticated

class GetCustomerData(APIView):
    authentication_classes = (JSONWebTokenAuthentication,  )
    permission_classes = (IsAuthenticated ,)
    def get(self, request):
        try:
        Customer.objects.get(id=request.user)

1 个答案:

答案 0 :(得分:2)

在标头值中应为JWT而不是Token

xhr.setRequestHeader("Authorization", "JWT " + localStorage.getItem('token'));