Flask OAuth 示例项目教程
1. 项目的目录结构及介绍
flask-oauth-example/
├── templates/
│ └── env_template
├── .gitignore
├── LICENSE
├── README.md
├── app.py
├── requirements.txt
- templates/: 包含项目的环境模板文件。
- .gitignore: 指定Git版本控制系统忽略的文件和目录。
- LICENSE: 项目的许可证文件。
- README.md: 项目的说明文档。
- app.py: 项目的启动文件。
- requirements.txt: 项目依赖的Python包列表。
2. 项目的启动文件介绍
app.py 是项目的启动文件,负责初始化Flask应用并配置OAuth服务。以下是文件的主要内容:
from flask import Flask, redirect, url_for, session, request
from flask_oauth import OAuth
app = Flask(__name__)
app.config.from_pyfile('config.py')
oauth = OAuth()
# 配置Google OAuth
google = oauth.remote_app(
'google',
base_url='https://www.google.com/accounts/',
request_token_url=None,
access_token_url='https://accounts.google.com/o/oauth2/token',
authorize_url='https://accounts.google.com/o/oauth2/auth',
consumer_key=app.config.get('GOOGLE_CLIENT_ID'),
consumer_secret=app.config.get('GOOGLE_CLIENT_SECRET'),
request_token_params={'scope': 'https://www.googleapis.com/auth/userinfo.email'}
)
# 配置GitHub OAuth
github = oauth.remote_app(
'github',
base_url='https://github.com/login/oauth/',
request_token_url=None,
access_token_url='https://github.com/login/oauth/access_token',
authorize_url='https://github.com/login/oauth/authorize',
consumer_key=app.config.get('GITHUB_CLIENT_ID'),
consumer_secret=app.config.get('GITHUB_CLIENT_SECRET')
)
@app.route('/')
def index():
return 'Hello, World!'
@app.route('/login/google')
def login_google():
return google.authorize(callback=url_for('authorized_google', _external=True))
@app.route('/login/github')
def login_github():
return github.authorize(callback=url_for('authorized_github', _external=True))
@app.route('/authorized/google')
def authorized_google():
resp = google.authorized_response()
if resp is None:
return 'Access denied: reason=%s error=%s' % (
request.args['error_reason'],
request.args['error_description']
)
session['google_token'] = (resp['access_token'], '')
return redirect(url_for('index'))
@app.route('/authorized/github')
def authorized_github():
resp = github.authorized_response()
if resp is None:
return 'Access denied: reason=%s error=%s' % (
request.args['error_reason'],
request.args['error_description']
)
session['github_token'] = (resp['access_token'], '')
return redirect(url_for('index'))
if __name__ == '__main__':
app.run()
3. 项目的配置文件介绍
项目的配置文件通常是一个Python文件,例如 config.py
,其中包含应用的配置信息,如OAuth客户端ID和密钥。以下是一个示例配置文件的内容:
import os
SECRET_KEY = os.urandom(24)
GOOGLE_CLIENT_ID = 'your-google-client-id'
GOOGLE_CLIENT_SECRET = 'your-google-client-secret'
GITHUB_CLIENT_ID = 'your-github-client-id'
GITHUB_CLIENT_SECRET = 'your-github-client-secret'
- SECRET_KEY: Flask应用的密钥,用于会话加密。
- **GO