How to disable admin-style browsable interface of django-rest-framework?

后端 未结 3 1277
感情败类
感情败类 2020-11-29 15:47

I am using django-rest-framework. It provides an awesome Django admin style browsable self-documenting API. But anyone can visit those pages and use the interface to add dat

3条回答
  •  囚心锁ツ
    2020-11-29 15:57

    While the accepted answer to this question does answer the question as it was worded, I feel that it does not solve the actual issue at hand.

    For completeness in this answer, disabling the browseable HTML api is done by removing it from the renderer classes like so:

    REST_FRAMEWORK = {
        'DEFAULT_RENDERER_CLASSES': (
            'rest_framework.renderers.JSONRenderer',
        )
    }
    

    However, the actual issue the question alludes to is people being able to post to the API without authentication. While removing the form makes it less obvious, this answer does not protect the API endpoints.

    At minimum, someone finds this question and is looking to protect the API from unauthenticated, or unauthorised POST submissions; the are looking to change the API Permissions

    The following will set all endpoints to be read only unless the user is authenticated.

    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticatedOrReadOnly',
        )
    }
    

    If you would like to completely hide the API unless the user is logged in, you could also use IsAuthenticated.

    FYI: This will also remove the form from the HTML browseable API as it responds to permissions. When an authenticated user logs in, the form will be available again.

    Bonus Round:

    Only enable the browseable HTML API in dev:

    DEFAULT_RENDERER_CLASSES = (
        'rest_framework.renderers.JSONRenderer',
    )
    
    if DEBUG:
        DEFAULT_RENDERER_CLASSES = DEFAULT_RENDERER_CLASSES + (
            'rest_framework.renderers.BrowsableAPIRenderer',
        )
    
    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticatedOrReadOnly',
        ),
        'DEFAULT_RENDERER_CLASSES': DEFAULT_RENDERER_CLASSES
    }
    

提交回复
热议问题