仅当您运行需要响应用户请求以进行身份验证的 Web 应用程序时,才需要重定向 URL。如果您以编程方式进行身份验证,您可以简单地将其设置为http://localhost。在需要用户手动进行身份验证的场景中,重定向 URL 应该调用 Web 应用程序中的某个函数来存储和处理返回的身份验证代码。您需要运行服务器吗?好吧,如果您想对返回的身份验证代码做一些事情,您指定的 URL 应该在您的控制之下并调用代码来做一些有用的事情。
store_tokens
这是函数应该是什么样子的示例。它应该接受两个参数,access_token
和refresh_token
。在下面的示例中,该函数会将这些提交到本地存储以供 API 需要重新验证时使用:
从这里开始:
"""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()