快速入门
Django OAuth工具包为 Django REST Framework 。本教程基于Django REST框架示例,并向您展示如何轻松地与其集成。
备注
以下代码已使用Django 2.0.3和Django REST框架3.7.7进行了测试
第1步:最小设置
创建一个Virtualenv并使用以下命令安装以下包 pip **
pip install django-oauth-toolkit djangorestframework
启动新的Django项目并添加 'rest_framework' 和 'oauth2_provider' 致您的 INSTALLED_APPS 布景。
INSTALLED_APPS = (
'django.contrib.admin',
...
'oauth2_provider',
'rest_framework',
)
现在我们需要告诉Django rest框架使用新的身份验证后端。要这样做,请在您的 settings.py 模块:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
)
}
步骤2:创建一个简单的API
让我们创建一个简单的API来访问用户和组。
这是我们项目的根本 urls.py 模块:
from django.urls import path, include
from django.contrib.auth.models import User, Group
from django.contrib import admin
admin.autodiscover()
from rest_framework import generics, permissions, serializers
from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope, TokenHasScope
# first we define the serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'email', "first_name", "last_name")
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = ("name", )
# Create the API views
class UserList(generics.ListCreateAPIView):
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetails(generics.RetrieveAPIView):
permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
queryset = User.objects.all()
serializer_class = UserSerializer
class GroupList(generics.ListAPIView):
permission_classes = [permissions.IsAuthenticated, TokenHasScope]
required_scopes = ['groups']
queryset = Group.objects.all()
serializer_class = GroupSerializer
# Setup the URLs and include login URLs for the browsable API.
urlpatterns = [
path('admin/', admin.site.urls),
path('o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
path('users/', UserList.as_view()),
path('users/<pk>/', UserDetails.as_view()),
path('groups/', GroupList.as_view()),
# ...
]
还可以将以下内容添加到您的 settings.py 模块:
OAUTH2_PROVIDER = {
# this is the list of available scopes
'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}
}
REST_FRAMEWORK = {
# ...
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}
LOGIN_URL = '/admin/login/'
OAUTH2_PROVIDER.SCOPES 设置参数包含应用程序将知道的作用域,因此我们可以使用它们进行权限检查。
现在运行以下命令:
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
第一个命令创建表,第二个命令创建管理员用户帐户,最后一个命令运行应用程序。
您应该做的下一件事是登录管理员
http://localhost:8000/admin
并创建一些用户和组,稍后将通过我们的API进行查询。
步骤3:注册应用程序
要首先获得有效的Access_Token,我们必须注册一个应用程序。DOT有一组可用于CRUD应用程序实例的可定制视图,只需将浏览器指向:
http://localhost:8000/o/applications/
单击该链接以创建新应用程序,并使用以下数据填写表单:
Name: just a name of your choice
Client Type: confidential
Authorization Grant Type: Resource owner password-based
保存您的应用程序!
步骤4:获取令牌并使用您的API
此时,我们准备请求一个ACCESS_TOKEN。打开您的Shell::
curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/
这个 user_name 和 password 是否为在您的 Authorization Server ,就像在步骤2中创建的任何用户一样。响应应该如下所示:
{
"access_token": "<your_access_token>",
"token_type": "Bearer",
"expires_in": 36000,
"refresh_token": "<your_refresh_token>",
"scope": "read write groups"
}
获取您的Access_Token并开始使用新的OAuth2 API::
# Retrieve users
curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/users/
curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/users/1/
# Retrieve groups
curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/groups/
# Insert a new user
curl -H "Authorization: Bearer <your_access_token>" -X POST -d"username=foo&password=bar&scope=write" http://localhost:8000/users/
一段时间过去了,您的访问令牌即将到期,您可以使用 refresh token **
curl -X POST -d "grant_type=refresh_token&refresh_token=<your_refresh_token>&client_id=<your_client_id>&client_secret=<your_client_secret>" http://localhost:8000/o/token/
您的回答应该与您的第一次类似 access_token 请求,包含新的Access_Token和REFRESH_Token:
{
"access_token": "<your_new_access_token>",
"token_type": "Bearer",
"expires_in": 36000,
"refresh_token": "<your_new_refresh_token>",
"scope": "read write groups"
}
步骤5:测试受限访问
让我们尝试使用具有受限作用域的令牌来访问资源 scope 令牌请求的参数::
curl -X POST -d "grant_type=password&username=<user_name>&password=<password>&scope=read" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/
如您所见,提供的唯一范围是 read :
{
"access_token": "<your_access_token>",
"token_type": "Bearer",
"expires_in": 36000,
"refresh_token": "<your_refresh_token>",
"scope": "read"
}
我们现在尝试访问我们的资源::
# Retrieve users
curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/users/
curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/users/1/
好的,这个可以用,因为用户只需要 read 作用域。
# 'groups' scope needed
curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/groups/
# 'write' scope needed
curl -H "Authorization: Bearer <your_access_token>" -X POST -d"username=foo&password=bar" http://localhost:8000/users/
你会得到一个 "You do not have permission to perform this action" 错误,因为您的Access_Token未提供所需的作用域 groups 和 write 。