代码示例: 下面是一个OAuth2库的基本示例,显示如何使用Basecamp API OAuth2令牌进行身份验证。
import requests
from requests_oauthlib import OAuth2Session
# Basecamp API URLs
auth_url = 'https://launchpad.37signals.com/authorization/new'
token_url = 'https://launchpad.37signals.com/authorization/token'
# Basecamp API OAuth2数据
client_id = 'YOUR_CLIENT_ID'
client_secret = 'YOUR_CLIENT_SECRET'
redirect_uri = 'YOUR_REDIRECT_URI'
scope = ['YOUR_SCOPE']
# 请求Basecamp API的访问令牌
oauth = OAuth2Session(client_id, redirect_uri=redirect_uri, scope=scope)
authorization_url, _ = oauth.authorization_url(auth_url)
print(authorization_url)
authorization_response = input('Authorization response: ')
oauth.fetch_token(token_url, authorization_response=authorization_response, client_secret=client_secret)
# 使用访问令牌调用Basecamp API
url = 'https://3.basecampapi.com/{}/projects.json'.format(client_id)
headers = {'Authorization': 'Bearer ' + oauth.access_token}
response = requests.get(url, headers=headers)
print(response.json())
在上面的示例中,首先使用OAuth2Session对象获取Authorization URL。用户将访问URL确认授权,然后使用authorization_response参数调用fetch_token()获取访问令牌。最后使用Bearer token头授权访问Basecamp API。