第2部分-保护您的API
情景
这对一个人来说是很常见的 Authorization Server 也要成为 Resource Server ,通常公开一个API以允许其他人访问它自己的资源。Django OAuth工具包使用OAuth2实现了一种保护Django应用程序视图的简单方法,在本教程中,我们将了解如何做到这一点。
制作你的API
我们从我们离开的地方开始 part 1 of the tutorial :您有一个授权服务器,我们希望它提供一个API来访问某种资源。我们不需要实际的资源,所以我们只需公开一个受OAuth2保护的端点:让我们在 class based view 时尚!
Django OAuth工具包提供了一组基于类的通用视图,可以用来将OAuth行为添加到您的视图中。打开你的 views.py 模块并导入视图:
from oauth2_provider.views.generic import ProtectedResourceView
from django.http import HttpResponse
然后创建将响应API端点的视图:
class ApiEndpoint(ProtectedResourceView):
def get(self, request, *args, **kwargs):
return HttpResponse('Hello, OAuth2!')
就是这样,我们的API将只公开一个方法,响应 GET 请求。现在打开你的 urls.py 并指定此视图将响应的URL:
from django.urls import path, include
import oauth2_provider.views as oauth2_views
from django.conf import settings
from .views import ApiEndpoint
# OAuth2 provider endpoints
oauth2_endpoint_views = [
path('authorize/', oauth2_views.AuthorizationView.as_view(), name="authorize"),
path('token/', oauth2_views.TokenView.as_view(), name="token"),
path('revoke-token/', oauth2_views.RevokeTokenView.as_view(), name="revoke-token"),
]
if settings.DEBUG:
# OAuth2 Application Management endpoints
oauth2_endpoint_views += [
path('applications/', oauth2_views.ApplicationList.as_view(), name="list"),
path('applications/register/', oauth2_views.ApplicationRegistration.as_view(), name="register"),
path('applications/<pk>/', oauth2_views.ApplicationDetail.as_view(), name="detail"),
path('applications/<pk>/delete/', oauth2_views.ApplicationDelete.as_view(), name="delete"),
path('applications/<pk>/update/', oauth2_views.ApplicationUpdate.as_view(), name="update"),
]
# OAuth2 Token Management endpoints
oauth2_endpoint_views += [
path('authorized-tokens/', oauth2_views.AuthorizedTokensListView.as_view(), name="authorized-token-list"),
path('authorized-tokens/<pk>/delete/', oauth2_views.AuthorizedTokenDeleteView.as_view(),
name="authorized-token-delete"),
]
urlpatterns = [
# OAuth 2 endpoints:
# need to pass in a tuple of the endpoints as well as the app's name
# because the app_name attribute is not set in the included module
path('o/', include((oauth2_endpoint_views, 'oauth2_provider'), namespace="oauth2_provider")),
path('api/hello', ApiEndpoint.as_view()), # an example resource endpoint
]
您可能希望编写自己的应用程序视图来处理权限和访问控制,但库中打包的那些视图可以让您在开发应用程序时开始使用。
因为我们继承了 ProtectedResourceView ,我们完成了,我们的API受OAuth2保护--看在懒惰的程序员的份上。
测试您的API
是时候向您的API发出请求了。
要快速测试,请尝试通过URL访问您的应用程序 /api/hello ,并验证它是否使用 403 (事实上没有 HTTP_AUTHORIZATION 提供了标头)。您可以使用任何可以执行HTTP请求的东西来测试您的API,但在本教程中,您可以使用在线 consumer client 。只需在表单中填入api端点的URL(即,如果您在本地主机上,则为http://localhost:8000/api/hello)和来自 part 1 of the tutorial 。进入Django管理员并从那里获得令牌不被认为是作弊,所以这是一个选择。
尝试执行请求并检查您的 Resource Server 又名 Authorization Server 正确响应为HTTP 200。
Part 3 of the tutorial 将演示如何使用访问令牌对用户进行身份验证。