2016-09-17 83 views
3

我按照说明in the docs。因此,这里是我的观点:Django REST框架Swagger - 身份验证错误

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

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

当我去/docs/页我的项目,我得到了以下错误:

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

在浏览器控制台中,我收到了以下消息:

Unable to Load SwaggerUI init.js (line 57) 

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

+0

您在DRF中使用哪种认证? – Windsooon

+0

我正在使用令牌认证。 –

回答

8

我想我已经找到了解决方案访问的资源。

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

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

然后,当我加载页面,我只要按一下授权按钮被放置在右上,并在输入该值文本字段:

Token <valid-token-string> 

但是,我仍然需要许可类schema view的设置为AllowAny。身份验证令牌只是让我从不同的用户切换,允许我查看不同的端点集。

0

Isn't there a way to login as an admin, or any other user to view the docs.

如果你只使用令牌认证,第一create tokens for your users,然后通过设置头

curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' 
+0

我这样做,当我打电话给我serivces。然而,不应该使用cURL或Postman来让浏览器访问Swagger UI吗? –

+0

我对swagger并不熟悉,我不知道是否应该在不使用SessionAuthentication的情况下在浏览器中使用Swagger UI。但是您也可以在DRF中启用SessionAuthentication。 – Windsooon

+0

我的API服务使用令牌认证。 Swagger插件仅用于生成api文档。所以它应该在浏览器AFAIK中访问。我不能只是将我的API设计更改为'SessionAuthentication',以便我可以登录到Swagger或类似的东西。 –