Using GitHub's API with Two-Factor Authentication (2FA) Enabled

When you enable 2FA in GitHub, this setting carries over to your usage of the API. github3.py provides a simple interface to manage 2FA.

First, you need to create a callback handler that will prompt the user for their token (which they will receive either by SMS or by checking a phone application).


In [1]:
def callback_handler():
    prompt_str = 'Please enter your 2FA token now: '
    try:
        token = raw_input(prompt_str)
    except NameError:
        token = input(prompt_str)
    return token

This handler will work on Python 2 and Python 3. (In Python 2, to prompt the user, you want to use raw_input but that was replaced in Python 3 with input.)

This will ask the user to type in their token and then return it to github3.py. If you're developing a GUI, you will want to write a different handler, but that is out of the scope of this example.

To use the handler above you can pass it to the github3.login function.


In [3]:
import github3

In [4]:
gh = github3.login('username', 'password', two_factor_callback=callback_handler)

The beauty of using the callback means that it is only used when necessary. If you have 2FA turned off, you'll never be prompted.

If you have 2FA enabled, then every call you make to the API will require you to provide a passcode. The tokens cannot be reliably cached by github3.py. To avoid this, the API documentation and github3.py suggest you create an API Token. You should decide which scopes you want the token to have before creating.


In [ ]:
authorization = github3.authorize('username', 'password', ['user'],
                                  two_factor_callback=callback_handler)
gh = github3.login(token=authorization.token)

The call to authorize will create an Authorization object which has a token. With the object you can pass the token to login and not have to worry about having to supply tokens generated by a mobile application or sent to your phone.