保护 Heroku 的 REST API 可以通过以下几种方法实现:
import requests
api_key = 'your_api_key'
headers = {'Authorization': f'Bearer {api_key}'}
response = requests.get('https://api.heroku.com/your-endpoint', headers=headers)
import requests
from requests_oauthlib import OAuth2Session
client_id = 'your_client_id'
client_secret = 'your_client_secret'
redirect_uri = 'https://your-redirect-uri'
oauth = OAuth2Session(client_id, redirect_uri=redirect_uri)
authorization_url, state = oauth.authorization_url('https://api.heroku.com/oauth/authorize')
# 用户通过浏览器访问 authorization_url,授权后重定向到 redirect_uri,并返回授权码
code = 'authorization_code'
token = oauth.fetch_token('https://api.heroku.com/oauth/token', code=code, client_secret=client_secret)
response = oauth.get('https://api.heroku.com/your-endpoint')
import requests
whitelisted_ips = ['127.0.0.1', '192.168.0.1']
current_ip = requests.get('https://api.ipify.org').text
if current_ip in whitelisted_ips:
response = requests.get('https://api.heroku.com/your-endpoint')
else:
# 处理未授权的请求
以上是保护 Heroku 的 REST API 的几种常见方法。根据实际需求和安全要求,你可以选择适合你的方法或结合多种方法来保护 API。