【问题标题】:How to make a Django view ONLY accessible to Unauthenticated users?如何使未经身份验证的用户只能访问 Django 视图?
【发布时间】:2014-11-24 07:06:25
【问题描述】:

我正在通过扩展 rest_framework.views.APIView 类来构建 Django API 视图。

我已经成功构建了许多只能由经过身份验证的用户调用的 API。我已经通过添加:permission_classes = [permissions.IsAuthenticated,]

有些 API 我只希望未经身份验证的用户调用。例如“忘记密码”。基本上,我想确保 API 调用者不会在请求标头中发送 JWT 令牌。我该如何执行?没有permissions.IsUnAuthenticated

【问题讨论】:

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


    【解决方案1】:

    您可以轻松创建自己的IsNotAuthenticated

    类似这样的:

    from rest_framework.permissions import BasePermission
    
    
    class IsNotAuthenticated(BasePermission):
        """
        Allows access only to non authenticated users.
        """
        def has_permission(self, request, view):
            return not request.user.is_authenticated()
    

    然后:permission_classes = (myapp.permissions.IsNotAuthenticated,)

    问候。

    【讨论】:

      【解决方案2】:

      如果您使用的是基于函数的视图,那么最好使用以下内容。

      from django.contrib.auth.decorators import user_passes_test
      @user_passes_test(lambda u: not u.is_authenticated())
      

      【讨论】:

        【解决方案3】:

        或者您可以像这样在 permissions.py 中执行此操作(对于谁得到 bool 对象错误)

        from rest_framework import permissions
        
        class IsNotAuthenticated(permissions.BasePermission):
            def has_permission(self, request, view):
                return not request.user.is_authenticated
        

        在主视图中

         from .permissions import IsNotAuthenticated
         
         permission_classes = [IsNotAuthenticated]
        

        【讨论】:

          猜你喜欢
          • 2016-10-01
          • 2017-01-17
          • 2012-12-24
          • 1970-01-01
          • 2019-08-26
          • 2016-11-30
          • 2016-01-15
          • 2021-12-09
          • 2016-10-21
          相关资源
          最近更新 更多