跳转到主要内容

OAuth客户端

项目描述

https://travis-ci.org/globocom/alf.svg?branch=master

Python OAuth 2 客户端

alf 是一个基于 requests.Session 的 OAuth 2 客户端,它对 客户端凭据流 提供无缝支持。

/assets/alf.jpeg?raw=true

功能

  • 自动获取和续签令牌

  • 令牌过期控制

  • 自动存储令牌

  • 在状态401 (未授权) 上自动重试

用法

初始化客户端并将其用作 requests.Session 对象。

from alf.client import Client

alf = Client(
    token_endpoint='http://example.com/token',
    client_id='client-id',
    client_secret='secret')

resource_uri = 'http://example.com/resource'

alf.put(
    resource_uri, data='{"name": "alf"}',
    headers={'Content-Type': 'application/json'})

alf.get(resource_uri)

alf.delete(resource_uri)

使用自定义令牌存储

现在你可以传递一个具有get和set属性的对象来存储或检索令牌。

此对象可以是Redis、Memcache或您自定义的对象。

from alf.client import Client
from redis import StrictRedis

redis = StrictRedis(host='localhost', port=6379, db=0)

alf = Client(
    token_endpoint='http://example.com/token',
    client_id='client-id',
    client_secret='secret',
    token_storage=redis)

resource_uri = 'http://example.com/resource'

alf.put(
    resource_uri, data='{"name": "alf"}',
    headers={'Content-Type': 'application/json'})

alf.get(resource_uri)

alf.delete(resource_uri)

它是如何工作的?

在请求之前,认证端点会请求一个令牌,并期望返回一个包含 access_tokenexpires_in 键的 JSON 响应。

如果使用了 token_retries 参数,端点错误响应后将会进行多次尝试。有关更多信息,请参阅 token-retrying

alf 会根据 expires_in 值保留令牌,直到其过期。

令牌将用于原始请求的 Bearer 授权头

GET /resource/1 HTTP/1.1
Host: example.com
Authorization: Bearer token-12312

如果请求因 401 (未授权) 状态码而失败,则从端点获取新的令牌并重试请求。这只会发生一次,如果再次失败,则返回错误响应。

在令牌过期之前,将重复使用该令牌进行每个后续请求。

令牌重试

客户端支持从 urllib3 的 重试接口 来重复尝试从端点获取令牌。

以下代码将在响应状态为 500 时重试令牌请求 5 次,并且每次错误后等待 0.3 秒更长(称为 指数退避)。

from requests.packages.urllib3.util import Retry
from alf.client import Client

alf = Client(
    token_endpoint='http://example.com/token',
    client_id='client-id',
    client_secret='secret',
    token_retry=Retry(total=5, status_forcelist=[500], backoff_factor=0.3))

工作流程

/assets/workflow.png?raw=true

故障排除

在检索令牌出错的情况下,将返回错误响应,实际请求不会发生。

项目详情


下载文件

下载您平台上的文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。

源分布

alf-0.7.1.tar.gz (7.9 kB 查看散列)

上传时间

由以下支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面