LoginRequiredMixin失败,但用户已通过身份验证

时间:2017-03-16 08:56:09

标签: django react-native django-rest-framework react-native-fetch-blob

我正在使用django rest框架令牌身份验证来验证用户身份。当我使用带有标题为

的react-native-fetch-blob命中请求时
{
    Authorization : token,
    'Content-Type' : 'multipart/form-data',
    'Range' : 'bytes=22976-'
} 

并在我的服务器代码中使用LoginRequiredMixin它失败并重定向。如果我删除LoginRequiredMixin,则request.user.is_authenticated()True。如何使用用户登录的限制对用户进行身份验证? 请求中是否有任何特定的标题?

2 个答案:

答案 0 :(得分:1)

LoginRequiredMixin是纯Django的东西,只能用于Session身份验证。由于您正在进行令牌身份验证,因此无法使用,并且会认为您未登录,因此会重定向您。

Django REST框架提供了自己的身份验证和权限系统。这是后者,你会对IsAuthenticated权限检查感兴趣。

答案 1 :(得分:0)

问候。基于@kaushikdr评论我写了这个mixin,允许会话身份验证需要登录+令牌身份验证:

https://gist.github.com/jsmedmar/d846eee063fa23148f8a87313dd590a3

from django.contrib.auth import mixins
from rest_framework.authentication import SessionAuthentication
from rest_framework.authentication import TokenAuthentication
from rest_framework import generics

class TokenLoginRequiredMixin(mixins.LoginRequiredMixin):

    """A login required mixin that allows token authentication."""

    def dispatch(self, request, *args, **kwargs):
        """If token was provided, ignore authenticated status."""
        http_auth = request.META.get("HTTP_AUTHORIZATION")

        if http_auth and "Token" in http_auth:
            pass

        elif not request.user.is_authenticated:
            return self.handle_no_permission()

        return super(mixins.LoginRequiredMixin, self).dispatch(
            request, *args, **kwargs)

class ListAPIView(TokenLoginRequiredMixin, generics.ListAPIView):

    """This view suppot both token and session authentication."""

    authentication_classes = [
        SessionAuthentication,
        TokenAuthentication,
        ]