Skip to main content
`Ctrl`+`K`

# jupyter_server.auth package

## Submodules

An Authorizer for use in the Jupyter server.

The default authorizer (AllowAllAuthorizer) allows all authenticated requests

Added in version 2.0.

class jupyter_server.auth.authorizer.AllowAllAuthorizer(**kwargs)

  Bases: `Authorizer`

  A no-op implementation of the Authorizer

  This authorizer allows all authenticated requests.

  Added in version 2.0.

  is_authorized(handler, user, action, resource)

    This method always returns True.

    All authenticated users are allowed to do anything in the Jupyter Server.

    Return type:

      `bool`

class jupyter_server.auth.authorizer.Authorizer(**kwargs)

  Bases: `LoggingConfigurable`

  Base class for authorizing access to resources in the Jupyter Server.

  All authorizers used in Jupyter Server should inherit from this base class and, at the very minimum, implement an `is_authorized` method with the same signature as in this base class.

  The `is_authorized` method is called by the `@authorized` decorator in JupyterHandler. If it returns True, the incoming request to the server is accepted; if it returns False, the server returns a 403 (Forbidden) error code.

  The authorization check will only be applied to requests that have already been authenticated.

  Added in version 2.0.

  identity_provider

    A trait whose value must be an instance of a specified class.

    The value can also be an instance of a subclass of the specified class.

    Subclasses can declare default classes by overriding the klass attribute

  is_authorized(handler, user, action, resource)

    A method to determine if `user` is authorized to perform `action` (read, write, or execute) on the `resource` type.

    Parameters:

      - user (`User`) – An object representing the authenticated user, as returned by `jupyter_server.auth.IdentityProvider.get_user()`.

      - action (`str`) – the category of action for the current request: read, write, or execute.

      - resource (`str`) – the type of resource (i.e. contents, kernels, files, etc.) the user is requesting.

    Returns:

      True if user authorized to make request; False, otherwise

    Return type:

      `Awaitable`[`bool`] | `bool`

Decorator for layering authorization into JupyterHandlers.

jupyter_server.auth.decorator.allow_unauthenticated(method)

  A decorator for tornado.web.RequestHandler methods that allows any user to make the following request.

  Selectively disables the ‘authentication’ layer of REST API which is active when `ServerApp.allow_unauthenticated_access = False`.

  To be used exclusively on endpoints which may be considered public, for example the login page handler.

  Added in version 2.13.

  Parameters:

    method (`TypeVar`(`FuncT`, bound= `Callable`[`...`, `Any`])) – the endpoint method to remove authentication from.

  Return type:

    `TypeVar`(`FuncT`, bound= `Callable`[`...`, `Any`])

jupyter_server.auth.decorator.authorized(action=None, resource=None, message=None)

  A decorator for tornado.web.RequestHandler methods that verifies whether the current user is authorized to make the following request.

  Helpful for adding an ‘authorization’ layer to a REST API.

  Added in version 2.0.

  Parameters:

    - action (`str` | `TypeVar`(`FuncT`, bound= `Callable`[`...`, `Any`]) | `None`) – the type of permission or action to check.

    - resource (`str` | `None`) – the name of the resource the action is being authorized to access.

    - message (`str` | `None`) – a message for the unauthorized action.

  Return type:

    `TypeVar`(`FuncT`, bound= `Callable`[`...`, `Any`])

jupyter_server.auth.decorator.ws_authenticated(method)

  A decorator for websockets derived from `WebSocketHandler` that authenticates user before allowing to proceed.

  Differently from tornado.web.authenticated, does not redirect to the login page, which would be meaningless for websockets.

  Added in version 2.13.

  Parameters:

    method (`TypeVar`(`FuncT`, bound= `Callable`[`...`, `Any`])) – the endpoint method to add authentication for.

  Return type:

    `TypeVar`(`FuncT`, bound= `Callable`[`...`, `Any`])

Identity Provider interface

This defines the _authentication_ layer of Jupyter Server, to be used in combination with Authorizer for _authorization_.

Added in version 2.0.

class jupyter_server.auth.identity.IdentityProvider(**kwargs)

  Bases: `LoggingConfigurable`

  Interface for providing identity management and authentication.

  Two principle methods:

  - `get_user()` returns a `User` object for successful authentication, or None for no-identity-found.

  - `identity_model()` turns a `User` into a JSONable dict. The default is to use `dataclasses.asdict()`, and usually shouldn’t need override.

  Additional methods can customize authentication.

  Added in version 2.0.

  property auth_enabled

    Is authentication enabled?

    Should always be True, but may be False in rare, insecure cases where requests with no auth are allowed.

    Previously: LoginHandler.get_login_available

  auth_header_pat = re.compile('(token|bearer)\\s+(.+)', re.IGNORECASE)
  check_update(user_data)

    Raises if some fields to update are not updatable.

    Return type:

      `None`

  clear_login_cookie(handler)

    Clear the login cookie, effectively logging out the session.

    Return type:

      `None`

  cookie_name: str | Unicode[str, str | bytes]

    username-${Host}.

    Type:

      Name of the cookie to set for persisting login. Default

  cookie_options

    Extra keyword arguments to pass to `set_secure_cookie`. See tornado’s set_secure_cookie docs for details.

  cookie_secret_hook(h)

    Update cookie secret input

    Subclasses may call `h.update()` with any credentials that, when changed, should invalidate existing cookies, such as a password.

    The updated hashlib object should be returned.

    Return type:

      `HMAC`

  generate_anonymous_user(handler)

    Generate a random anonymous user.

    For use when a single shared token is used, but does not identify a user.

    Return type:

      `User`

  get_cookie_name(handler)

    Return the login cookie name

    Uses IdentityProvider.cookie_name, if defined. Default is to generate a string taking host into account to avoid collisions for multiple servers on one hostname with different ports.

    Return type:

      `str`

  get_handlers()

    Return list of additional handlers for this identity provider

    For example, an OAuth callback handler.

    Return type:

      `list`[`tuple`[`str`, `object`]]

  get_secure_cookie_kwargs

    Extra keyword arguments to pass to `get_secure_cookie`. See tornado’s get_secure_cookie docs for details.

  get_token(handler)

    Get the user token from a request

    Default:

    - in URL parameters: ?token=<token>

    - in header: Authorization: token <token>

    Return type:

      `str` | `None`

  get_user(handler)

    Get the authenticated user for a request

    Must return a `jupyter_server.auth.User`, though it may be a subclass.

    Return None if the request is not authenticated.

    _may_ be a coroutine

    Return type:

      `User` | `None` | `Awaitable`[`User` | `None`]

  get_user_cookie(handler)

    Get user from a cookie

    Calls user_from_cookie to deserialize cookie value

    Return type:

      `User` | `None` | `Awaitable`[`User` | `None`]

  async get_user_token(handler)

    Identify the user based on a token in the URL or Authorization header

    Returns: - uuid if authenticated - None if not

    Return type:

      `User` | `None`

  identity_model(user)

    Return a User as an Identity model

    Return type:

      `dict`[`str`, `Any`]

  is_token_authenticated(handler)

    Returns True if handler has been token authenticated. Otherwise, False.

    Login with a token is used to signal certain things, such as:

    - permit access to REST API

    - xsrf protection

    - skip origin-checks for scripts

    Return type:

      `bool`

  property login_available

    Whether a LoginHandler is needed - and therefore whether the login page should be displayed.

  login_handler_class

    The login handler class to use, if any.

  property logout_available

    Whether a LogoutHandler is needed.

  logout_handler_class

    The logout handler class to use.

  need_token: bool | Bool[bool, bool | int]

    A boolean (True, False) trait.

  persist_user_model(handler)

    Persist the user model (i.e. a cookie).

    Return type:

      `None`

  process_login_form(handler)

    Process login form data

    Return authenticated User if successful, None if not.

    Return type:

      `User` | `None`

  secure_cookie: bool | Bool[bool | None, bool | int | None]

    Specify whether login cookie should have the `secure` property (HTTPS-only).Only needed when protocol-detection gives the wrong answer due to proxies.

  set_login_cookie(handler, user)

    Call this on handlers to set the login cookie for success

    Return type:

      `None`

  should_check_origin(handler)

    Should the Handler check for CORS origin validation?

    Origin check should be skipped for token-authenticated requests.

    Returns: - True, if Handler must check for valid CORS origin. - False, if Handler should skip origin check since requests are token-authenticated.

    Return type:

      `bool`

  token: str | Unicode[str, str | bytes]

    Token used for authenticating first-time connections to the server.

    The token can be read from the file referenced by JUPYTER_TOKEN_FILE or set directly with the JUPYTER_TOKEN environment variable.

    When no password is enabled, the default is to generate a new, random token.

    Setting to an empty string disables authentication altogether, which is NOT RECOMMENDED.

    Prior to 2.0: configured as ServerApp.token

  token_generated = False
  updatable_fields

    List of fields in the User model that can be updated.

  update_user(handler, user_data)

    Update user information and persist the user model.

    Return type:

      `User`

  update_user_model(current_user, user_data)

    Update user information.

    Return type:

      `User`

  user_from_cookie(cookie_value)

    Inverse of user_to_cookie

    Return type:

      `User` | `None`

  user_to_cookie(user)

    Serialize a user to a string for storage in a cookie

    If overriding in a subclass, make sure to define user_from_cookie as well.

    Default is just the user’s username.

    Return type:

      `str`

  validate_security(app, ssl_options=None)

    Check the application’s security.

    Show messages, or abort if necessary, based on the security configuration.

    Return type:

      `None`

class jupyter_server.auth.identity.LegacyIdentityProvider(**kwargs)

  Bases: `PasswordIdentityProvider`

  Legacy IdentityProvider for use with custom LoginHandlers

  Login configuration has moved from LoginHandler to IdentityProvider in Jupyter Server 2.0.

  property auth_enabled

    Return whether any auth is enabled

  get_user(handler)

    Get the user.

    Return type:

      `User` | `None`

  is_token_authenticated(handler)

    Whether we are token authenticated.

    Return type:

      `bool`

  property login_available: bool

    Whether a LoginHandler is needed - and therefore whether the login page should be displayed.

  settings

    An instance of a Python dict.

    One or more traits can be passed to the constructor to validate the keys and/or values of the dict. If you need more detailed validation, you may use a custom validator method.

    Changed in version 5.0: Added key_trait for validating dict keys.

    Changed in version 5.0: Deprecated ambiguous `trait`, `traits` args in favor of `value_trait`, `per_key_traits`.

  should_check_origin(handler)

    Whether we should check origin.

    Return type:

      `bool`

  validate_security(app, ssl_options=None)

    Validate security.

    Return type:

      `None`

class jupyter_server.auth.identity.PasswordIdentityProvider(**kwargs)

  Bases: `IdentityProvider`

  A password identity provider.

  allow_password_change

    Allow password to be changed at login for the Jupyter server.

    While logging in with a token, the Jupyter server UI will give the opportunity to the user to enter a new password at the same time that will replace the token login mechanism.

    This can be set to False to prevent changing password from the UI/API.

  property auth_enabled: bool

    Return whether any auth is enabled

  cookie_secret_hook(h)

    Include password in cookie secret.

    This makes it so changing the password invalidates cookies.

    Return type:

      `HMAC`

  hashed_password

    Hashed password to use for web authentication.

    To generate, type in a python/IPython shell:

    > from jupyter_server.auth import passwd; passwd()

    The string should be of the form type:salt:hashed-password.

  property login_available: bool

    Whether a LoginHandler is needed - and therefore whether the login page should be displayed.

  passwd_check(password)

    Check password against our stored hashed password

  password_required

    Forces users to use a password for the Jupyter server. This is useful in a multi user environment, for instance when everybody in the LAN can access each other’s machine through ssh.

    In such a case, serving on localhost is not secure since any user can connect to the Jupyter server via ssh.

  persist_user_model(handler)

    Persist the user model to a cookie.

    Return type:

      `None`

  process_login_form(handler)

    Process login form data

    Return authenticated User if successful, None if not.

    Return type:

      `User` | `None`

  update_user_model(current_user, user_data)

    Update user information.

    Return type:

      `User`

  validate_security(app, ssl_options=None)

    Handle security validation.

    Return type:

      `None`

class jupyter_server.auth.identity.User(username, name='', display_name='', initials=None, avatar_url=None, color=None)

  Bases: `object`

  Object representing a User

  This or a subclass should be returned from IdentityProvider.get_user

  avatar_url: str | None = None
  color: str | None = None
  display_name: str = ''
  fill_defaults()

    Fill out default fields in the identity model

    - Ensures all values are defined

    - Fills out derivative values for name fields fields

    - Fills out null values for optional fields

  initials: str | None = None
  name: str = ''
  username: str

Tornado handlers for logging into the Jupyter Server.

class jupyter_server.auth.login.LegacyLoginHandler(application, request, **kwargs)

  Bases: `LoginFormHandler`

  Legacy LoginHandler, implementing most custom auth configuration.

  Deprecated in jupyter-server 2.0. Login configuration has moved to IdentityProvider.

  auth_header_pat = re.compile('token\\s+(.+)', re.IGNORECASE)
  classmethod get_login_available(settings)

    DEPRECATED in 2.0, use IdentityProvider API

  classmethod get_token(handler)

    Get the user token from a request

    Default:

    - in URL parameters: ?token=<token>

    - in header: Authorization: token <token>

  classmethod get_user(handler)

    DEPRECATED in 2.0, use IdentityProvider API

  classmethod get_user_cookie(handler)

    DEPRECATED in 2.0, use IdentityProvider API

  classmethod get_user_token(handler)

    DEPRECATED in 2.0, use IdentityProvider API

  property hashed_password
  classmethod is_token_authenticated(handler)

    DEPRECATED in 2.0, use IdentityProvider API

  passwd_check(a, b)

    Check a passwd.

  classmethod password_from_settings(settings)

    DEPRECATED in 2.0, use IdentityProvider API

  post()

    Post a login form.

  classmethod set_login_cookie(handler, user_id=None)

    Call this on handlers to set the login cookie for success

  classmethod should_check_origin(handler)

    DEPRECATED in 2.0, use IdentityProvider API

  classmethod validate_security(app, ssl_options=None)

    DEPRECATED in 2.0, use IdentityProvider API

class jupyter_server.auth.login.LoginFormHandler(application, request, **kwargs)

  Bases: `JupyterHandler`

  The basic tornado login handler

  accepts login form, passed to IdentityProvider.process_login_form.

  get()

    Get the login form.

  post()

    Post a login.

jupyter_server.auth.login.LoginHandler

  alias of `LegacyLoginHandler`

Tornado handlers for logging out of the Jupyter Server.

class jupyter_server.auth.logout.LogoutHandler(application, request, **kwargs)

  Bases: `JupyterHandler`

  An auth logout handler.

  get()

    Handle a logout.

Password generation for the Jupyter Server.

jupyter_server.auth.security.passwd(passphrase=None, algorithm='argon2')

  Generate hashed password and salt for use in server configuration.

  In the server configuration, set `c.ServerApp.password` to the generated string.

  Parameters:

    - passphrase (str) – Password to hash. If unspecified, the user is asked to input and verify a password.

    - algorithm (str) – Hashing algorithm to use (e.g, ‘sha1’ or any argument supported by `hashlib.new()`, or ‘argon2’).

  Returns:

    hashed_passphrase – Hashed password, in the format ‘hash_algorithm:salt:passphrase_hash’.

  Return type:

    str

  Examples

      >>> passwd("mypassword")
      'argon2:...'

jupyter_server.auth.security.passwd_check(hashed_passphrase, passphrase)

  Verify that a given passphrase matches its hashed version.

  Parameters:

    - hashed_passphrase (str) – Hashed password, in the format returned by `passwd`.

    - passphrase (str) – Passphrase to validate.

  Returns:

    valid – True if the passphrase matches the hash.

  Return type:

    bool

  Examples

      >>> myhash = passwd("mypassword")
      >>> passwd_check(myhash, "mypassword")
      True

      >>> passwd_check(myhash, "otherpassword")
      False

      >>> passwd_check("sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a", "mypassword")
      True

jupyter_server.auth.security.persist_config(config_file=None, mode=384)

  Context manager that can be used to modify a config object

  On exit of the context manager, the config will be written back to disk, by default with user-only (600) permissions.

jupyter_server.auth.security.set_password(password=None, config_file=None)

  Ask user for password, store it in JSON configuration file

A module with various utility methods for authorization in Jupyter Server.

jupyter_server.auth.utils.get_anonymous_username()

  Get a random user-name based on the moons of Jupyter. This function returns names like “Anonymous Io” or “Anonymous Metis”.

  Return type:

    `str`

jupyter_server.auth.utils.get_regex_to_resource_map()

  Returns a dictionary with all of Jupyter Server’s request handler URL regex patterns mapped to their resource name.

  e.g. { “/api/contents/<regex_pattern>”: “contents”, …}

jupyter_server.auth.utils.match_url_to_resource(url, regex_mapping=None)

  Finds the JupyterHandler regex pattern that would match the given URL and returns the resource name (str) of that handler.

  e.g. /api/contents/… returns “contents”

jupyter_server.auth.utils.warn_disabled_authorization()

  DEPRECATED, does nothing

## Module contents