github OAuth Apps demo

github oauth 认证登陆的一个demo

from flask import Flask, render_template_string, request, redirect, flash
import requests

app = Flask(__name__)
app.config['SECRET_KEY'] = 'YOUR_SECRET_KEY'
client_id = '' # 申请应用的时候获取
client_secret = ''  # 申请应用的时候获取,只会显示一次,请保存好

@app.route('/auth/github/login')
def github_login():
    return render_template_string(
        "{% for message in get_flashed_messages() %}<div>{{ message }}</div>{% endfor %}" +
        f"<a href='https://github.com/login/oauth/authorize?client_id={client_id}'>github 登录</a>")


@app.route('/auth/github/callback')
def call_back():
    code = request.args.get('code', '')
    if code:
        try:
            access_token = get_access_token(code)
        except KeyError:
            flash("code 错误请重新登录")
            return redirect('/auth/github/login')
        user_info = get_user(access_token)
        # 1. 这里应该保存到数据库里,用户名等信息
        # 2. 登录用户
        # 3. 跳转到别的页面
        return render_template_string(f"用户名: {user_info['login']}, 签名: {user_info['bio']}")
    else:
        return redirect('/')


def get_access_token(code: str) -> str:
    res = requests.post(
        f'https://github.com/login/oauth/access_token?client_id={client_id}&client_secret={client_secret}&code={code}',
        headers={
            'accept': 'application/json'
        })
    return res.json()['access_token']


def get_user(access_token: str) -> dict:
    res = requests.get('https://api.github.com/user', headers={
        'accept': 'application/json',
        'Authorization': f'token {access_token}'
    })
    return res.json()


if __name__ == '__main__':
    app.run()

https://example.lllyyb.com/auth/github/login

# 瞎折腾 

右下角对话与我联系。


评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×