1. 程式人生 > >Django Rest Framework--oauth實驗筆記--參考官方文件

Django Rest Framework--oauth實驗筆記--參考官方文件

Getting started
Django OAuth Toolkit provide a support layer for Django REST Framework. This tutorial is based on the Django REST Framework example and shows you how to easily integrate with it.
NOTE
The following code has been tested with django 1.7.7 and Django REST Framework 3.1.1
第一步:安裝配置
Step 1: Minimal setup
Create a virtualenv and install following packages using pip…
pip install django-oauth-toolkit djangorestframework
A–自己新建一個專案,配置apps和rest框架

Start a new Django project and add ‘rest_framework’ and ‘oauth2_provider’ to your INSTALLED_APPS setting.

INSTALLED_APPS = (
    'django.contrib.admin',
    ...
    'oauth2_provider',
    'rest_framework',
)

Now we need to tell Django REST Framework to use the new authentication backend. To do so add the following lines at the end of your settings.py module:

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

第二步:建立簡單的受oauth保護的api
Step 2: Create a simple API
Let’s create a simple API for accessing users and groups.
Here’s our project’s root urls.py module:

from
django.conf.urls import url, include from django.contrib.auth.models import User, Group from django.contrib import admin admin.autodiscover() # 高版本不需要 from rest_framework import permissions, routers, serializers, viewsets 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", ) # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope] queryset = User.objects.all() serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated, TokenHasScope] required_scopes = ['groups'] queryset = Group.objects.all() serializer_class = GroupSerializer # Routers provide an easy way of automatically determining the URL conf router = routers.DefaultRouter() router.register(r'users', UserViewSet) router.register(r'groups', GroupViewSet) # 配置url # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browseable API. urlpatterns = [ url(r'^', include(router.urls)), url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')), # ... ] #配置授權範圍 Also add the following to your settings.py module: OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } #配置rest許可權 REST_FRAMEWORK = { # ... 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) }

執行一下資料庫同步

OAUTH2_PROVIDER.SCOPES setting parameter contains the scopes that the application will be aware of, so we can use them for permission check.
Now run the following commands:

python manage.py migrate
python manage.py createsuperuser
python manage.py runserver

The first command creates the tables, the second creates the admin user account and the last one runs the application.
Next thing you should do is to login in the admin at
http://localhost:8000/admin

and create some users and groups that will be queried later through our API.

第三步:註冊一個應用

這裡註冊的時候不需要,填寫回調地址
Step 3: Register an application
To obtain a valid access_token first we must register an application. DOT has a set of customizable views you can use to CRUD application instances, just point your browser at:
http://localhost:8000/o/applications/

Click on the link to create a new application and fill the form with the following data:
● Name: just a name of your choice
● Client Type: confidential
● Authorization Grant Type: Resource owner password-based
Save your app!

第四步:測試token的獲取,以及使用者資訊的訪問
Step 4: Get your token and use your API
At this point we’re ready to request an access_token. Open your shell

curl -X POST -d "grant_type=password&username=<user_name>&password=<password>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/

The user_name and password are the credential of the users registered in your :term:Authorization Server, like any user created in Step 2. Response should be something like:

{
    "access_token": "<your_access_token>",
    "token_type": "Bearer",
    "expires_in": 36000,
    "refresh_token": "<your_refresh_token>",
    "scope": "read write groups"
}

Grab your access_token and start using your new 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" http://localhost:8000/users/

自己實驗一下:

  1. 註冊自己的app
    這裡寫圖片描述

這裡寫圖片描述
2. 選擇認證型別,注意註冊成功後保留client_id和client_secret
這裡寫圖片描述

3 獲取token並且訪問資料


#  注意訪問在post表單中用認證伺服器中註冊過的賬號,而使用者用client_id和client_secret!
$ curl -X POST -d "grant_type=password&username=dev1&password=dev123456" -u"by95yDRGyBW20A9GClHzo31Me9lwnw48l4IB5hWrjOmY6WAcGiQGOQTbVR39D9HzzcrBsCthqF6k68w5waISkkbwxmTJhVsDRiRtdrGk86m7OmWeHjNt5jjlFX7qHSZpO3ILOcTkTVJ4l9" http://localhost:8000/o/token/

{"access_token": "NVAfMELJlxM1s36WjAWuPoUniFlTAb", "token_type": "Bearer", "expires_in": 36000, "refresh_token": "06hvJdUxCpc0jMe5nSMpns9A5VXZiB", "scope": "read write groups"}

$ curl -H "Authorization: Bearer NVAfMELJlxM1s36WjAWuPoUniFlTAb" http://localhost:8000/users/

[{"username":"miao","email":"","first_name":"","last_name":""},{"username":"dev1","email":"","first_name":"","last_name":""},{"username":"dev2","email":"","first_name":"","last_name":""}]

$ curl -H "Authorization: Bearer NVAfMELJlxM1s36WjAWuPoUniFlTAb" http://localhost:8000/users/1/

{"username":"miao","email":"","first_name":"","last_name":""}

$ curl -H "Authorization: Bearer NVAfMELJlxM1s36WjAWuPoUniFlTAb" http://localhost:8000/groups/

[{"name":"superuser"},{"name":"normal"}]