liboauth2python oauth2 客户端
liboauth2 是一个轻量级的oauth2 python客户端。
liboauth2 只是实现oauth2协议,并没有实现任何第三方oauth2认证。
如果需要实现第三登录,可以看pysns
支持四种认证方式
一、Authorization Code授权码方式
二、Implicit Grant隐式授权
三、Resource Owner Password Credentials
四、Client Credentials客户端证书授权
安装
easy_install liboauth2
腾讯微博演示
# -*- coding: utf-8 -*- import liboauth2 import urllib from flask import Flask, redirect, request CLIENT_ID = 'you client id' CLIENT_SECRET = 'you client secret' client = liboauth2.Client(CLIENT_ID, CLIENT_SECRET) REDIRECT_URI = 'http://localhost:5000/callback/' AUTH_URI = 'https://open.t.qq.com/cgi-bin/oauth2/authorize' ACCESS_TOKEN_URL = 'https://open.t.qq.com/cgi-bin/oauth2/access_token' app = Flask(__name__) app.debug = True @app.route('/') def home(): # get auth url url = client.get_auth_url(AUTH_URI, REDIRECT_URI) return redirect(url) @app.route('/callback/') def callback(): # get access token params = {'code': request.args['code'], 'redirect_uri': REDIRECT_URI} resp = client.get_access_token(ACCESS_TOKEN_URL, liboauth2.GRANT_TYPE_AUTH_CODE, params) # print resp def urldecode(values): ret = {} for s in values.split('&'): if s.find('=') > -1: k, v = map(urllib.unquote, s.split('=')) ret[k] = v #ret.setdefault(k, []).append(v) return ret data = urldecode(resp['result']) # set access token and query user info client.set_access_token(data['access_token']) params = { 'oauth_consumer_key': CLIENT_ID, 'openid': data['openid'], 'clientip': request.remote_addr, 'oauth_version': '2.a', } resp = client.fetch('http://open.t.qq.com/api/user/info', params) return str(resp['result']) if __name__ == '__main__': app.run(host='localhost', port=5000)
评论