Django和OAuth2-403未经授权:未提供身份验证凭据,并且禁止401

时间:2019-06-21 16:35:15

标签: python django oauth oauth-2.0 django-rest-framework

我有一个通过Okta运行的身份验证服务器,但是我没有使Django与OAuth2一起使用。我已经阅读并尝试了一些Tut和文档,但现在我有些困惑。 我测试了我的API并通过Postman获取了新的访问令牌,但是当我连接到它时,会遇到两个不同的未授权错误。

http://localhost:8000/api/love-buddy,我得到

  

状态:401未经授权:{“详细信息”:“未提供身份验证凭据。”}

http://localhost:8000/api/hello,我得到

  

状态:禁止使用403”

并且http://localhost:8000/api/user在没有访问令牌的情况下工作。

如何使用OAuth2保护Django资源服务器以及如何成功访问?

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'analytics',
    'rest_framework',
    'rest_framework_mongoengine',
    'oauth2_provider'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

urls.py

# OAuth2 provider endpoints
oauth2_endpoint_views = [
    url(r'^authorize/$', oauth2_views.AuthorizationView.as_view(), name="authorize"),
    url(r'^token/$', oauth2_views.TokenView.as_view(), name="token"),
    url(r'^revoke-token/$', oauth2_views.RevokeTokenView.as_view(), name="revoke-token"),
]

if settings.DEBUG:
    # OAuth2 Application Management endpoints
    oauth2_endpoint_views += [
        url(r'^applications/$', oauth2_views.ApplicationList.as_view(), name="list"),
        url(r'^applications/register/$', oauth2_views.ApplicationRegistration.as_view(), name="register"),
        url(r'^applications/(?P<pk>\d+)/$', oauth2_views.ApplicationDetail.as_view(), name="detail"),
        url(r'^applications/(?P<pk>\d+)/delete/$', oauth2_views.ApplicationDelete.as_view(), name="delete"),
        url(r'^applications/(?P<pk>\d+)/update/$', oauth2_views.ApplicationUpdate.as_view(), name="update"),
    ]

    # OAuth2 Token Management endpoints
    oauth2_endpoint_views += [
        url(r'^authorized-tokens/$', oauth2_views.AuthorizedTokensListView.as_view(), name="authorized-token-list"),
        url(r'^authorized-tokens/(?P<pk>\d+)/delete/$', oauth2_views.AuthorizedTokenDeleteView.as_view(),
            name="authorized-token-delete"),
    ]

urlpatterns = [
    path('', include('analytics.urls')),
    path('api/love-buddy', buddy_api_view.LoveBuddy.as_view()),
    path('api/hate-buddy', buddy_api_view.HateBuddy.as_view()),
    url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
    url(r'^api/hello', ApiEndpoint.as_view()),  # an example resource endpoint
]

analytics.urls.py

router = routers.DefaultRouter()
router.register('api/user', UserViewSet, 'user')

urlpatterns = router.urls

api.py

class LoveBuddy(APIView):
    def get(self, request):
        return self.service.get_love_buddy()

class ApiEndpoint(ProtectedResourceView):
    def get(self, request, *args, **kwargs):
        return HttpResponse('Hello, OAuth2!')

class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    permission_classes = [
        permissions.AllowAny
    ]
    serializer_class = UserSerializer

0 个答案:

没有答案