oauthenticator.auth0

Custom Authenticator to use Auth0 OAuth with JupyterHub

Derived using the Github and Google OAuthenticator implementations as examples.

The following environment variables may be used for configuration:

AUTH0_SUBDOMAIN - The subdomain for your Auth0 account OAUTH_CLIENT_ID - Your client id OAUTH_CLIENT_SECRET - Your client secret OAUTH_CALLBACK_URL - Your callback handler URL

Additionally, if you are concerned about your secrets being exposed by an env dump(I know I am!) you can set the client_secret, client_id and oauth_callback_url directly on the config for Auth0OAuthenticator.

One instance of this could be adding the following to your jupyterhub_config.py :

c.Auth0OAuthenticator.client_id = ‘YOUR_CLIENT_ID’ c.Auth0OAuthenticator.client_secret = ‘YOUR_CLIENT_SECRET’ c.Auth0OAuthenticator.oauth_callback_url = ‘YOUR_CALLBACK_URL’ c.Auth0OAuthenticator.scope = [‘openid’,’profile’,’email’]

If you are using the environment variable config, all you should need to do is define them in the environment then add the following line to jupyterhub_config.py :

c.JupyterHub.authenticator_class = ‘oauthenticator.auth0.Auth0OAuthenticator’

class oauthenticator.auth0.Auth0OAuthenticator(**kwargs)
admin_users c.Auth0OAuthenticator.admin_users = Set()

Set of users that will have admin rights on this JupyterHub.

Admin users have extra privileges:
  • Use the admin panel to see list of users logged in

  • Add / remove users in some authenticators

  • Restart / halt the hub

  • Start / stop users’ single-user servers

  • Can access each individual users’ single-user server (if configured)

Admin access should be treated the same way root access is.

Defaults to an empty set, in which case no user has admin access.

allowed_users c.Auth0OAuthenticator.allowed_users = Set()

Set of usernames that are allowed to log in.

Use this with supported authenticators to restrict which users can log in. This is an additional list that further restricts users, beyond whatever restrictions the authenticator has in place.

If empty, does not perform any additional restriction.

Changed in version 1.2: Authenticator.whitelist renamed to allowed_users

auth_refresh_age c.Auth0OAuthenticator.auth_refresh_age = Int(300)

The max age (in seconds) of authentication info before forcing a refresh of user auth info.

Refreshing auth info allows, e.g. requesting/re-validating auth tokens.

See refresh_user() for what happens when user auth info is refreshed (nothing by default).

authorize_url c.Auth0OAuthenticator.authorize_url = Unicode('')

The authenticate url for initiating oauth

auto_login c.Auth0OAuthenticator.auto_login = Bool(False)

Automatically begin the login process

rather than starting with a “Login with…” link at /hub/login

To work, .login_url() must give a URL other than the default /hub/login, such as an oauth handler or another automatic login handler, registered with .get_handlers().

New in version 0.8.

blocked_users c.Auth0OAuthenticator.blocked_users = Set()

Set of usernames that are not allowed to log in.

Use this with supported authenticators to restrict which users can not log in. This is an additional block list that further restricts users, beyond whatever restrictions the authenticator has in place.

If empty, does not perform any additional restriction.

Changed in version 1.2: Authenticator.blacklist renamed to blocked_users

delete_invalid_users c.Auth0OAuthenticator.delete_invalid_users = Bool(False)

Delete any users from the database that do not pass validation

When JupyterHub starts, .add_user will be called on each user in the database to verify that all users are still valid.

If delete_invalid_users is True, any users that do not pass validation will be deleted from the database. Use this if users might be deleted from an external system, such as local user accounts.

If False (default), invalid users remain in the Hub’s database and a warning will be issued. This is the default to avoid data loss due to config changes.

enable_auth_state c.Auth0OAuthenticator.enable_auth_state = Bool(False)

Enable persisting auth_state (if available).

auth_state will be encrypted and stored in the Hub’s database. This can include things like authentication tokens, etc. to be passed to Spawners as environment variables.

Encrypting auth_state requires the cryptography package.

Additionally, the JUPYTERHUB_CRYPT_KEY environment variable must contain one (or more, separated by ;) 32B encryption keys. These can be either base64 or hex-encoded.

If encryption is unavailable, auth_state cannot be persisted.

New in JupyterHub 0.8

extra_authorize_params c.Auth0OAuthenticator.extra_authorize_params = Dict()

Extra GET params to send along with the initial OAuth request to the OAuth provider.

logout_redirect_url c.Auth0OAuthenticator.logout_redirect_url = Unicode('')

URL for logging out of Auth0

oauth_callback_url c.Auth0OAuthenticator.oauth_callback_url = Unicode('')

Callback URL to use. Typically https://{host}/hub/oauth_callback

post_auth_hook c.Auth0OAuthenticator.post_auth_hook = Any(None)

An optional hook function that you can implement to do some bootstrapping work during authentication. For example, loading user account details from an external system.

This function is called after the user has passed all authentication checks and is ready to successfully authenticate. This function must return the authentication dict reguardless of changes to it.

This maybe a coroutine.

Example:

import os, pwd
def my_hook(authenticator, handler, authentication):
    user_data = pwd.getpwnam(authentication['name'])
    spawn_data = {
        'pw_data': user_data
        'gid_list': os.getgrouplist(authentication['name'], user_data.pw_gid)
    }

    if authentication['auth_state'] is None:
        authentication['auth_state'] = {}
    authentication['auth_state']['spawn_data'] = spawn_data

    return authentication

c.Authenticator.post_auth_hook = my_hook
refresh_pre_spawn c.Auth0OAuthenticator.refresh_pre_spawn = Bool(False)

Force refresh of auth prior to spawn.

This forces refresh_user() to be called prior to launching a server, to ensure that auth state is up-to-date.

This can be important when e.g. auth tokens that may have expired are passed to the spawner via environment variables from auth_state.

If refresh_user cannot refresh the user auth data, launch will fail until the user logs in again.

scope c.Auth0OAuthenticator.scope = List()

The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo.

token_url c.Auth0OAuthenticator.token_url = Unicode('')

The url retrieving an access token at the completion of oauth

userdata_url c.Auth0OAuthenticator.userdata_url = Unicode('')

The url for retrieving user data with a completed access token

username_key c.Auth0OAuthenticator.username_key = Unicode('email')

Userdata username key from returned json with user data login information

username_map c.Auth0OAuthenticator.username_map = Dict()

Dictionary mapping authenticator usernames to JupyterHub users.

Primarily used to normalize OAuth user names to local users.

username_pattern c.Auth0OAuthenticator.username_pattern = Unicode('')

Regular expression pattern that all valid usernames must match.

If a username does not match the pattern specified here, authentication will not be attempted.

If not set, allow any username.

whitelist c.Auth0OAuthenticator.whitelist = Set()

Deprecated, use Authenticator.allowed_users

class oauthenticator.auth0.LocalAuth0OAuthenticator(**kwargs)

A version that mixes in local system user creation

add_user_cmd c.LocalAuth0OAuthenticator.add_user_cmd = Command()

The command to use for creating users as a list of strings

For each element in the list, the string USERNAME will be replaced with the user’s username. The username will also be appended as the final argument.

For Linux, the default value is:

[‘adduser’, ‘-q’, ‘–gecos’, ‘””’, ‘–disabled-password’]

To specify a custom home directory, set this to:

[‘adduser’, ‘-q’, ‘–gecos’, ‘””’, ‘–home’, ‘/customhome/USERNAME’, ‘–disabled-password’]

This will run the command:

adduser -q –gecos “” –home /customhome/river –disabled-password river

when the user ‘river’ is created.

admin_users c.LocalAuth0OAuthenticator.admin_users = Set()

Set of users that will have admin rights on this JupyterHub.

Admin users have extra privileges:
  • Use the admin panel to see list of users logged in

  • Add / remove users in some authenticators

  • Restart / halt the hub

  • Start / stop users’ single-user servers

  • Can access each individual users’ single-user server (if configured)

Admin access should be treated the same way root access is.

Defaults to an empty set, in which case no user has admin access.

allowed_groups c.LocalAuth0OAuthenticator.allowed_groups = Set()

Allow login from all users in these UNIX groups.

If set, allowed username set is ignored.

allowed_users c.LocalAuth0OAuthenticator.allowed_users = Set()

Set of usernames that are allowed to log in.

Use this with supported authenticators to restrict which users can log in. This is an additional list that further restricts users, beyond whatever restrictions the authenticator has in place.

If empty, does not perform any additional restriction.

Changed in version 1.2: Authenticator.whitelist renamed to allowed_users

auth_refresh_age c.LocalAuth0OAuthenticator.auth_refresh_age = Int(300)

The max age (in seconds) of authentication info before forcing a refresh of user auth info.

Refreshing auth info allows, e.g. requesting/re-validating auth tokens.

See refresh_user() for what happens when user auth info is refreshed (nothing by default).

authorize_url c.LocalAuth0OAuthenticator.authorize_url = Unicode('')

The authenticate url for initiating oauth

auto_login c.LocalAuth0OAuthenticator.auto_login = Bool(False)

Automatically begin the login process

rather than starting with a “Login with…” link at /hub/login

To work, .login_url() must give a URL other than the default /hub/login, such as an oauth handler or another automatic login handler, registered with .get_handlers().

New in version 0.8.

blocked_users c.LocalAuth0OAuthenticator.blocked_users = Set()

Set of usernames that are not allowed to log in.

Use this with supported authenticators to restrict which users can not log in. This is an additional block list that further restricts users, beyond whatever restrictions the authenticator has in place.

If empty, does not perform any additional restriction.

Changed in version 1.2: Authenticator.blacklist renamed to blocked_users

create_system_users c.LocalAuth0OAuthenticator.create_system_users = Bool(False)

If set to True, will attempt to create local system users if they do not exist already.

Supports Linux and BSD variants only.

delete_invalid_users c.LocalAuth0OAuthenticator.delete_invalid_users = Bool(False)

Delete any users from the database that do not pass validation

When JupyterHub starts, .add_user will be called on each user in the database to verify that all users are still valid.

If delete_invalid_users is True, any users that do not pass validation will be deleted from the database. Use this if users might be deleted from an external system, such as local user accounts.

If False (default), invalid users remain in the Hub’s database and a warning will be issued. This is the default to avoid data loss due to config changes.

enable_auth_state c.LocalAuth0OAuthenticator.enable_auth_state = Bool(False)

Enable persisting auth_state (if available).

auth_state will be encrypted and stored in the Hub’s database. This can include things like authentication tokens, etc. to be passed to Spawners as environment variables.

Encrypting auth_state requires the cryptography package.

Additionally, the JUPYTERHUB_CRYPT_KEY environment variable must contain one (or more, separated by ;) 32B encryption keys. These can be either base64 or hex-encoded.

If encryption is unavailable, auth_state cannot be persisted.

New in JupyterHub 0.8

extra_authorize_params c.LocalAuth0OAuthenticator.extra_authorize_params = Dict()

Extra GET params to send along with the initial OAuth request to the OAuth provider.

group_whitelist c.LocalAuth0OAuthenticator.group_whitelist = Set()

DEPRECATED: use allowed_groups

logout_redirect_url c.LocalAuth0OAuthenticator.logout_redirect_url = Unicode('')

URL for logging out of Auth0

oauth_callback_url c.LocalAuth0OAuthenticator.oauth_callback_url = Unicode('')

Callback URL to use. Typically https://{host}/hub/oauth_callback

post_auth_hook c.LocalAuth0OAuthenticator.post_auth_hook = Any(None)

An optional hook function that you can implement to do some bootstrapping work during authentication. For example, loading user account details from an external system.

This function is called after the user has passed all authentication checks and is ready to successfully authenticate. This function must return the authentication dict reguardless of changes to it.

This maybe a coroutine.

Example:

import os, pwd
def my_hook(authenticator, handler, authentication):
    user_data = pwd.getpwnam(authentication['name'])
    spawn_data = {
        'pw_data': user_data
        'gid_list': os.getgrouplist(authentication['name'], user_data.pw_gid)
    }

    if authentication['auth_state'] is None:
        authentication['auth_state'] = {}
    authentication['auth_state']['spawn_data'] = spawn_data

    return authentication

c.Authenticator.post_auth_hook = my_hook
refresh_pre_spawn c.LocalAuth0OAuthenticator.refresh_pre_spawn = Bool(False)

Force refresh of auth prior to spawn.

This forces refresh_user() to be called prior to launching a server, to ensure that auth state is up-to-date.

This can be important when e.g. auth tokens that may have expired are passed to the spawner via environment variables from auth_state.

If refresh_user cannot refresh the user auth data, launch will fail until the user logs in again.

scope c.LocalAuth0OAuthenticator.scope = List()

The OAuth scopes to request. See the OAuth documentation of your OAuth provider for options. For GitHub in particular, you can see github_scopes.md in this repo.

token_url c.LocalAuth0OAuthenticator.token_url = Unicode('')

The url retrieving an access token at the completion of oauth

uids c.LocalAuth0OAuthenticator.uids = Dict()

Dictionary of uids to use at user creation time. This helps ensure that users created from the database get the same uid each time they are created in temporary deployments or containers.

userdata_url c.LocalAuth0OAuthenticator.userdata_url = Unicode('')

The url for retrieving user data with a completed access token

username_key c.LocalAuth0OAuthenticator.username_key = Unicode('email')

Userdata username key from returned json with user data login information

username_map c.LocalAuth0OAuthenticator.username_map = Dict()

Dictionary mapping authenticator usernames to JupyterHub users.

Primarily used to normalize OAuth user names to local users.

username_pattern c.LocalAuth0OAuthenticator.username_pattern = Unicode('')

Regular expression pattern that all valid usernames must match.

If a username does not match the pattern specified here, authentication will not be attempted.

If not set, allow any username.

whitelist c.LocalAuth0OAuthenticator.whitelist = Set()

Deprecated, use Authenticator.allowed_users