2015-11-06 44 views
0

我正在寫一個應用程序,它可以直接與我的Box帳戶進行交互。我需要執行Python SDK API中列出的所有操作。果然,我試圖通過認證部分。鑑於我client_idclient_secret,我有以下腳本:自動化身份驗證 - Python

#!/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任務中獲得點擊該按鈕,並獲得與網址代碼,但是我正在尋找更容易......線條之間的東西。 幾個問題:

  • 我怎麼能自動地在Box SDKauth過程?
  • 爲什麼不調用stoke_tokens_callback
+0

我想了解點你的行爲,但目前爲止沒有用)你想做什麼? Box是一個簡單的網頁應用程序,登錄(用戶名/密碼)頁面,您正嘗試通過身份驗證或什麼? – Andersson

回答

0

我有完全一樣的要求。 SDK將在使用60天刷新令牌時刷新訪問令牌。刷新標記本身也被刷新,這意味着它還有60天有效。使用下面的代碼,只要API每60天至少被調用一次,首先「準備好」訪問刷新令牌就會很好。按照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', '[email protected]') 
    refresh_token = keyring.get_password('Box_Refresh', '[email protected]') 
    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', '[email protected]', access_token) 
    keyring.set_password('Box_Refresh', '[email protected]', 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()