如何添加令牌auth到swagger + django休息框架?

mig*_*lfg 21 django documentation swagger django-rest-framework

我正在使用两个很棒的工具DRFDjango-REST-Swagger,但是我的一些API视图都在令牌认证下.

所以现在我想在我的API的swagger doc页面中添加测试那些令牌身份验证页面的可能性,包括令牌头.我怎么能这样做?

我的类API视图的快照如下所示:

class BookList(APIView):
    """
    List all books, or create a new book.
    """
    authentication_classes = (TokenAuthentication, )
    permission_classes = (IsAuthenticated,)
    ...
Run Code Online (Sandbox Code Playgroud)

由于扬鞭自动检测到很多东西,我期待看到约令牌身份验证,并问我关于它的Web界面令牌或用户ID,但事实并非如此.因此我通过CURL命令手动测试它...

Mel*_*nez 23

如果您正在使用令牌身份验证,则可能需要查看此问题

基本上,您只需将此添加到您的settings.py:

SWAGGER_SETTINGS = {
    'SECURITY_DEFINITIONS': {
        'api_key': {
            'type': 'apiKey',
            'in': 'header',
            'name': 'Authorization'
        }
    },
}
Run Code Online (Sandbox Code Playgroud)

在Swagger UI页面中,您应该看到" 授权"按钮.单击该按钮,然后在输入文本字段中输入您的授权值.

  • 它对我不起作用.尝试了Auth-Token和Authorization. (3认同)
  • 它对我也不起作用.当我在浏览器中检查元素时,我看不到新添加的请求标头 (3认同)
  • 请注意,要使其工作,您必须在标有“值”的文本字段中提供“Token”,后跟实际令牌,单击“授权”按钮时会显示该令牌,例如“Token 994...ee4b”。 (2认同)

mig*_*lfg 11

自从我开始工作以后,我自己回答.

实际上Swagger设置有一个选项,api_key - >

SWAGGER_SETTINGS = {
    "exclude_namespaces": [], # List URL namespaces to ignore
    "api_version": '0.1',  # Specify your API's version
    "api_path": "/",  # Specify the path to your API not a root level
    "enabled_methods": [  # Specify which methods to enable in Swagger UI
        'get',
        'post',
        'put',
        'patch',
        'delete'
    ],
    "api_key": '', # An API key
    "is_authenticated": False,  # Set to True to enforce user authentication,
    "is_superuser": False,  # Set to True to enforce admin only access
}
Run Code Online (Sandbox Code Playgroud)

对我来说不是那么清楚,但我只是为测试用户输入了一个有效的令牌,它适用于auth所需的视图:-)


mat*_*yas 7

我的问题是,在激活TokenAuthentification后,由于AuthentificationError,我的api url在swagger UI中不再显示.
对我来说,解决方案是激活Django Rest框架设置中的两个认证类:
SessionAuthentification - >用于Swagger UI
TokenAuthentification - >用于Rest客户端

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.SessionAuthentication'
)
Run Code Online (Sandbox Code Playgroud)

}


ode*_*den 6

架构视图需要具有AllowAny的权限.这允许插件在用户进行身份验证之前查看哪些端点可用.如果设置正确,端点仍应受到保护.例:

@api_view()
@renderer_classes([SwaggerUIRenderer, OpenAPIRenderer, renderers.CoreJSONRenderer])
@authentication_classes((TokenAuthentication, SessionAuthentication))
@permission_classes((AllowAny,))
def schema_view(request):
    generator = schemas.SchemaGenerator(
        title='My API end points',
        patterns=my_urls,
        url="/api/v1/")
    return response.Response(generator.get_schema(request=request))
Run Code Online (Sandbox Code Playgroud)

最好删除SessionAuthentication并仅使用TokenAuthentication,但这是一个选择问题,在这里我删除了它

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated'
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication'
)
Run Code Online (Sandbox Code Playgroud)

请确保将其添加'rest_framework.authtoken'到已安装的应用程序中并CsrfViewMiddleware从中间件类中删除,因为它将不再需要.和昂首阔步的设置

SWAGGER_SETTINGS = {
    'SECURITY_DEFINITIONS': {
        'api_key': {
            'type': 'apiKey',
            'in': 'header',
            'name': 'Authorization'
        }
    },
    'USE_SESSION_AUTH': False,
    'JSON_EDITOR': True,
}
Run Code Online (Sandbox Code Playgroud)

这将使swagger将令牌填充到所有示例curl命令中,这非常好.保持会话auth到位似乎禁用此功能.

招摇授权对话框询问api_key需要提供哪些内容.似乎无法改善这一点,如果我这样做会更新这篇文章.