根据用户名密码进行论坛oauth授权

始皇提供的接口需要用户自行登录,不方便纯服务端验证,写了一个代码自动点击回调URL中的按钮:

代码
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from requests_oauthlib import OAuth2Session
from urllib.parse import urlparse, urlunparse
import time
client_id = 'hi3geJYfTotoiR5S62u3rh4W5tSeC5UG'
redirect_uri = 'http://localhost:8181/oauth2/callback'
username = '用户名'
password = '密码'
oauth = OAuth2Session(client_id=client_id, redirect_uri=redirect_uri)
authorization_url, state = oauth.authorization_url('https://connect.linux.do/oauth2/authorize')
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options)
driver.get(authorization_url)
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "login-account-name"))).send_keys(username)
driver.find_element(By.ID, "login-account-password").send_keys(password + Keys.RETURN)
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@class, 'bg-red-500')]"))).click()
time.sleep(5)
redirected_url_https = driver.current_url
driver.quit()
parsed_url = urlparse(redirected_url_https)
if parsed_url.scheme != 'https':
    redirected_url_https = urlunparse(parsed_url._replace(scheme='https'))
token = oauth.fetch_token('https://connect.linux.do/oauth2/token',
                          authorization_response=redirected_url_https,
                          client_secret='VMPBVoAfOB5ojkGXRDEtzvDhRLENHpaN')
response = oauth.get('https://connect.linux.do/api/user')
print(response.json())

1 Like

常规话题软件开发

这些如何应对?

2 Likes

看也看不懂

暂时没想好,我记得pandora获取assecstoken,第三方登录还是要老老实实用官网

对,这是我只放了code获取的原因。

2 Likes