令牌创建

令牌端点向已获得授权访问的客户端颁发令牌,无论是通过用户的显式操作还是隐式操作。令牌响应定义良好,通常由不可猜测的访问令牌、令牌类型、从现在起的过期时间(以秒为单位)以及将用于在未经授权的情况下获取新访问令牌的刷新令牌组成。

OAuth 2比OAuth 1更具可伸缩性的一个理由是令牌可能包含隐藏信息。提供商可以通过对令牌进行加密来将诸如客户标识符、用户标识符、到期时间等信息嵌入令牌中。这略微增加了解密令牌所需的工作量,但释放了否则所需的必要数据库查找,从而显著改善了延迟。OAuthlib目前没有提供创建密码令牌的方法,但将来可能会提供。

标准令牌类型“持有者”不要求提供程序将特定客户端绑定到令牌。不将客户端绑定到令牌允许匿名令牌,除非您确定需要它们,否则这不是一个好主意。

Token Request

POST请求用于大多数授权类型,但具有不同的凭据设置。如果希望在请求中嵌入额外的凭据,即供以后在验证或创建令牌时使用,则可以使用 credentials 中的论点 create_token_response

所有响应都是json格式,并且由 create_token_response 将包含一些与内容类型和缓存相关的建议标头。

# Initial setup
from your_validator import your_validator
server = WebApplicationServer(your_validator)

# Validate request
uri = 'https://example.com/token'
http_method = 'POST'
body = 'code=somerandomstring&'
       'grant_type=authorization_code&'
# Clients authenticate through a method of your choosing, for example
# using HTTP Basic Authentication
headers = { 'Authorization': 'Basic ksjdhf923sf' }

# Extra credentials you wish to include
credentials = {'client_ip': '1.2.3.4'}

headers, body, status = server.create_token_response(
    uri, http_method, body, headers, credentials)

# headers will contain some suggested headers to add to your response
{
    'Content-Type': 'application/json',
    'Cache-Control': 'no-store',
    'Pragma': 'no-cache',
}
# body will contain the token in json format and expiration from now
# in seconds.
{
    'access_token': 'sldafh309sdf',
    'refresh_token': 'alsounguessablerandomstring',
    'expires_in': 3600,
    'scope': 'https://example.com/userProfile https://example.com/pictures',
    'token_type': 'Bearer'
}
# body will contain an error code and possibly an error description if
# the request failed, also in json format.
{
    'error': 'invalid_grant_type',
    'description': 'athorizatoin_coed is not a valid grant type'
}
# status will be a suggested status code, 200 on ok, 400 on bad request
# and 401 if client is trying to use an invalid authorization code,
# fail to authenticate etc.

from your_framework import http_response
http_response(body, status=status, headers=headers)
class oauthlib.oauth2.TokenEndpoint(default_grant_type, default_token_type, grant_types)[源代码]

令牌颁发终结点。

令牌端点由客户端用于通过提供其授权授权或刷新令牌来获取访问令牌。令牌端点用于除隐式授权类型之外的所有授权授权(因为访问令牌是直接颁发的)。

客户端获取令牌端点的位置的方法超出了本规范的范围,但该位置通常在服务文档中提供。

端点URI可以包括格式化(PER)的“应用程序/x-www-form-urlencode Appendix B )查询组件,添加其他查询参数时必须保留该组件。终结点URI不得包含片段组件::

https://example.com/path?query=component             # OK
https://example.com/path?query=component#fragment    # Not OK

由于对令牌端点的请求导致明文凭据的传输(在HTTP请求和响应中),因此授权服务器在向令牌端点发送请求时必须要求使用第1.6节所述的TLS::

# We will deny any request which URI schema is not with https

客户端在发出访问令牌请求时必须使用HTTP“POST”方法:

# HTTP method is currently not enforced

发送的没有值的参数必须被视为已从请求中省略。授权服务器必须忽略无法识别的请求参数。请求和响应参数不得包含多次::

# Delegated to each grant type.
create_token_response(uri, http_method='POST', body=None, headers=None, credentials=None, grant_type_for_scope=None, claims=None)[源代码]

提取GRANT_TYPE并路由到指定的处理程序。