【问题标题】: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]