flask使用github登录

Flask框架 2020-09-01 1177

.flaskenv配置文件

import os
GITHUB_CLIENT_ID = os.getenv('github_client_id')
GITHUB_CLIENT_SECRET = os.getenv('github_client_secret')

 

from flask import Flask, render_template, request, make_response, jsonify, session, url_for, redirect
import os
from authlib.integrations.flask_client import OAuth

app = Flask(__name__)
app.secret_key = 'xds6d*/s/+d8s452264552ddsdsd95d5fv52cx6s9'
app.config['GITHUB_CLIENT_ID'] = os.getenv('github_client_id')
app.config['GITHUB_CLIENT_SECRET'] = os.getenv('github_client_secret')
app.config['GITHUB_AUTHORIZE_URL'] = os.getenv('github_authorize_url')
app.config['GITHUB_ACCESS_TOKEN_URL'] = 'https://github.com/login/oauth/access_token'
oauth = OAuth(app)
oauth.register(
    name='github',
)
@app.route('/')
def homepage():
    user = session.get('user')
    return render_template('home.html', user=user)


@app.route('/login')
def login():
    redirect_uri = url_for('auth', _external=True)
    print(redirect_uri)
    return oauth.github.authorize_redirect(redirect_uri)


@app.route('/auth', methods=['GET'])
def auth():
    token = oauth.github.authorize_access_token()
    # 重定向后,会自动请求GITHUB_ACCESS_TOKEN_URL
    # 但在此之前,它会解析重定向后的url,入口方法在(authlib>base_app.py>def retrieve_access_token_params)
    # (作用:检索用于获取访问令牌的参数,这些参数来自请求以及会话中先前保存的临时数据。)
    # 并获取参数(可以看authlib>integration.py>def generate_access_token_params)
    # 请求access_token_url,调用方法来自:authlib>integration>flask_client>remote_app.py
    print(token)
    resp = oauth.github.get('https://api.github.com/user', token=token)
    profile = resp.json()
    print(profile)
    return '...'

 

标签:Flask框架

文章评论

评论列表

已有0条评论