Python - 获取浏览器重定向后的URL
我正在尝试通过API来验证一个应用程序。
下面是具体步骤:
- 我使用
webbrowser.open
打开一个网址。 - 用户完成应用程序的验证后,会被重定向到另一个网址,这个网址是
https://stackexchange.com/oauth/login_success
,并且这个网址中包含了一些编码的参数。
一个示例重定向网址是:
.../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)
我该如何获取重定向网址(用户完成验证后被带到的网址)呢???
3 个回答
-1
当用户在 Stack Exchange 上完成身份验证后,页面会跳转回你的页面(下面的 "redirect_uri")。你现在的代码是跳转到 https://stackexchange.com/oauth/login_success;但你应该把它改成跳转到你自己控制的页面。
- 在 https://stackexchange.com/oauth/dialog 打开一个新窗口,并添加以下查询参数:
- client_id
- scope
- redirect_uri
- state - 可选
- 用户批准你的应用
- 用户会被重定向到 redirect_uri,并在地址中带上这些参数:
- access_token
- expires - 可选,只有在 scope 不包含 no_expiry 时才会有
0
我之前也遇到过同样的问题,后来发现自己犯了个小错误。如果你要进行页面跳转,并且需要从浏览器获取网址,你必须确保有一个可以让其他应用程序返回的地址。
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')
redirect(url)
你可以在用户当前的窗口中进行跳转,然后他们被跳转到的其他应用程序会使用你指定的redirect_uri把他们再跳转回你的应用程序。
3
试着自己搭建一个小的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实现可能会更好。