2014-09-29 52 views
2

我正在通过扩展rest_framework.views.APIView类来构建Django API视图。如何仅对未经身份验证的用户访问Django视图?

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

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

回答

4

您可以轻松创建自己的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,)

问候。

0

如果您使用的是基于功能的视图,那么使用以下方法会很好。

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