从URL响应获取身份验证代码-Python

从URL响应获取身份验证代码-Python,python,http,url,post,python-requests,Python,Http,Url,Post,Python Requests,我使用来处理OneDrive SDK的身份验证。身份验证按以下方式进行: import onedrivesdk from onedrivesdk.helpers import GetAuthCodeServer redirect_uri = "http://localhost:8080/" client_secret = "your_app_secret" client = onedrivesdk.get_default_client(client_id='your_client_id',

我使用来处理OneDrive SDK的身份验证。身份验证按以下方式进行:

import onedrivesdk
from onedrivesdk.helpers import GetAuthCodeServer

redirect_uri = "http://localhost:8080/"
client_secret = "your_app_secret"

client = onedrivesdk.get_default_client(client_id='your_client_id',
                                        scopes=['wl.signin',
                                                'wl.offline_access',
                                                'onedrive.readwrite'])

auth_url = client.auth_provider.get_auth_url(redirect_uri)

#this will block until we have the code
code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri)

client.auth_provider.authenticate(code, redirect_uri, client_secret)
然而,由于我使用一个EC2实例来运行此身份验证,而且我不想仅仅为此使用浏览器,因此代码会无限期地阻塞。以下是Microsoft提供的
get\u auth\u code

def get_auth_code(auth_url, redirect_uri):
    """Easy way to get the auth code. Wraps up all the threading
    and stuff. Does block main thread.
    Args:
        auth_url (str): URL of auth server
        redirect_uri (str): Redirect URI, as set for the app. Should be 
            something like "http://localhost:8080" for this to work.
    Returns: 
        str: A string representing the auth code, sent back by the server
    """
    HOST, PORT = urlparse(redirect_uri).netloc.split(':')
    PORT = int(PORT)
    # Set up HTTP server and thread
    code_acquired = threading.Event()
    s = GetAuthCodeServer((HOST, PORT), code_acquired, GetAuthCodeRequestHandler)    
    th = threading.Thread(target=s.serve_forever)
    th.start()
    webbrowser.open(auth_url)
    # At this point the browser will open and the code
    # will be extracted by the server
    code_acquired.wait()  # First wait for the response from the auth server
    code = s.auth_code
    s.shutdown()
    th.join()
    return code
我想返回代码。下面是一个
验证url
的示例:

https://login.live.com/oauth20_authorize.srf?scope=wl.offline_access+onedrive.readwrite&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F&response_type=code&client_id='your_client_id'
当我在浏览器中输入该URL时,我会返回代码:

http://localhost:8080/?code=Mb0bba7d1-adbc-9c1d-f790-3709cd0b9f16

因此,我希望通过使用来避免获取代码的繁琐过程。我怎样才能做到这一点呢?

我知道这是一个老问题,但我也遇到了同样的问题——我想使用请求库获取代码。我设法做到了,但我怀疑这不是一个可持续的解决方案。希望在阅读了我的解决方案后,您能够更好地理解身份验证的工作原理,并找到一个改进的解决方案

我有一个带有mySQL数据库的Python Flask应用程序。有时,我想创建数据库备份并将备份文件发送到我的OneDrive,另外我还想在我的Flask应用程序中启动此过程

首先,我在注册了我的应用程序,并添加了一个带有重定向url的新平台Web。我授予应用程序读写权限,并存储应用程序Id(
client\u Id
)和应用程序机密(
client\u Secret

其次,我在我的Flask应用程序中添加了一条新路线。请注意,我的Flask应用程序正在本地主机8080上运行

@app.route("/signin-microsoft", methods=['GET'])
def get_code():
    return 'Yadda'
第三,我将浏览器创建的HTTP请求头复制到我的
请求中。也就是说,我打开Chrome,将
auth_url
粘贴到地址栏,点击enter键,检查请求头并将其内容复制到我的代码中

r = requests.get(auth_url, 
headers = {"Host" : "login.live.com",
           "Connection" : "keep-alive",
           "Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
           "Accept-Encoding" : "gzip, deflate, br",
           "Upgrade-Insecure-Requests" : "1",
           "Accept-Language" : "fi-FI,fi;q=0.9,en-US;q=0.8,en;q=0.7",
           "User-agent" : "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
           "Cookie": (SUPER LONG WONT PASTE HERE)})
第四,我从url解析了代码,请求被重定向

re_url = r.url
code = re_url.split('code=')[-1]
以下是最终代码:

redirect_uri = 'http://localhost:8080/signin-microsoft'
client_secret = CLIENT_SECRET
client_id = CLIENT_ID
api_base_url='https://api.onedrive.com/v1.0/'
scopes=['wl.signin', 'wl.offline_access', 'onedrive.readwrite']

http_provider = onedrivesdk.HttpProvider()
auth_provider = onedrivesdk.AuthProvider(
http_provider = http_provider, client_id=client_id, scopes=scopes)

client = onedrivesdk.OneDriveClient(api_base_url, auth_provider, http_provider)
auth_url = client.auth_provider.get_auth_url(redirect_uri)
r = requests.get(auth_url, 
    headers = {"Host" : "login.live.com",
               "Connection" : "keep-alive",
               "Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
               "Accept-Encoding" : "gzip, deflate, br",
               "Upgrade-Insecure-Requests" : "1",
               "Accept-Language" : "fi-FI,fi;q=0.9,en-US;q=0.8,en;q=0.7",
               "User-agent" : "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36",
               "Cookie": (SUPER LOOONG)})
re_url = r.url
code = re_url.split('code=')[-1]
client.auth_provider.authenticate(code, redirect_uri, client_secret)
我认为这里有两个要点:您需要一个侦听重定向uri的HTTP服务器(在Microsoft的示例中,他们使用HTTP.server中的HTTPServer),并且您需要正确获取请求的头。如果没有标题,请求将无法正确重定向,您将无法获得代码