Python - Getting url a browser was redirected to

梦想的初衷 提交于 2019-12-03 15:14:36

问题


I am trying to authenticate an application with the API.
Here's How:

  1. I am opening a URL using webbrowser.open.
  2. The user authenticates the application, and is redirected to another URL, which is
    https://stackexchange.com/oauth/login_successwith arguments encoded with this URL.
    A sample redirect url is:
    .../login_success#access_token=xyz&expires=00000

My Current code:

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)

How can I get the redirect URL (the URL the user is taken to) after the user authenticates themselves???


回答1:


Try to fire up your own little HTTP server for just one request, let the API redirect to it and wait for the redirected request to appear. This is not a complete example, just the basic concept:

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()

You probably need to use HTTPS though. In the long run, you might be better off with an existing OAuth implementation.




回答2:


After the user authenticates with stack exchange, the SE page will redirect back to your page ("redirect_uri" below). Your code currently redirects to https://stackexchange.com/oauth/login_success ; instead, you should redirect to a page you control.

  1. Open a new window at https://stackexchange.com/oauth/dialog, with these query string parameters
    • client_id
    • scope
    • redirect_uri
    • state - optional
  2. The user approves your app
  3. The user is redirected to redirect_uri, with these parameters in the hash
    • access_token
    • expires - optional, only if scope doesn't contain no_expiry

source: https://api.stackexchange.com/docs/authentication



来源:https://stackoverflow.com/questions/15492917/python-getting-url-a-browser-was-redirected-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!