python实现github oauth2认证
# !/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
import json
import subprocess
from http import HTTPStatus
from bottle import Bottle, request, redirect, template, static_file, run
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
app = Bottle()
CLIENT_ID = '4520e5d3f12345b26c0'
CLIENT_SECRET = '505974f6764fe4123456186007256fae00b3f652'
AUTHORIZATION_URL = 'https://github.com/login/oauth/authorize'
ACCESS_TOKEN_URL = 'https://github.com/login/oauth/access_token'
USER_INFO_URL = 'https://api.github.com/user'
# REDIRECT_URL = 'https://b97b-223-112-131-202.ngrok-free.app/api/vdi-server/user/localLogin'
REDIRECT_URL = 'http://vdi.local.com/callback'
@app.route('/')
def index():
# 构造授权链接
auth_url = f"{AUTHORIZATION_URL}?client_id={CLIENT_ID}&redirect_uri={REDIRECT_URL}&state=terminal_or_admin_id"
return template('''
<html>
<body>
<h1>Welcome!</h1>
<h1>Please click href login!</h1>
<a href="{{auth_url}}">Login with GitHub</a>
</body>
</html>
''', auth_url=auth_url)
# print(auth_url)
# redirect(auth_url)
@app.route('/callback')
def app_redirect():
# 从GitHub获取code
query = request.query
print('code_request_url=', request.url)
print(query, type(query))
code = query.get('code')
if not code:
print('params code not found!')
return template('''
<html>
<body>
<h1>Welcome, {{login}}!</h1>
</body>
</html>
''', login='NOT FOUND')
print('code=', code)
print('state=', query.get('state'))
# 使用code获取access_token
data = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'code': code,
# 'redirect_uri': 'http://localhost:5000/customer/github/redirect'
}
headers = {'Accept': 'application/json'}
response = requests.post(ACCESS_TOKEN_URL, params=data, headers=headers, verify=False, timeout=5)
print('request url', response.request.url)
if response.status_code != HTTPStatus.OK:
print('request token error', response.status_code)
return
access_token = response.json().get('access_token')
print('access_token=', access_token)
# 使用access_token获取用户信息
headers = {'Authorization': f'token {access_token}'}
user_response = requests.get(USER_INFO_URL, headers=headers, verify=False, timeout=5)
if user_response.status_code != HTTPStatus.OK:
print('request user error', user_response.status_code)
return
user_data = user_response.json()
print('user=', json.dumps(user_data))
# 显示用户信息
return template('''
<html>
<body>
<h1>Welcome, {{login}}!</h1>
<p>Your GitHub id is {{id}}.</p>
<p>Your GitHub login is {{login}}.</p>
</body>
</html>
''', **user_data)
# 运行服务器
if __name__ == '__main__':
run(app, host='localhost', port=80)
# run(app, host='0.0.0.0', port=5000)
网友评论