tornado.auth — Third-party login with OpenID and OAuth

This module contains implementations of various third-party authentication schemes.

All the classes in this file are class mixins designed to be used with the tornado.web.RequestHandler class. They are used in two ways:

  • On a login handler, use methods such as authenticate_redirect(), authorize_redirect(), and get_authenticated_user() to establish the user’s identity and store authentication tokens to your database and/or cookies.

  • In non-login handlers, use methods such as facebook_request() or twitter_request() to use the authentication tokens to make requests to the respective services.

They all take slightly different arguments due to the fact all these services implement authentication and authorization slightly differently. See the individual service classes below for complete documentation.

Example usage for 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:
            await 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'})

Common protocols

These classes implement the OpenID and OAuth standards. They will generally need to be subclassed to use them with any particular site. The degree of customization required will vary, but in most cases overriding the class attributes (which are named beginning with underscores for historical reasons) should be sufficient.

class tornado.auth.OpenIdMixin[source]

Abstract implementation of OpenID and Attribute Exchange.

Class attributes:

  • _OPENID_ENDPOINT: the identity provider’s URI.

authenticate_redirect(callback_uri: Optional[str] = None, ax_attrs: List[str] = ['name', 'email', 'language', 'username']) → None[source]

Redirects to the authentication URL for this service.

After authentication, the service will redirect back to the given callback URI with additional parameters including openid.mode.

We request the given attributes for the authenticated user by default (name, email, language, and username). If you don’t need all those attributes for your app, you can request fewer with the ax_attrs keyword argument.

Changed in version 6.0: The callback argument was removed and this method no longer returns an awaitable object. It is now an ordinary synchronous function.

get_auth_http_client() → tornado.httpclient.AsyncHTTPClient[source]

Returns the AsyncHTTPClient instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than the default.

class tornado.auth.OAuthMixin[source]

Abstract implementation of OAuth 1.0 and 1.0a.

See TwitterMixin below for an example implementation.

Class attributes:

  • _OAUTH_AUTHORIZE_URL: The service’s OAuth authorization url.

  • _OAUTH_ACCESS_TOKEN_URL: The service’s OAuth access token url.

  • _OAUTH_VERSION: May be either “1.0” or “1.0a”.

  • _OAUTH_NO_CALLBACKS: Set this to True if the service requires advance registration of callbacks.

Subclasses must also override the _oauth_get_user_future and _oauth_consumer_token methods.

async authorize_redirect(callback_uri: Optional[str] = None, extra_params: Optional[Dict[str, Any]] = None, http_client: Optional[tornado.httpclient.AsyncHTTPClient] = None) → None[source]

Redirects the user to obtain OAuth authorization for this service.

The callback_uri may be omitted if you have previously registered a callback URI with the third-party service. For some services, you must use a previously-registered callback URI and cannot specify a callback via this method.

This method sets a cookie called _oauth_request_token which is subsequently used (and cleared) in get_authenticated_user for security purposes.

This method is asynchronous and must be called with await or yield (This is different from other auth*_redirect methods defined in this module). It calls RequestHandler.finish for you so you should not write any other response after it returns.

Changed in version 3.1: Now returns a Future and takes an optional callback, for compatibility with gen.coroutine.

Changed in version 6.0: The callback argument was removed. Use the returned awaitable object instead.

async get_authenticated_user(http_client: Optional[tornado.httpclient.AsyncHTTPClient] = None) → Dict[str, Any][source]

Gets the OAuth authorized user and access token.

This method should be called from the handler for your OAuth callback URL to complete the registration process. We run the callback with the authenticated user dictionary. This dictionary will contain an access_key which can be used to make authorized requests to this service on behalf of the user. The dictionary will also contain other fields such as name, depending on the service used.

Changed in version 6.0: The callback argument was removed. Use the returned awaitable object instead.

_oauth_consumer_token() → Dict[str, Any][source]

Subclasses must override this to return their OAuth consumer keys.

The return value should be a dict with keys key and secret.

async _oauth_get_user_future(access_token: Dict[str, Any]) → Dict[str, Any][source]

Subclasses must override this to get basic information about the user.

Should be a coroutine whose result is a dictionary containing information about the user, which may have been retrieved by using access_token to make a request to the service.

The access token will be added to the returned dictionary to make the result of get_authenticated_user.

Changed in version 5.1: Subclasses may also define this method with async def.

Changed in version 6.0: A synchronous fallback to _oauth_get_user was removed.

get_auth_http_client() → tornado.httpclient.AsyncHTTPClient[source]

Returns the AsyncHTTPClient instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than the default.

class tornado.auth.OAuth2Mixin[source]

Abstract implementation of OAuth 2.0.

See FacebookGraphMixin or GoogleOAuth2Mixin below for example implementations.

Class attributes:

  • _OAUTH_AUTHORIZE_URL: The service’s authorization url.

  • _OAUTH_ACCESS_TOKEN_URL: The service’s access token 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[str] = None, response_type: str = 'code') → None[source]

Redirects the user to obtain OAuth authorization for this service.

Some providers require that you register a redirect URL with your application instead of passing one via this method. You should call this method to log the user in, and then call get_authenticated_user in the handler for your redirect URL to complete the authorization process.

Changed in version 6.0: The callback argument and returned awaitable were removed; this is now an ordinary synchronous function.

get_auth_http_client() → tornado.httpclient.AsyncHTTPClient[source]

Returns the AsyncHTTPClient instance to be used for auth requests.

May be overridden by subclasses to use an HTTP client other than the default.

New in version 4.3.

Google

class tornado.auth.GoogleOAuth2Mixin[source]

Google authentication using OAuth2.

In order to use, register your application with Google and copy the relevant parameters to your application settings.

  • Go to the Google Dev Console at http://console.developers.google.com

  • Select a project, or create a new one.

  • In the sidebar on the left, select APIs & Auth.

  • In the list of APIs, find the Google+ API service and set it to ON.

  • In the sidebar on the left, select Credentials.

  • In the OAuth section of the page, select Create New Client ID.

  • Set the Redirect URI to point to your auth handler

  • Copy the “Client secret” and “Client ID” to the application settings as {"google_oauth": {"key": CLIENT_ID, "secret": CLIENT_SECRET}}

New in version 3.2.

Facebook

class tornado.auth.FacebookGraphMixin[source]

Facebook authentication using the new Graph API and OAuth2.

Twitter

class tornado.auth.TwitterMixin[source]

Twitter OAuth authentication.

To authenticate with Twitter, register your application with Twitter at http://twitter.com/apps. Then copy your Consumer Key and Consumer Secret to the application settings twitter_consumer_key and twitter_consumer_secret. Use this mixin on the handler for the URL you registered as your application’s callback URL.

When your application is set up, you can use this mixin like this to authenticate the user with Twitter and get access to their stream:

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()

The user object returned by get_authenticated_user includes the attributes username, name, access_token, and all of the custom Twitter user attributes described at https://dev.twitter.com/docs/api/1.1/get/users/show