Django REST Framework Swagger - 身份验证错误

问题描述

我按照文档中的说明进行操作.所以这是我的看法:

I followed the instructions in the docs. So here's my view:

from rest_framework.decorators import api_view, renderer_classes
from rest_framework import response, schemas
from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer


@api_view()
@renderer_classes([OpenAPIRenderer, SwaggerUIRenderer])
def schema_view(request):
    generator = schemas.SchemaGenerator(title='Bookings API')
    return response.Response(generator.get_schema(request=request))

我在 urls.py 中添加了以下内容:

And I added the following to my urls.py:

url(r'^docs/', views.schema_view),

当我转到我的项目的 /docs/ 页面时,我收到以下错误:

When I went to the /docs/ page of my project, I got the following error:

401 : {"detail": "Authentication credentials were not provided."} http://127.0.0.1:8000/docs/?format=openapi

在浏览器控制台中我收到了这条消息:

In the browser console I got this message:

Unable to Load SwaggerUI init.js (line 57)

当我将 schema_viewpermission_classes 设置为 AllowAny 时,我能够查看我的 api 文档.但是,我不确定这是否是正确的方法.没有办法以管理员或任何其他用户身份登录以查看文档.另外,在浏览器中查看时如何提供身份验证令牌?也许我错过了文档中的某些内容.

When I set the permission_classes of my schema_view to AllowAny, I was able to view my api docs. However, I'm not sure if this is the right way of doing this. Isn't there a way to login as an admin, or any other user to view the docs. Also, how do I provide the auth tokens when viewing this in the browser? Maybe I missed something in the docs.


解决方案

我想我已经找到了解决方案.

I think I've found the solution.

settings.py中,我添加了以下设置:

In the settings.py, I added the following settings:

SWAGGER_SETTINGS = {
    'SECURITY_DEFINITIONS': {
        'api_key': {
            'type': 'apiKey',
            'in': 'header',
            'name': 'Authorization'
        }
    },
}

然后当我加载页面时,我只需点击右上角的 Authorize 按钮,然后在 value 文本字段中输入此值:

Then when I load the page, I just click on the Authorize button at the upper right and enter this value in the value text field:

Token <valid-token-string>

但是,我仍然需要将 schema view 的权限类设置为 AllowAny.auth token 只是让我从不同的用户切换,允许我查看不同的端点集.

However, I still needed to set the permission class of the schema view to AllowAny. The auth token just let me switch from different users, allowing me to view different set of endpoints.

相关文章