我正在尝试使用 API 对应用程序进行身份验证。
方法如下:
- 我正在使用
webbrowser.open
打开一个 URL。 - 用户对应用程序进行身份验证,并被重定向到另一个 URL,即
https://stackexchange.com/oauth/login_success
使用此 URL 编码的参数。
示例重定向 URL 是:
.../login_success#access_token=xyz&expires=00000
我当前的代码:
auth_url = 'https://stackexchange.com/oauth/dialog'
def authenticate():
scope = "write_access,private_info,read_inbox"
url = make_url(auth_url,client_id=132,
scope=scope,response_type='code',
redirect_uri='https://stackexchange.com/oauth/login_success')
webbrowser.open(url)
如何在用户对自己进行身份验证后获取重定向 URL(用户被带到的 URL)???
最佳答案
尝试为一个请求启动您自己的小型 HTTP 服务器,让 API 重定向到它并等待重定向的请求出现。这不是一个完整的例子,只是基本概念:
import BaseHTTPServer
auth_url = 'https://stackexchange.com/oauth/dialog'
# replace with your own http handlers
def wait_for_request(server_class=BaseHTTPServer.HTTPServer,
handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
return httpd.handle_request()
def authenticate():
scope = "write_access,private_info,read_inbox"
url = make_url(auth_url,client_id=132,
scope=scope,response_type='code',
redirect_uri='http://localhost:8000/login_success')
webbrowser.open(url)
wait_for_request()
不过您可能需要使用 HTTPS。从长远来看,使用现有的 OAuth 实现可能会更好。
关于Python - 获取浏览器被重定向到的网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15492917/