自动化框验证 - Python

时间:2015-11-06 18:29:49

标签: python selenium oauth oauth-2.0 box

我正在编写一个与我的Box帐户直接互动的应用。我需要执行Python SDK API中列出的所有操作。果然,我正试图克服认证部分。鉴于我的client_idclient_secret,我有以下脚本:

#!/usr/bin/env python
import boxsdk
import requests

def store_tokens_callback(access_token, refresh_token):
    # I don't know why this is never being called.
    print access_token, refresh_token

oauth = boxsdk.OAuth2(
    client_id="<my_client_id>",
    client_secret="<client_secret>",
    store_tokens=store_tokens_callback,
)

auth_url, csrf_token = oauth.get_authorization_url('http://127.0.0.1')
print auth_url
print csrf_token
r = requests.get(auth_url)
print r.text
client = boxsdk.Client(oauth)

我得到auth_url

https://app.box.com/api/oauth2/authorize?state=box_csrf_token_<csrf_tken>&response_type=code&client_id=<client_id>&redirect_uri=http%3A%2F%2F127.0.0.1

但是,始终单击该URL将无法执行此操作。我需要一种方法来自动执行此authentication流程,因此我不必每次都点击此按钮:enter image description here

果然,我可以添加一点Selenium任务来点击该按钮并获取带有代码的网址,但是我正在寻找更简单的线路之间的内容。 几个问题:

  • 如何在auth
  • 中自动执行Box SDK流程
  • 为什么stoke_tokens_callback没有被调用?

2 个答案:

答案 0 :(得分:1)

查看enterprise edition documentation,它允许您仅通过API调用进行交互(无需点击按钮)。

答案 1 :(得分:0)

我有完全相同的要求。 SDK将使用60天刷新令牌在过期时处理刷新访问令牌。刷新令牌本身也会刷新,这意味着它再有60天有效。使用下面的代码,只要每60天至少调用一次API,首先“启动”访问和刷新令牌就会很好。按照Box SDK说明获取初始访问权限并刷新令牌。然后,您必须安装这些Python模块:

pip.exe install keyring
pip.exe install boxsdk

然后使用keyring.exe来填充凭据存储:

keyring.exe set Box_Auth <AuthKey>
keyring.exe set Box_Ref <RefreshKey>

From here

"""An example of Box authentication with external store"""

import keyring
from boxsdk import OAuth2
from boxsdk import Client

CLIENT_ID = 'specify your Box client_id here'
CLIENT_SECRET = 'specify your Box client_secret here'


def read_tokens():
    """Reads authorisation tokens from keyring"""
    # Use keyring to read the tokens
    auth_token = keyring.get_password('Box_Auth', 'mybox@box.com')
    refresh_token = keyring.get_password('Box_Refresh', 'mybox@box.com')
    return auth_token, refresh_token


def store_tokens(access_token, refresh_token):
    """Callback function when Box SDK refreshes tokens"""
    # Use keyring to store the tokens
    keyring.set_password('Box_Auth', 'mybox@box.com', access_token)
    keyring.set_password('Box_Refresh', 'mybox@box.com', refresh_token)


def main():
    """Authentication against Box Example"""

    # Retrieve tokens from secure store
    access_token, refresh_token = read_tokens()

    # Set up authorisation using the tokens we've retrieved
    oauth = OAuth2(
        client_id=CLIENT_ID,
        client_secret=CLIENT_SECRET,
        access_token=access_token,
        refresh_token=refresh_token,
        store_tokens=store_tokens,
    )

    # Create the SDK client
    client = Client(oauth)
    # Get current user details and display
    current_user = client.user(user_id='me').get()
    print('Box User:', current_user.name)

if __name__ == '__main__':
    main()
相关问题