django实战oauth2 provider/consumer和google oauth2详解

时间:2022-12-19 21:00:47

Oauth2 Django

Part I

  • Install
pip install django-oauth-toolkit django-cors-middleware
  • source/config/setting.py
INSTALLED_APPS += (
'django_extensions',
'debug_toolbar',
'oauth2_provider',
'corsheaders',
)

MIDDLEWARE += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
'corsheaders.middleware.CorsMiddleware',
)
CORS_ORIGIN_ALLOW_ALL = True

AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'oauth2_provider.backends.OAuth2Backend',
)
  • source/config/urls.py
url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')),
  • Migrate
python source/manger.py migrate

Part II

  • Register your application
http://localhost:8000/o/applications/ 
  • Information
*Client id* and *Client Secret* are automatically generated;
ID = kzsUOB12CcXKkSZfG90dLcons33daYYqafjBUdAw
secret = qN7MiCfG9cUpo2kAaj0lDkbpNBBgHKlIiO3GeeGS2dQkxwFUVS2NpWlPVCiVCpmnEjTLYtIPWBJwubWGB3SqF4fKypqsyVCCvX5DebaQW82shdyQIH96lWcPWFKYUtBj

Part III

注:当前的两个程序,A为provider(提供权限的一方)端口为8000,B为请求的一方,端口为8082
  1. 请求Bhttp://127.0.0.1:8082,设置url重定向
  2. 重定向A的http://127.0.0.1:8000/o/authorize/?state=xx&client_id=xx&response_type=code
  3. 浏览器请求,A判断是否登录,authorize是login_required的,所以会先判断是否登录,然后进入授权界面
  4. 按照预先返回的要求,重定向到指定url
  5. 在该url内获取到接收数据code和state,其中code是authorization_code。
  6. 向A的8080请求获取Access Token,http://127.0.0.1:8000/o/token/?code=xx&redirect_uri=xx&grant_type=authorization_code&client_id=xx,注意要用post方法
// 返回
{
"refresh_token": "k6hT71TZIsPIQYVJqxlzcoN6j6k306",
"access_token": "kltBlehmZbSJ9yCWpBv5f8St1oqLhu",
"expires_in": 36000,
"token_type": "Bearer",
"scope": "write read"
}
  1. 带着headers={‘acess_token’: ‘xxx’}访问A的url,则A访问数据库,返回给B所需要的信息。
  2. 重写template的授权页面,在templates添加oauth2_provider目录,在其中添加authorize.html,重写界面,第一行固定为{% extends "base.html" %}

Part IV

  • Google Oauth2
pip install  oauth2client
  • Before Starting
    注册一个帐号在google develop中,并enable相应的权限(scope)API,获取clientID。
  • build a flow
from oauth2client.client import OAuth2WebServerFlow
flow = OAuth2WebServerFlow(client_id='xxx',
client_secret='X1nUWXLi9UxMk-rGj0oWohfb',
# scope='https://www.googleapis.com/auth/plus.login',
scope="https://www.googleapis.com/auth/userinfo.email",
redirect_uri='http://localhost:8002/user/google_token/',
authuser=-1,)
  • First Step
auth_uri = flow.step1_get_authorize_url()
return redirect(auth_uri)
  • Second Step
response = requests.post("https://www.googleapis.com/oauth2/v4/token",
data={'code': code, 'redirect_uri': 'http://localhost:8002/user/google_token/',
'grant_type': 'authorization_code',
'client_id': '769145275139-ano9e5tp62s656jta058176o36pv3qpf.apps.googleusercontent.com',
'client_secret': 'X1nUWXLi9UxMk-rGj0oWohfb'}).json()
res = requests.get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + response["access_token"]).json()
  • Warning: refresh_token only exists in the first time…