您的位置:首页 > 编程语言 > Go语言

Django Rest Framework--oauth实验笔记--参考官方文档

2017-12-28 10:02 381 查看
很多内容官方文档都不是最新的,需要结合github上的doc,以及自己的实战经验进行分析

https://github.com/evonove/django-oauth-toolkit/blob/master/docs/rest-framework/getting_started.rst

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/[/code] 
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/[/code] 

Retrieve groups

curl -H "Authorization: Bearer <your_access_token>" http://localhost:8000/groups/[/code] 

Insert a new user

curl -H "Authorization: Bearer <your_access_token>" -X POST -d"username=foo&password=bar" http://localhost:8000/users/[/code] 

自己实验一下:

注册自己的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"}]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  django rest oauth 实战