django oAuth2
 2017-11-20

Oauth2 Django

Part I

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
```python
url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')),

Part II

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"
    }
    
  7. 带着headers={‘acess_token’: ‘xxx’}访问A的url,则A访问数据库,返回给B所需要的信息。
  8. 重写template的授权页面,在templates添加oauth2_provider目录,在其中添加authorize.html,重写界面,第一行扩展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)