最近我研究了一下Flask的OAuth庫。情況並不樂觀,大部分的包都已過時並且不再被支援了。大家熟知的Flask-Oauth基本上已經被廢棄了,我也不推薦依賴這個庫。有趣的是OAuth本身其實是很簡單的,認證之後你會得到一個訪問token,你只需將其作為GET引數或者作為request的特殊的header即可。也許其他的OAuth提供者需要更復雜的邏輯,但是Github僅此就足夠。
我在StackOverflow上請教了如何解決Flask-OAuth的問題 ,從rauth的作者那裡得到回答,他建議試一下他寫的庫。本文就是對他及開源社群的回報。我寫了這個真實的例子,告訴你如何使用Flask、rauth、Github和會話來對你的站點的使用者進行認證。
首先你需要設定好本地的環境。你需要安裝好python、pip和virtualenv。接下來對環境進行設定:
1 2 3 |
$ virtualenv venv $ source venv/bin/activate (venv)$ pip install rauth Flask Flask-SQLAlchemy |
如果要執行我的例子,你還需要安裝Sqlite的python繫結,SQLAlchemy會需要它:
1 |
(venv)$ pip install pysqlite |
pip會安裝所有需要的依賴,所以你的環境已經就緒了。
現在你需要到Github設定頁面裡找到 Applications sections,為你設定好一個新的應用。下圖顯示了在我的配置區域。
下面是程式碼,主模組如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
# github.py from flask import (Flask, flash, request, redirect, render_template, url_for, session) from flask.ext.sqlalchemy import SQLAlchemy from rauth.service import OAuth2Service # Flask config SQLALCHEMY_DATABASE_URI = 'sqlite:///github.db' SECRET_KEY = '\xfb\x12\xdf\xa1@i\xd6>V\xc0\xbb\x8fp\x16#Z\x0b\x81\xeb\x16' DEBUG = True # Flask setup app = Flask(__name__) app.config.from_object(__name__) db = SQLAlchemy(app) # Use your own values in your real application github = OAuth2Service( name='github', base_url='https://api.github.com/', access_token_url='https://github.com/login/oauth/access_token', authorize_url='https://github.com/login/oauth/authorize', client_id= '477151a6a9a9a25853de', client_secret= '23b97cc6de3bea712fddbef70a5f5780517449e4', ) # models class User(db.Model): id = db.Column(db.Integer, primary_key=True) login = db.Column(db.String(80), unique=True) name = db.Column(db.String(120)) def __init__(self, login, name): self.login = login self.name = name def __repr__(self): return '<User %r>' % self.login @staticmethod def get_or_create(login, name): user = User.query.filter_by(login=login).first() if user is None: user = User(login, name) db.session.add(user) db.session.commit() return user # views @app.route('/') def index(): return render_template('login.html') @app.route('/about') def about(): if session.has_key('token'): auth = github.get_session(token = session['token']) resp = auth.get('/user') if resp.status_code == 200: user = resp.json() return render_template('about.html', user = user) else: return redirect(url_for('login')) @app.route('/login') def login(): redirect_uri = url_for('authorized', next=request.args.get('next') or request.referrer or None, _external=True) print(redirect_uri) # More scopes http://developer.github.com/v3/oauth/#scopes params = {'redirect_uri': redirect_uri, 'scope': 'user:email'} print(github.get_authorize_url(**params)) return redirect(github.get_authorize_url(**params)) # same path as on application settings page @app.route('/github/callback') def authorized(): # check to make sure the user authorized the request if not 'code' in request.args: flash('You did not authorize the request') return redirect(url_for('index')) # make a request for the access token credentials using code redirect_uri = url_for('authorized', _external=True) data = dict(code=request.args['code'], redirect_uri=redirect_uri, scope='user:email,public_repo') auth = github.get_auth_session(data=data) # the "me" response me = auth.get('user').json() user = User.get_or_create(me['login'], me['name']) session['token'] = auth.access_token session['user_id'] = user.id flash('Logged in as ' + me['name']) return redirect(url_for('index')) if __name__ == '__main__': db.create_all() app.run() |
模板:
1 2 3 4 5 6 7 8 |
<!-- templates/about.html --> <!doctype html> <title>Login</title> <h1>About you</h1> Welcome , and your email is <br /> <a href ="">Main page</a> |
1 2 3 4 5 6 7 8 |
<!-- templates/login.html --> <!doctype html> <title>Login</title> <h1>Login</h1> <a href ="">Login with OAuth2</a> <h1>About</h1> <a href="">About</a> If you are not logged in then you will be redirected to login page. |
啟動後將建立資料庫:
1 |
(venv)$ python github.py |
在瀏覽器開啟網站後,將在 session 儲存 login.access_token,這是不安全的,但作為例子已經足夠了。實際的網站中你可以這樣使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Probably your User model placed in different blueprint from authmodule.models import User @app.before_request def before_request(): g.user = None if 'user_id' in session: if session['user_id']: user = User.query.get(session['user_id']) if user: g.user = user else: del session['user_id'] |
相關連結:
- rauth https://github.com/litl/rauth
- Github developers API http://developer.github.com/
- Flask http://flask.pocoo.org/
- SQLAlchemy http://www.sqlalchemy.org/
- Flask-SQLAlchemy http://pythonhosted.org/Flask-SQLAlchemy/
- More complex applicaion examplebakery https://github.com/xen/bakery/