带有OAuth2身份验证的Django REST Swagger

时间:2016-11-24 16:07:55

标签: django rest swagger-2.0

我有一个用Django rest框架创建的REST API。要验证我的API调用,我使用的是OAuth2令牌。我的问题是如何在Django rest swagger生成的文档中启用标准用户名/密码验证。 现在我到了 401 : {"detail":"Authentication credentials were not provided."} http://127.0.0.1:8000/docs/?format=openapi 设置

REST_FRAMEWORK = {
    # Don't perform any authentication on API calls so we don't have any CSRF problems
    # :PRODUCTION: Put back authentication for production version when not testing on same server?
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'oauth2_provider.ext.rest_framework.OAuth2Authentication',
        'rest_framework_social_oauth2.authentication.SocialAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'PAGE_SIZE': 1000,  # Max number of results returned from a list API call
    'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),
    # Use JSONRender so the Web API interface is not shown. This is needed when testing the app on the same server
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    )
}
SWAGGER_SETTINGS = {
    'SECURITY_DEFINITIONS': {
        'veeu': {
            'type': 'oauth2',
            'flow': 'password',
            'tokenUrl': 'http://localhost:8000/auth/token/',
            'scopes': {
                'write:all': 'Write all',
                'read:all': 'Read all',
            }
        }
    },
}

LOGIN_URL = 'http://localhost:8000/admin/'

当我点击Django登录时,它会将我带到管理员登录页面。登录后,此消息仍然相同。如果我添加标题Authorization: Bearer TokenHere,它就可以了。但是,重点是启用用户名/密码登录。

1 个答案:

答案 0 :(得分:0)

要访问Swagger文档,您需要在 settings.py 中具有以下内容的SessionAuth:

# API VERSIONING
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.SessionAuthentication',
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated'
    ],
}

这使您可以访问Swagger生成的文档。问题是,用 OAuth2 保护的任何端点都不会通过Swagger看到,至少在通过“应用程序”生成OAuth的情况下。以下代码根本不起作用,我正在链接讨论的线程,要求任何人使用该功能:

# TODO Swagger implementation is not working for password since
# it sends client_id and client_secret as query strings and not as
# user separated with "::"
# The "application" flow setting also that does work
#
SWAGGER_SETTINGS = {
    'SUPPORTED_SUBMIT_METHODS': [],  # Due to bug described above
    'SECURITY_DEFINITIONS': {
        "customers_auth": {
            "type": "oauth2",
            "tokenUrl": "/o/token/",
            "flow": "password",
            "scopes": {
                "read": "Read scope",
                "write": "Write scope"
            }
        }
    },
}