【问题标题】:How to limit view to authenticated user in Django Rest Framework如何在 Django Rest Framework 中将视图限制为经过身份验证的用户
【发布时间】:2015-07-14 12:14:51
【问题描述】:

我有一个 Django Rest Framework 应用程序。 通过登录方式进行认证:

def login(self, request):
    user = find_my_user(request)
    user.backend = 'django.contrib.auth.backends.ModelBackend'
    login(request, user)
    return Response({"status": "ok"})

身份验证工作正常。

我有一个 ViewSet 有一个 list_route() 需要使用经过身份验证的用户。 代码如下:

class CommonView(viewsets.ViewSet):
    @list_route()
    @authentication_classes(SessionAuthentication)
    @permission_classes(IsAuthenticated)
    def connected(self, request):
        return Response({"status": "ok"})

即使用户未通过身份验证(无会话 cookie),也会执行操作。

作为一种变通方法,我已经这样做了:

class CommonView(viewsets.ViewSet):
    @list_route()
    def connected(self, request):
        if request.user.is_authenticated():
            return Response({"status": "ok"})
        else:
            return Response({"status": "ko", "message": "Unauthenticated"})

但我觉得它可以更清洁,有什么想法吗?

【问题讨论】:

    标签: django authentication django-rest-framework


    【解决方案1】:

    您可以创建一个自定义的ListRouteIsAuthenticated 权限类继承自BasePermission 类,该类将拒绝未经身份验证的用户对list 路由中的任何请求的任何权限。

    对于detail 路由请求,它将允许不受限制的访问,无论请求是经过身份验证还是未经身份验证。

    from rest_framework.permissions import  BasePermission
    
    class ListRouteIsAuthenticated(BasePermission):
        """
        Custom Permission Class which authenticates a request for `list` route
        """
    
        def has_permission(self, request, view):
            if view.action == 'list':
                return request.user and request.user.is_authenticated() #  check user is authenticated for 'list' route requests
            return True # no authentication check otherwise
    

    然后在你的视图中,你需要定义这个权限类。

    class CommonView(viewsets.ViewSet):
    
        permission_classes = [ListRouteIsAuthenticated]
        ...
    

    【讨论】:

      【解决方案2】:

      根据文档,添加一个属性:

      class CommonView(viewsets.ModelViewSet):
      
          permission_classes = [IsAuthenticated]
      

      【讨论】:

      • 确实如此,但是它将应用于视图内的所有方法。我只需要将它应用于其中的一些,
      猜你喜欢
      • 2018-07-02
      • 2013-05-03
      • 2019-07-06
      • 2014-06-07
      • 1970-01-01
      • 2016-10-09
      • 2013-04-22
      • 2019-06-28
      • 2019-02-20
      相关资源
      最近更新 更多