django-rest-framework(实战篇)——drf权限验证

official guide——permissions

  • auth是用来做用户验证
  • permission是用来做权限认证

判断用户是否登陆:
user_operation/view.py:

from rest_framework.permissions import IsAuthenticated
permission_classes = (IsAuthenticated,)

用户未登录访问userfav的list会给我们抛出401的错误。

在utils中新建permissions,这是我们自定义的permissions。
utils/permissions.py:

class IsOwnerOrReadOnly(permissions.BasePermission):
    """
    Object-level permission to only allow owners of an object to edit it.
    Assumes the model instance has an `owner` attribute.
    """

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        # so we'll always allow GET, HEAD or OPTIONS requests.
        if request.method in permissions.SAFE_METHODS:
            return True

        # Instance must have an attribute named `owner`.
        return obj.user == request.user

这个自定义的permission类继承了我们的BasePermission。它有一个方法叫做has_object_permission,是否有对象权限。检测我们从数据库中拿出来的obj的user是否等于request.user。安全的方法也就是不会对数据库进行变动的方法,总是可以让大家都有权限访问到。

views中添加该自定义的权限认证类
user_operation/views.py:

from utils.permissions import IsOwnerOrReadOnly

permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)

这样在做删除的时候就会验证权限。

不能让所有的收藏关系数据都被获取到。因此我们要重载get_queryset方法

def get_queryset(self):
        return UserFav.objects.filter(user=self.request.user)

重载之后queryset的参数配置就可以注释掉了。

token的认证最好是配置到view里面去,而不是配置到全局中。

前端的每一个request请求都加入我们的token的话,token过期了,当用户访问goods列表页等不需要token认证的页面也会拿不到数据。

将setting中的'rest_framework.authentication.SessionAuthentication'删除掉。

然后在具体的view中来import以及进行配置

user_operation/views.py中实现代码:

from rest_framework_jwt.authentication import JSONWebTokenAuthentication

authentication_classes = (JSONWebTokenAuthentication, )

此时在我们在后台无法使用session登陆查看userfav,是因为我们的类内auth并不包含session auth,添加session登陆:

from rest_framework.authentication import SessionAuthentication

authentication_classes = (JSONWebTokenAuthentication, SessionAuthentication)
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容