如何将Django Rest Framework可浏览API接口限制为管理员用户 [英] How to restrict Django Rest Framework browsable API interface to admin users

查看:249
本文介绍了如何将Django Rest Framework可浏览API接口限制为管理员用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为移动应用程序开发Django Rest Framework后端。该API是私有的,只能在内部使用。

I'm developing a Django Rest Framework backend for a mobile app. The API is private and will only ever be used internally.

可浏览的API可以很方便地帮助开发人员进行项目开发,但是我想防止任何未设置为使用可浏览界面的项目管理员。

The browsable API is convenient for helping developers working on the project but I would like to prevent anyone who's not set as an admin on the project from using the browsable interface.

我意识到,可浏览的管理员不会授予用户原本不会拥有的任何权限,但是它确实具有一些安全性灰色区域(例如,对于具有外部权限的模型关键关系,除非您特别指示不要在HTML选择器字段中填充数据库中所有可能的相关对象。

I realize that the browsable admin doesn't grant any permissions that user wouldn't otherwise have, but it does have some security gray areas (e.g. for models with a foreign key relationship, the HTML selector field gets populated with all the possible related objects in the DB unless you specifically instruct it not to).

由于此应用处理了敏感的用户数据,我希望向公众公开尽可能小的表面积,以减少我自己潜在的错误疏忽的风险。

Because this app handles sensitive user data, I'd prefer to expose the smallest surface area possible to the public to reduce the risk of my own potential mistakes oversights.

是否可以通过任何方式禁用可浏览API非管理员用户,而不是对所有人都禁用它?我在Google上进行了大量搜索,并且搜索了SO,但没有找到答案。此问题关闭如何禁用admin样式django-rest-framework的可浏览界面吗?但不一样,因为那些指令对每个人都禁用了界面。

Is there any way to disable the browsable API for non-admin users without disabling it for everyone? I've done a fair amount of Google searching and looked on SO and haven't found an answer. This question is close How to disable admin-style browsable interface of django-rest-framework? but not the same because those instructions disable the interface for everyone.

推荐答案

假设您使用的是DRF的内置视图,我认为您可以覆盖 get_renderers()

Assuming you're using DRF's built in views, I think you can just override get_renderers().

在您的设置文件:

REST_FRAMEWORK = {
    # Only enable JSON renderer by default.
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
    ],
}

然后在您的 views.py 中:

from rest_framework import generics, renderers

class StaffBrowsableMixin(object):
    def get_renderers(self):
        """
        Add Browsable API renderer if user is staff.
        """
        rends = self.renderer_classes
        if self.request.user and self.request.user.is_staff:
            rends.append(renderers.BrowsableAPIRenderer)
        return [renderer() for renderer in rends]

class CustomListApiView(StaffBrowsableMixin, generics.ListAPIView):
    """
    List view.
    """
    # normal stuff here

这篇关于如何将Django Rest Framework可浏览API接口限制为管理员用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆