Authomatic: python library for authentication and authorization

    imageAlmost any web application provides the ability to authorize a user using a user account in any of the well-known social services.

    The authentication magic happens strictly according to the OAuth 1.0a and OAuth 2.0 protocols and greatly simplifies the life of both the owner of the web application and the user himself.

    It remains a mere trifle to implement the desired protocol for a specific web application. Registering and logging into the TheOnlyPage web service using Facebook , Google , LinkedIn and Microsoft Live accounts works thanks to the python Authomatic library .

    According to Authomatic documentation possesses the following remarkable features:

    • Weak connectedness.
    • Compact but powerful interface
    • The only, and optional dependency: python-openid library
    • CSRF protection
    • Thanks to the adapters, there is no binding to a specific framework. Out of the box, Django , Flask, and Webapp2 are supported .
    • Ability to include new emerging authorization and authentication protocols
    • Requests to the provider program interface (API) - nowhere is easier.
    • Asynchronous Request Support
    • As a bonus, the javascript library
    • Out of the box support:
      • OAuth 1.0a providers: Bitbucket, Flickr, Meetup, Plurk, Twitter, Tumblr, UbuntuOne, Vimeo, Xero, Xing and Yahoo
      • OAuth 2.0 providers: Behance, Bitly, Cosm, DeviantART, Facebook, Foursquare, GitHub, Google, LinkedIn, PayPal, Reddit, Viadeo, VK, WindowsLive, Yammer and Yandex.
      • python-openid and OpenID based on Google App Engine

    In addition to everything, it is noted that the library is at a very early stage of creation , and is practically not tested .

    Despite such a self-critical statement, if you look at the demo page , you can make sure that the library provides trouble-free operation with all kinds of providers OAuth 1.0a and OAuth 2.0 .

    High-quality documentation provides enough information to use the library in conjunction with the frameworks: Django , Flask , Pyramid and Webapp2 .

    We will illustrate work with Authomaticreal life example. In order to register / enter TheOnlyPage web service through your Facebook , Google , LinkedIn and Microsoft Live account , just click on the corresponding button on the service login page:


    The authorization process is implemented using the Authomatic library . At the same time, TheOnlyPage runs on the Flask framework . In order to use the Authomatic library in conjunction with the Flask framework , provided that the library is already present in the workspace, you need:

    1. Register your application with each of the OAuth providers.
    2. Add OAuth provider settings to the configuration file.
    3. Initiate the base object with the authomaticparameters stored in the configuration file.
    4. Create a view that will fulfill the request to the provider and get the result from it.

    Let's do these 4 simple steps:

    Application Registration

    Each provider has its own registration features.

    Facebook app registration addresses :

    for Google:

    for LinkedIn:

    for Microsoft Live: / create

    Some parameters that need to be specified may differ from one provider to another, but among the other parameters they must be present:

    1. addresses of our service from which a redirect with a request to the provider is allowed
    2. the address at which the provider returns the user to our service after granting access
    3. address at which the provider returns the user to our service in case of refusal to provide access

    If you use the Authomatic library in the 1st and 2nd cases, it is convenient to specify the same address, so for the respective providers we will use the addresses:


    Also on the registration page of the application from the provider, we need to get the user code and secret key , in terms of various providers they are respectively called:
    user codeThe secret key
    FacebookApp idApp secret
    GoogleClient IDClient secret
    LinkedInAPI KeySecret key
    Microsoft liveClient IDClient secret

    In addition, in the registration section of the application with the provider, we must find out under what name the data we need appears. For example, the user's email address is indicated:

    for Facebook: email

    for Google: email

    for LinkedIn: r_emailaddress

    for Microsoft Live: wl.emails

    After the application is registered with all providers, the redirect addresses are indicated, the user code and secret key are received, it is clear how data is referred to in relation to each provider; you can proceed to configure the configuration file.

    Defining OAuth Providers Configuration

    In the standard configuration file of the flask application, you need to add a dictionary containing the parameters of all providers:

      'facebook': {          
        'class_': oauth2.Facebook,
        'consumer_key': 123456789012345',
        'consumer_secret': ' edcba987654321012345679abcdedcab',
        'scope': ['email',],
        'google': {
        'class_': oauth2.Google,
        'consumer_key': '',
        'consumer_secret': ' ABcDEFgiJKLmNOPQRStUVWxyz ',
        'scope': ['email',],
      'linkedin': {
        'class_': oauth2.LinkedIn,
        'consumer_key': ' ABC123df45GIJ6h ',
        'consumer_secret': ‘zyx987vutSRQponM ',
        'scope': ['r_emailaddress',],
        'microsoft': {        
        'class_': oauth2.WindowsLive,
        'consumer_key': '0000000012345A67',
        'consumer_secret': ' ABcDe123fgHIJK45LmnO6789PQrS0tUVXyz ',
        'scope': ['wl.emails',],

    As we see, each provider is assigned a dictionary with the following attributes:

    class_- a class that is part of the Authomatic library that corresponds to the next provider;

    consumer_key- user code of the next provider;

    consumer_secret- secret key of the next provider;

    scope- a list of data that is supposed to be requested from the next provider.

    Presets made.

    Initiate an authomatic base object

    It happens very simply, with the specified configuration data and the secret line:

    from authomatic import Authomatic
    from config import OAUTH_CONFIG 
    authomatic = Authomatic(OAUTH_CONFIG, ‘very secret string', report_errors=False)

    Create view

    It remains to create a view that:
    • corresponds to the Internet address from which the data request is redirected to the provider and data is received from the provider;
    • Obtains the user's email address from the oauth provider;
    • and if this user is registered in the system - gives him access.

    import re
    from authomatic.adapters import WerkzeugAdapter
    from flask import redirect, make_response
    from flask.ext.login import login_user
    from models import User
    from app import app
    EMAIL_REGEX = re.compile(r'[^@]+@[^@]+\.[^@]+')
    def login(provider_name):
      # для работый с адаптером WerkzeugAdapter понадобится объект response
      response = make_response()
      # перехватываем ошибки которые могут возникнуть при работе с oauth2 провайдером
        # если result = None значит процедура логина находится в процессе выполнения
        result = authomatic.login( WerkzeugAdapter( request, response ), provider_name )
        if result:
        # если получен результат oauth-логина
          if result.user:
          # и если имеется информация о пользователе 
            # получаем информацию о пользователе
            # получаем email
            email =
            if email and EMAIL_REGEX.match(email):
            # если указан правильный адрес
              # находим соответствующего пользователя
              user = User.query.filter_by( email = email ).first()
              if user:
              # если пользователь зарегистрирован с системе
                # осуществляем вход в систему
                login_user( user )
                # делаем редирект на главную страницу сервиса
                return redirect( url_for( 'index' ) )
    # здесь отрабатываем все варианты отказа в регистрации
    # ...
    # ...
        # если результат oauth-логина еще не получен (result=None)
        # возвращаем объект response
         return response

    The bulk of the interaction with the oauth provider comes down to one line:

    result = authomatic.login( WerkzeugAdapter( request, response ), provider_name )

    upon initial visit to the address: authomatic.loginredirects to the specified provider and transfers the necessary parameters;

    then the provider does a reverse redirect to the same address and authomatic.loginreceives the required data from the provider.

    As you can see, it’s not difficult at all. The main part of the time is not programming, but registering your application with each of the providers used.

    Also popular now: