swagger HTTP 401未授权访问

bmp9r5qi  于 2022-12-04  发布在  其他
关注(0)|答案(1)|浏览(462)

我已经成功安装了rest_framework_swagger,之后我在www.example.com文件中设置了urlurls.py项目:

from django.contrib import admin
from django.urls import path, include, re_path
from unimiproject.router import router
from rest_framework.authtoken import views
from rest_framework.schemas import get_schema_view
from django.views.generic import TemplateView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api-auth/', include('rest_framework.urls')),
    re_path(r"^appjud/",include("appjud.urls")),
    path('api/', include(router.urls)),
    path('api-token-auth/', views.obtain_auth_token, name='api-token-auth'),
    path('openapi/', get_schema_view(
        title="School Service",
        description="API developers hpoing to use our service"
    ), name='openapi-schema'),
    path('docs/', TemplateView.as_view(
        template_name='documentation.html',
        extra_context={'schema_url':'openapi-schema'}
    ), name='swagger-ui')

]

但是如果我浏览http://172.18.0.1:7000/openapi/,我会看到:

Schema

GET /openapi/

HTTP 401 Unauthorized
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
WWW-Authenticate: Token

{
    "detail": "Authentication credentials were not provided."
}

为什么我会得到“未提供身份验证凭据”?它应该向我显示所有API的架构,而不是测试它们。

czfnxgou

czfnxgou1#

尝试对代码使用permission_classes=(permissions.AllowAny,),则用户不需要用户名和密码即可访问您的文档

from rest_framework import permissions
from drf_yasg import openapi

path('openapi/',get_schema_view(
    openapi.Info(
        title="School Service",
        description="API developers hoping to use our service",
        contact=openapi.Contact(email="mail@domain.com"),
        license=openapi.License(name="Proprietary Software"),
    ),
    public=True,
    permission_classes=(permissions.AllowAny,),
))

相关问题