tornado.auth
---使用openid和oauth登录第三方¶
此模块包含各种第三方身份验证方案的实现。
此文件中的所有类都是设计用于 tornado.web.RequestHandler
班级。它们有两种用途:
在登录处理程序上,使用诸如
authenticate_redirect()
,authorize_redirect()
和get_authenticated_user()
建立用户身份并将身份验证令牌存储到数据库和/或cookie中。在非登录处理程序中,使用诸如
facebook_request()
或twitter_request()
使用身份验证令牌向各自的服务发出请求。
由于所有这些服务实现身份验证和授权的方式都稍有不同,所以它们的参数都略有不同。有关完整的文档,请参阅下面的各个服务类。
google oauth的示例用法:
class GoogleOAuth2LoginHandler(tornado.web.RequestHandler,
tornado.auth.GoogleOAuth2Mixin):
async def get(self):
if self.get_argument('code', False):
user = await self.get_authenticated_user(
redirect_uri='http://your.site.com/auth/google',
code=self.get_argument('code'))
# Save the user with e.g. set_secure_cookie
else:
self.authorize_redirect(
redirect_uri='http://your.site.com/auth/google',
client_id=self.settings['google_oauth']['key'],
scope=['profile', 'email'],
response_type='code',
extra_params={'approval_prompt': 'auto'})
通用协议¶
这些类实现OpenID和OAuth标准。它们通常需要子类化才能与任何特定站点一起使用。所需的定制程度将有所不同,但在大多数情况下,覆盖类属性(由于历史原因以下划线开头命名)就足够了。
- class tornado.auth.OpenIdMixin[源代码]¶
OpenID和属性交换的抽象实现。
类属性:
_OPENID_ENDPOINT
:标识提供程序的URI。
- authenticate_redirect(callback_uri: Optional[str] = None, ax_attrs: List[str] = ['name', 'email', 'language', 'username']) None [源代码]¶
重定向到此服务的身份验证URL。
经过身份验证后,服务将重定向回具有其他参数的给定回调URI,这些参数包括
openid.mode
.默认情况下,我们请求认证用户的给定属性(名称、电子邮件、语言和用户名)。如果你的应用不需要所有这些属性,你可以通过ax-attrs关键字参数请求更少的属性。
在 6.0 版更改: 这个
callback
参数已被删除,此方法不再返回可等待的对象。它现在是一个普通的同步函数。
- coroutine get_authenticated_user(http_client: Optional[tornado.httpclient.AsyncHTTPClient] = None) Dict[str, Any] [源代码]¶
在重定向时获取经过身份验证的用户数据。
此方法应由接收来自
authenticate_redirect()
方法(通常与调用它的方法相同;在这种情况下,您将调用get_authenticated_user
如果openid.mode
参数存在且authenticate_redirect
如果不是这样的话。此方法的结果通常用于设置cookie。
在 6.0 版更改: 这个
callback
参数已删除。请改用返回的等待对象。
- get_auth_http_client() tornado.httpclient.AsyncHTTPClient [源代码]¶
返回
AsyncHTTPClient
用于身份验证请求的实例。可以被子类重写以使用默认之外的HTTP客户端。
- class tornado.auth.OAuthMixin[源代码]¶
OAuth 1.0和1.0a的抽象实现。
见
TwitterMixin
下面是一个示例实现。类属性:
_OAUTH_AUTHORIZE_URL
:服务的OAuth授权URL。_OAUTH_ACCESS_TOKEN_URL
:服务的OAuth访问令牌URL。_OAUTH_VERSION
:可以是“1.0”或“1.0a”。_OAUTH_NO_CALLBACKS
:如果服务需要提前注册回调,则将此设置为true。
子类还必须重写
_oauth_get_user_future
and `_ oauth-consumer-token`方法。- async authorize_redirect(callback_uri: Optional[str] = None, extra_params: Optional[Dict[str, Any]] = None, http_client: Optional[tornado.httpclient.AsyncHTTPClient] = None) None [源代码]¶
重定向用户以获取此服务的OAuth授权。
这个
callback_uri
如果您以前向第三方服务注册过回调URI,则可以省略。对于某些服务,必须使用以前注册的回调URI,并且不能通过此方法指定回调。此方法设置一个名为
_oauth_request_token
随后在get_authenticated_user
出于安全目的。此方法是异步的,必须使用
await
或yield
(这和其他的不同auth*_redirect
本模块中定义的方法)。它叫RequestHandler.finish
所以你不应该在它返回后写任何其他的响应。在 3.1 版更改: 现在返回
Future
并接受可选回调,以便与gen.coroutine
.在 6.0 版更改: 这个
callback
参数已删除。请改用返回的等待对象。
- async get_authenticated_user(http_client: Optional[tornado.httpclient.AsyncHTTPClient] = None) Dict[str, Any] [源代码]¶
获取OAuth授权用户和访问令牌。
应该从OAuth回调URL的处理程序调用此方法以完成注册过程。我们使用经过身份验证的用户字典运行回调。此词典将包含
access_key
可用于代表用户向此服务发出授权请求。字典还将包含其他字段,如name
,取决于所使用的服务。在 6.0 版更改: 这个
callback
参数已删除。请改用返回的等待对象。
- _oauth_consumer_token() Dict[str, Any] [源代码]¶
子类必须重写此项才能返回其OAuth使用者密钥。
返回值应为
dict
带钥匙key
和secret
.
- async _oauth_get_user_future(access_token: Dict[str, Any]) Dict[str, Any] [源代码]¶
子类必须重写此项才能获取有关用户的基本信息。
应该是一个协程,其结果是一个包含有关用户信息的字典,可以使用
access_token
向服务部门提出请求。访问令牌将添加到返回的字典中,以使
get_authenticated_user
.在 5.1 版更改: 子类也可以用
async def
.在 6.0 版更改: 同步回退到
_oauth_get_user
被移除。
- get_auth_http_client() tornado.httpclient.AsyncHTTPClient [源代码]¶
返回
AsyncHTTPClient
用于身份验证请求的实例。可以被子类重写以使用默认之外的HTTP客户端。
- class tornado.auth.OAuth2Mixin[源代码]¶
OAuth 2.0的抽象实现。
见
FacebookGraphMixin
或GoogleOAuth2Mixin
下面的示例实现。类属性:
_OAUTH_AUTHORIZE_URL
:服务的授权URL。_OAUTH_ACCESS_TOKEN_URL
:服务的访问令牌URL。
- authorize_redirect(redirect_uri: Optional[str] = None, client_id: Optional[str] = None, client_secret: Optional[str] = None, extra_params: Optional[Dict[str, Any]] = None, scope: Optional[List[str]] = None, response_type: str = 'code') None [源代码]¶
重定向用户以获取此服务的OAuth授权。
有些提供程序要求您在应用程序中注册重定向URL,而不是通过此方法传递。您应该调用此方法登录用户,然后调用
get_authenticated_user
在处理程序中为您的重定向URL完成授权过程。在 6.0 版更改: 这个
callback
移除了参数和返回的awaitable;这现在是一个普通的同步函数。
- coroutine oauth2_request(url: str, access_token: Optional[str] = None, post_args: Optional[Dict[str, Any]] = None, **args: Any) Any [源代码]¶
获取给定的URL身份验证OAuth2访问令牌。
如果请求是一个帖子,
post_args
应提供。查询字符串参数应作为关键字参数提供。示例用法:
..测试代码:
class MainHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin): @tornado.web.authenticated async def get(self): new_entry = await self.oauth2_request( "https://graph.facebook.com/me/feed", post_args={"message": "I am posting from my Tornado application!"}, access_token=self.current_user["access_token"]) if not new_entry: # Call failed; perhaps missing permission? self.authorize_redirect() return self.finish("Posted a message!")
4.3 新版功能.
- get_auth_http_client() tornado.httpclient.AsyncHTTPClient [源代码]¶
返回
AsyncHTTPClient
用于身份验证请求的实例。可以被子类重写以使用默认之外的HTTP客户端。
4.3 新版功能.
谷歌¶
- class tornado.auth.GoogleOAuth2Mixin[源代码]¶
使用OAuth2进行谷歌认证。
要使用,请在Google中注册应用程序,并将相关参数复制到应用程序设置中。
转到Google Dev控制台:http://console.developers.google.com
选择一个项目,或创建一个新项目。
在左侧的侧栏中,选择凭证。
单击创建凭据,然后单击OAuth客户端ID。
在应用程序类型下,选择Web应用程序。
将OAuth 2.0 Client命名为OAuth 2.0,然后单击Create。
将“客户端机密”和“客户端ID”复制到应用程序设置
{{"google_oauth": {{"key": CLIENT_ID, "secret": CLIENT_SECRET}}}}
3.2 新版功能.
- coroutine get_authenticated_user(redirect_uri: str, code: str) Dict[str, Any] [源代码]¶
处理Google用户的登录,返回访问令牌。
结果是一个包含
access_token
字段( [在其他中] (https://developers.google.com/identity/protocols/oauth2webserver handlingtheresponse))。不像其他get_authenticated_user
方法,此方法不会返回有关用户的任何其他信息。返回的访问令牌可用于OAuth2Mixin.oauth2_request
请求附加信息(可能来自https://www.googleapis.com/oauth2/v2/userinfo
)示例用法:
class GoogleOAuth2LoginHandler(tornado.web.RequestHandler, tornado.auth.GoogleOAuth2Mixin): async def get(self): if self.get_argument('code', False): access = await self.get_authenticated_user( redirect_uri='http://your.site.com/auth/google', code=self.get_argument('code')) user = await self.oauth2_request( "https://www.googleapis.com/oauth2/v1/userinfo", access_token=access["access_token"]) # Save the user and access token with # e.g. set_secure_cookie. else: self.authorize_redirect( redirect_uri='http://your.site.com/auth/google', client_id=self.settings['google_oauth']['key'], scope=['profile', 'email'], response_type='code', extra_params={'approval_prompt': 'auto'})
在 6.0 版更改: 这个
callback
参数已删除。请改用返回的等待对象。
脸谱网¶
- class tornado.auth.FacebookGraphMixin[源代码]¶
使用新的图形API和OAuth2进行Facebook身份验证。
- coroutine get_authenticated_user(redirect_uri: str, client_id: str, client_secret: str, code: str, extra_fields: Optional[Dict[str, Any]] = None) Optional[Dict[str, Any]] [源代码]¶
处理Facebook用户的登录,返回用户对象。
示例用法:
class FacebookGraphLoginHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin): async def get(self): if self.get_argument("code", False): user = await self.get_authenticated_user( redirect_uri='/auth/facebookgraph/', client_id=self.settings["facebook_api_key"], client_secret=self.settings["facebook_secret"], code=self.get_argument("code")) # Save the user with e.g. set_secure_cookie else: self.authorize_redirect( redirect_uri='/auth/facebookgraph/', client_id=self.settings["facebook_api_key"], extra_params={"scope": "read_stream,offline_access"})
此方法返回可能包含以下字段的字典:
access_token
, a string which may be passed tofacebook_request
session_expires
,一个整数,编码为一个字符串,表示访问令牌在秒内过期之前的时间。此字段的使用方式应为int(user['session_expires'])
;在Tornado的未来版本中,它将从字符串更改为整数。id
,name
,first_name
,last_name
,locale
,picture
,link
, plus any fields named in theextra_fields
argument. These fields are copied from the Facebook graph API user object
在 4.5 版更改: 这个
session_expires
更新字段以支持2017年3月对Facebook API所做的更改。在 6.0 版更改: 这个
callback
参数已删除。请改用返回的等待对象。
- coroutine facebook_request(path: str, access_token: Optional[str] = None, post_args: Optional[Dict[str, Any]] = None, **args: Any) Any [源代码]¶
获取给定的相对API路径,例如“/btaylor/picture”
如果请求是一个帖子,
post_args
应提供。查询字符串参数应作为关键字参数提供。有关Facebook图形API的介绍,请访问http://developers.facebook.com/docs/api。
许多方法都需要OAuth访问令牌,您可以通过
authorize_redirect
和get_authenticated_user
. 通过该过程返回的用户包括access_token
可用于通过此方法进行身份验证请求的属性。示例用法:
class MainHandler(tornado.web.RequestHandler, tornado.auth.FacebookGraphMixin): @tornado.web.authenticated async def get(self): new_entry = await self.facebook_request( "/me/feed", post_args={"message": "I am posting from my Tornado application!"}, access_token=self.current_user["access_token"]) if not new_entry: # Call failed; perhaps missing permission? self.authorize_redirect() return self.finish("Posted a message!")
给定路径相对于
self._FACEBOOK_BASE_URL
,默认为“https://graph.facebook.com”。这个方法是一个包装
OAuth2Mixin.oauth2_request
;唯一的区别是,此方法采用相对路径,而oauth2_request
获取完整的URL。在 3.1 版更改: 添加了覆盖功能
self._FACEBOOK_BASE_URL
.在 6.0 版更改: 这个
callback
参数已删除。请改用返回的等待对象。
推特¶
- class tornado.auth.TwitterMixin[源代码]¶
Twitter OAuth身份验证。
要使用Twitter进行认证,请在http://twitter.com/apps上的twitter注册您的应用程序。然后将您的消费者密钥和消费者机密复制到应用程序中
settings
twitter_consumer_key
和twitter_consumer_secret
. 在您注册为应用程序回调URL的URL的处理程序上使用此mixin。当您的应用程序设置好后,您可以像这样使用这个mixin来通过twitter验证用户身份并访问他们的流:
class TwitterLoginHandler(tornado.web.RequestHandler, tornado.auth.TwitterMixin): async def get(self): if self.get_argument("oauth_token", None): user = await self.get_authenticated_user() # Save the user using e.g. set_secure_cookie() else: await self.authorize_redirect()
返回的用户对象
get_authenticated_user
包括属性username
,name
,access_token
以及在https://dev.twitter.com/docs/api/1.1/get/users/show中描述的所有自定义twitter用户属性。- coroutine authenticate_redirect(callback_uri: Optional[str] = None) None [源代码]¶
就像
authorize_redirect
,但如果授权,则自动重定向。如果您使用Twitter进行单点登录,那么这通常是正确的界面。
在 3.1 版更改: 现在返回
Future
并接受可选回调,以便与gen.coroutine
.在 6.0 版更改: 这个
callback
参数已删除。请改用返回的等待对象。
- coroutine twitter_request(path: str, access_token: Dict[str, Any], post_args: Optional[Dict[str, Any]] = None, **args: Any) Any [源代码]¶
获取给定的API路径,例如,
statuses/user_timeline/btaylor
路径不应包含格式或API版本号。(我们自动使用JSON格式和API版本1)。
如果请求是一个帖子,
post_args
应提供。查询字符串参数应作为关键字参数提供。所有twitter方法都记录在http://dev.twitter.com上。/
许多方法都需要OAuth访问令牌,您可以通过
authorize_redirect
和get_authenticated_user
. 通过该进程返回的用户包含一个“access_token”属性,该属性可用于通过此方法发出经过身份验证的请求。示例用法:class MainHandler(tornado.web.RequestHandler, tornado.auth.TwitterMixin): @tornado.web.authenticated async def get(self): new_entry = await self.twitter_request( "/statuses/update", post_args={"status": "Testing Tornado Web Server"}, access_token=self.current_user["access_token"]) if not new_entry: # Call failed; perhaps missing permission? await self.authorize_redirect() return self.finish("Posted a message!")
在 6.0 版更改: 这个
callback
参数已删除。请改用返回的等待对象。