如何为swagger + django rest框架添加标记auth ?

时间:2021-12-09 03:30:20

I am using both great tools DRF and Django-REST-Swagger, however a few of my API views are under token authentication.

我正在使用优秀的工具DRF和django rest - swagger,但是我的一些API视图正在进行令牌认证。

So now I'd like to add to my swagger doc page of my API the possibility to test those token auth api urls, including the Token header. How could I do this?.

因此,现在我想在API的swagger doc页面上添加测试这些令牌auth API url(包括令牌头)的可能性。我怎么能这样做?

A snapshot of my class API view is like this:

我的类API视图的快照是这样的:

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

Since Swagger auto detects a lot of stuff, I was expecting to notice about token auth, and ask me about token or user id in its web interface, but it doesn't. Hence I am testing it manually through CURL commands...

由于Swagger auto检测到很多东西,我希望注意到token auth,并询问我它的web界面中的token或user id,但它没有。因此,我正在通过CURL命令手动测试它……

4 个解决方案

#1


19  

If you're using token authentication, you might want to look at this question

如果您正在使用令牌身份验证,您可能想看看这个问题

Basically, you just need to add this to your settings.py:

基本上,你只需要把它添加到你的设置中。

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

In your Swagger UI page you should see an Authorize button. Click that and enter your Authorization value in the input text field.

在Swagger UI页面中,您应该看到一个授权按钮。单击它并在输入文本字段中输入授权值。

#2


9  

I answer myself since I made it work.

我自言自语,因为我让它起作用了。

Actually Swagger settings has an option for this, api_key ->

实际上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
}

To me it wasn't that clear, but I've just input a valid token for testing user and it worked for the auth needed views :-)

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

#3


5  

My Problem was that after activating TokenAuthentification my api urls were not shown any more in the swagger UI due to an AuthentificationError.
For me the solution was to activate both authentaction classes in the Django Rest Framework Settings:
SessionAuthentification -> for the Swagger UI
TokenAuthentification -> for the Rest Clients

我的问题是,在激活了TokenAuthentification之后,由于authentiationerror,我的api url在swagger UI中不再显示。对我来说,解决方案是在Django Rest框架设置中激活这两个authentaction类:sessionauthfication -> For the Swagger UI tokenauthfication -> For the Rest client

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.SessionAuthentication'
)

}

}

#4


4  

The schema view needs to have the permission of AllowAny. This allows the plugin to see which endpoints are available before the user has authenticated. The end points should still be protected if they are setup correctly. Example:

模式视图需要具有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))

It is best to remove the SessionAuthentication and only use the TokenAuthentication but that is a matter of choice, here I have removed it

最好删除SessionAuthentication,并且只使用标记身份验证,但是这是一个选择,这里我删除了它

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated'
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication'
)

Be sure it add 'rest_framework.authtoken' into your installed apps and remove the CsrfViewMiddleware from the middleware classes as it will no longer be needed. And the swagger settings

确保它添加了“rest_framework”。将authtoken”放入已安装的应用程序中,并从中间件类中删除CsrfViewMiddleware,因为不再需要它。和大摇大摆的设置

SWAGGER_SETTINGS = {
    'SECURITY_DEFINITIONS': {
        'api_key': {
            'type': 'apiKey',
            'in': 'header',
            'name': 'Authorization'
        }
    },
    'USE_SESSION_AUTH': False,
    'JSON_EDITOR': True,
}

This will make swagger populate the token into all of the example curl commands as well, which is really nice to have. Leaving the session auth in place seems to disable this.

这将使大摇大摆地将标记填充到所有的示例curl命令中,这非常好。将会话auth保留在适当的位置似乎会禁用此功能。

The swagger authorization dialog asks for the api_key which needs to be provided. Can not seem improve this, will update this post if I do.

swagger授权对话框要求提供api_key。似乎无法改善这一点,将更新这篇文章如果我做。

#1


19  

If you're using token authentication, you might want to look at this question

如果您正在使用令牌身份验证,您可能想看看这个问题

Basically, you just need to add this to your settings.py:

基本上,你只需要把它添加到你的设置中。

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

In your Swagger UI page you should see an Authorize button. Click that and enter your Authorization value in the input text field.

在Swagger UI页面中,您应该看到一个授权按钮。单击它并在输入文本字段中输入授权值。

#2


9  

I answer myself since I made it work.

我自言自语,因为我让它起作用了。

Actually Swagger settings has an option for this, api_key ->

实际上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
}

To me it wasn't that clear, but I've just input a valid token for testing user and it worked for the auth needed views :-)

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

#3


5  

My Problem was that after activating TokenAuthentification my api urls were not shown any more in the swagger UI due to an AuthentificationError.
For me the solution was to activate both authentaction classes in the Django Rest Framework Settings:
SessionAuthentification -> for the Swagger UI
TokenAuthentification -> for the Rest Clients

我的问题是,在激活了TokenAuthentification之后,由于authentiationerror,我的api url在swagger UI中不再显示。对我来说,解决方案是在Django Rest框架设置中激活这两个authentaction类:sessionauthfication -> For the Swagger UI tokenauthfication -> For the Rest client

REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAdminUser',),
'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.SessionAuthentication'
)

}

}

#4


4  

The schema view needs to have the permission of AllowAny. This allows the plugin to see which endpoints are available before the user has authenticated. The end points should still be protected if they are setup correctly. Example:

模式视图需要具有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))

It is best to remove the SessionAuthentication and only use the TokenAuthentication but that is a matter of choice, here I have removed it

最好删除SessionAuthentication,并且只使用标记身份验证,但是这是一个选择,这里我删除了它

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated'
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication'
)

Be sure it add 'rest_framework.authtoken' into your installed apps and remove the CsrfViewMiddleware from the middleware classes as it will no longer be needed. And the swagger settings

确保它添加了“rest_framework”。将authtoken”放入已安装的应用程序中,并从中间件类中删除CsrfViewMiddleware,因为不再需要它。和大摇大摆的设置

SWAGGER_SETTINGS = {
    'SECURITY_DEFINITIONS': {
        'api_key': {
            'type': 'apiKey',
            'in': 'header',
            'name': 'Authorization'
        }
    },
    'USE_SESSION_AUTH': False,
    'JSON_EDITOR': True,
}

This will make swagger populate the token into all of the example curl commands as well, which is really nice to have. Leaving the session auth in place seems to disable this.

这将使大摇大摆地将标记填充到所有的示例curl命令中,这非常好。将会话auth保留在适当的位置似乎会禁用此功能。

The swagger authorization dialog asks for the api_key which needs to be provided. Can not seem improve this, will update this post if I do.

swagger授权对话框要求提供api_key。似乎无法改善这一点,将更新这篇文章如果我做。