Authentication

Introduction

When you run the Flow Production Tracking, it will connect to Flow Production Tracking on a regular basis in order to carry out certain operations. For example, you publish a new render or you browse for an item that you want to load into your scene. In order to do that, Toolkit will need to log in to Flow Production Tracking, either to read or write data, which means that it will need to make sure the current user is authenticated so that a connection with the Flow Production Tracking server can be established.

Note

The Toolkit authentication API does not require an installed or bootstrapped instance of the Toolkit Core platform. You can use it simply by importing sgtk and calling its methods.

Toolkit uses session tokens for authentication. These are unique identifiers which are generated by the Flow Production Tracking server. Whenever a Flow Production Tracking API request comes in from Toolkit, this session token is passed along so that the server can validate it and grant access to the request. These session tokens time out after a certain period of inactivity, usually 24 hours, and whenever this happens, the user is typically prompted to enter their password again in order for Toolkit to retrieve a new session token.

This sgtk.authentication API handles the notion of the current user and wraps around the Flow Production Tracking API to ensure that if a session times out, the user is prompted to re-enter their credentials. The API and process for authentication can be summarized as follows:

  • A ShotgunAuthenticator class is used to handle the actual authentication process. This can be called in various ways and also wraps around storing authenticated sessions so that the user doesn’t have to keep typing their password in.

  • After a successful authentication operation, the ShotgunAuthenticator returns a ShotgunUser object. This object represents the user and can be used to generate a Flow Production Tracking API instance which belongs to the user. The generated API instance is subclassed from the normal Flow Production Tracking API and gracefully traps when the user credentials are no longer valid (which usually happens after a certain period of inactivity). In this case it will automatically present the user with a password prompt.

  • ShotgunUser objects can be serialized via the serialize_user() and deserialize_user() methods and can be passed between multiple sessions, say for example when a DCC is launched or when a job is sent to the render farm.

  • Toolkit core does not have a built-in notion of the current user so this needs to be explicitly set via the sgtk.set_authenticated_user() method. If you are using the Bootstrap process to start up Toolkit, you pass a ShotgunUser directly to the ToolkitManager constructor.

  • If you want to control how the ShotgunAuthenticator creates a user object and caches session data inbetween invocations, you can subclass the DefaultsManager.

Normally, the tk session is created automatically as part of the DCC launch process, tank command or Flow Production Tracking Desktop, so there is little to worry about. There are some use cases where controlling the authentication directly may be useful:

  • If you are dispatching jobs to the render farm, you can serialize and deserialize the user object from the dispatching DCC. Use the sgtk.get_authenticated_user() to extract the user object from your current session and sgtk.set_authenticated_user() to set it on your remote session.

  • If you want to use an explicit script user, use ShotgunAuthenticator.create_script_user() to create a ShotgunUser object representing a script. This may look like this:

    import sgtk
    
    # create an authenticator object. This is the main object which
    # handles all authentication
    sa = sgtk.authentication.ShotgunAuthenticator()
    
    # Use the authenticator to create a user object. This object
    # identifies a Flow Production Tracking user or script and also wraps around
    # a Flow Production Tracking API instance which is associated with that user.
    user = sa.create_script_user(api_script="myscript",
                                 api_key="xxxxx",
                                 host="https://myhost.shotgrid.autodesk.com")
    
    # tell the Toolkit Core API which user to use
    sgtk.set_authenticated_user(user)
    
  • If you want to use a standard UI to prompt a user for a host, username and password.

API Reference

ShotgunAuthenticator

class sgtk.authentication.ShotgunAuthenticator(defaults_manager=None)[source]

The ShotgunAuthenticator is the central object in the Shotgun authentication module. It helps you with authentication and login and makes it easy to create and maintain a shotgun connection so that it belongs to a given user. It also helps store who the current user is, so that users don’t have to log in over and over again, but only when needed.

A simple use case scenario would look something like this:

# create an authenticator
sa = ShotgunAuthenticator()

# Get a user object. If the authenticator system has already
# stored a default user belonging to a default shotgun site,
# it will simply return this. Otherwise, it will pop up a UI
# asking the user to log in.
user = sa.get_user()

# now the user object can be used to generate an authenticated
# Shotgun connection.
sg =  user.create_sg_connection()

# This connection will automatically monitor itself and in the
# case the user credentials (session token) that the user object
# encapsulates expires or become invalid, the shotgun connection
# instance will automatically pop up a UI, asking the user
# to type in their password. This typically happens after
# 24 hours of inactivity.

In addition to the simple code sample, there are a few more concepts:

  • User objects are serializable, meaning that you can pass one from one process to another, allowing you to maintain an experience where a user is authenticated across multiple applications. This is useful if you for example want to launch RV from Maya or Maya from the PTR desktop app.

  • The authenticator maintains the concept of a default user - which can be used in order to present good defaults in UIs as well as headless script based authentication flows.

  • The API provides methods for authentication where client code can request that the user is prompted to log in.

  • On the backend, a defaults manager can be specified which implements the logic for how various settings are to be stored. This makes it possible to easily customize the behavior of the authenticator to work in different scenarios.

For more information, please see the individual methods below.

Constructor

Parameters:

defaults_manager – A DefaultsManager object that defines the basic behavior of this authenticator. If omitted, the default, built-in DefaultsManager will be used.

clear_default_user()[source]

Removes the default user’s credentials from disk for the default host. The next time the ShotgunAuthenticator.get_default_user() method is called, None will be returned.

Returns:

If a user was cleared, the user object is returned, None otherwise.

get_user_from_prompt(host=None, login=None, http_proxy=None, is_host_fixed=None)[source]

Display a UI prompt (QT based UI if possible but may fall back on console)

The DefaultsManager is called to pre-fill the host, login name, http_proxy and is_host_fixed if not provided.

Parameters:
  • host – Shotgun host to log in to. If None, the default host will be used.

  • login – Shotgun user login. If None, the default login will be used.

  • http_proxy – Shotgun proxy to use. If None, the default http proxy will be used.

  • is_host_fixed – Weither the host is fixed or not. If None, the default value will be used.

Raises:

AuthenticationCancelled – If the user cancels the authentication process, an AuthenticationCancelled is thrown.

Returns:

The SessionUser based on the login information provided.

create_session_user(login, session_token=None, password=None, host=None, http_proxy=None, session_metadata=None)[source]

Create a ShotgunUser given a set of human user credentials. Either a password or session token must be supplied. If a password is supplied, a session token will be generated for security reasons.

Parameters:
  • login – Shotgun user login

  • session_token – Shotgun session token

  • password – Shotgun password

  • host – Shotgun host to log in to. If None, the default host will be used.

  • http_proxy – Shotgun proxy to use. If None, the default http proxy will be used.

  • session_metadata – When using Web/SSO, b64encoded browser cookies.

Returns:

A ShotgunUser instance.

create_script_user(api_script, api_key, host=None, http_proxy=None)[source]

Create an AuthenticatedUser given a set of script credentials.

Parameters:
  • api_script – Shotgun script user

  • api_key – Shotgun script key

  • host – Shotgun host to log in to. If None, the default host will be used.

  • http_proxy – Shotgun proxy to use. If None, the default http proxy will be used.

Returns:

A ShotgunUser derived instance.

get_default_host()[source]

Returns the host from the defaults manager.

Returns:

The default host string.

get_default_http_proxy()[source]

Returns the HTTP proxy from the defaults manager.

Returns:

The default http proxy string.

get_default_user()[source]

Returns the default user from the defaults manager.

Returns:

A ShotgunUser derived instance if available, None otherwise.

get_user()[source]

This method will always return a valid user. It will first ask for the default user to the defaults manager. If none is found, the user will be prompted on the command line or from a dialog for their credentials. Once the user has entered valid credentials, the default user will be updated with these.

Returns:

A ShotgunUser derived instance matching the credentials provided.

Raises:

AuthenticationCancelled is raised if the user cancelled the authentication.

ShotgunUser

class sgtk.authentication.ShotgunUser(impl)[source]

Represents a Shotgun user, either a script or a person and provides an entry point into the authentication system.

User objects are created via the ShotgunAuthenticator object, which will handle caching user objects on disk, prompting the user for their credentials etc.

Once you have retrieved one of the user objects below, this can be used to access Shotgun in a seamless way. The create_sg_connection() will return a Shotgun API handle which is associated with the current user. This API handle is also monitored for authentication timeouts, so if the user’s session times out (typically due to periods of inactivity), the user may be prompted (via a QT UI or stdin/stdout if only console is accessible) to refresh their Shotgun session by typing in their password.

If you need to persist the user object, this is possible via the serialization methods. This is particularly useful if you need to pass a user object from one process to another, for example when launching a DCC such as Maya or Nuke.

Parameters:

impl – Internal user implementation class this class proxies.

property host

Returns the host for this user.

Returns:

The host string.

property http_proxy

Returns the HTTP proxy for this user.

Returns:

The HTTP proxy string.

property login

The login for this current user. For Shotgun user types that don’t have a concept of a login (like API scripts), None is returned.

Returns:

The login string or None.

resolve_entity()[source]

Resolves the Shotgun entity associated with this user.

Returns:

A dictionary with type and id values.

Return type:

dict

create_sg_connection()[source]

Creates a Shotgun connection using the credentials for this user.

Returns:

A Shotgun connection.

are_credentials_expired()[source]

Checks if the credentials for the user are expired.

Returns:

True if the credentials are expired, False otherwise.

refresh_credentials()[source]

Refreshes the credentials of this user so that they don’t expire. If they are expired, you will be prompted for the user’s password.

DefaultsManager

class sgtk.authentication.DefaultsManager(fixed_host=None)[source]

The defaults manager allows a client of the Shotgun Authenticator class to customize various behaviors around data storage and settings.

By default, when you construct a ShotgunAuthenticator object, it will be instantiated with a standard defaults manager implementation. This will work for most cases - user session credentials will be stored in a file on disk and the system maintains a concept of a current user and a current host.

If a setting isn’t found, the DefaultsManager will fall back to the value stored inside toolkit.ini See Centralizing your settings for more information.

If, however, you want to implement a custom behavior around how defaults are managed, simply derive from this class and pass your custom instance to the ShotgunAuthenticator object when you construct it.

Parameters:

fixed_host (str) – Allows to specify the host that will be used for authentication. Defaults to None.

is_host_fixed()[source]

When doing an interactive login, this indicates if the user can decide the host to connect to. In its default implementation, the DefaultsManager will indicate that the host is not fixed, meaning that the user will be presented with an option to pick a site at login time, unless a default host was provided during initialization. If that is the case, then this method will return True.

With something like Toolkit, where each project already have a specific site association, you typically want to override this to return True, indicating to the authenticator not to ask the user which site they want to log in to.

Returns:

False if the user should be given an option to decide which host to log in to, True if the host is already predetermined and cannot be changed by the user.

get_host()[source]

The default host is used as a useful starting point when doing interactive authentication. When the host is not fixed (see the is_host_fixed() method), the return value of get_host is what is used to implement single sign-on between all Toolkit desktop applications (at the moment, tank and Flow Production Tracking).

The default implementation will return the fixed host if one was provided during the initialization. If fixed host was provided, the default implementation maintains a concept of a “current host” which will be presented as a default to users when they are logging in.

When the host is fixed, this must return a value and this value will be used as an absolute rather than a default suggested to the user.

Returns:

A string containing the default host name.

set_host(host)[source]

Called by the authentication system when a new host has been defined.

Parameters:

host – The new default host.

get_http_proxy()[source]

Called by the authentication system when it needs to retrieve the proxy settings to use for a Shotgun connection.

Note

If the centralized settings do not specify an HTTP proxy, Toolkit will rely on Python’s urllib.getproxies to find an HTTP proxy.

There is a restriction when looking for proxy information from Mac OS X System Configuration or Windows Systems Registry: in these cases, Toolkit does not support the use of proxies which require authentication (username and password).

The returned format will be the same as is being used in the Shotgun API. For more information, see the Shotgun API documentation.

Returns:

String containing the default http proxy, None by default.

get_login()[source]

Called by the authentication system when it needs to get a value for the login. Typically this is used to populate UI fields with defaults.

Returns:

Default implementation returns the login for the currently stored user.

get_user_credentials()[source]

Called by the authentication system when it requests a default or current user.

A dictionary with a login and a session token should be returned, which will allow the authentication system to authenticate the user.

The default implementation maintains a concept where it stores the currently authenticated user and its session token and tries to return this if possible, effectively meaning that the user will be automatically logged in without having to be prompted.

This is typically subclassed if you want to track the notion of a current user in an alternative way or maintain a separate notion of the “current” user, separate from the default user maintained by the default implementation.

Toolkit uses the default implementation and will therefore remember the user’s credentials across all DCCs and tools.

Returns:

A dictionary either with keys login and session_token in the case of a normal Shotgun User, keys api_script and api_key in the case of a Script User or None in case no credentials could be established.

set_login(login)[source]

Called by the authentication system when a new user is being logged in.

The default implementation maintains a concept of a default user (returned via the get_user_credentials) and whenever the login is set via this method, the default user will change to be this login instead.

Parameters:

login – login as string

Utilities

sgtk.authentication.deserialize_user(payload)[source]

Converts a payload produced by serialize into any of the ShotgunUser derived instance.

Parameters:

payload – Pickled dictionary of values

Returns:

A ShotgunUser derived instance.

sgtk.authentication.serialize_user(user, use_json=False)[source]

Serializes a user. Meant to be consumed by deserialize.

Parameters:
  • user – User object that needs to be serialized.

  • use_json – If True, a json representation will be generated. A pickled representation will be generated otherwise.

Returns:

The payload representing the user.

Exception Classes

class sgtk.authentication.ShotgunAuthenticationError[source]

Bases: Exception

Base class for all exceptions coming out from this module.

class sgtk.authentication.AuthenticationError[source]

Bases: ShotgunAuthenticationError

Thrown when credentials are rejected by the server.

class sgtk.authentication.IncompleteCredentials(msg)[source]

Bases: ShotgunAuthenticationError

Thrown when credentials are provided but are incomplete.

Parameters:

msg (str) – Reason why the credentials are incomplete.

class sgtk.authentication.AuthenticationCancelled[source]

Bases: ShotgunAuthenticationError

Thrown when the user cancels authentication or session renewal.

class sgtk.authentication.ConsoleLoginNotSupportedError(url, site_auth_type='Single Sign-On')[source]

Bases: ShotgunAuthenticationError

Thrown when attempting to use Username/Password pair to login onto an SSO-enabled site.

Parameters:
  • url (str) – Url of the site where login was attempted.

  • site_auth_type (str) – type of authentication, e.g. SSO, Identity. The default value is for backward compatibility.

class sgtk.authentication.UnresolvableHumanUser(login)[source]

Bases: UnresolvableUser

Thrown when Toolkit is not able to resolve a human user.

Parameters:

login (str) – login field value of the HumanUser that could not be resolved.

class sgtk.authentication.UnresolvableScriptUser(script_name)[source]

Bases: UnresolvableUser

Thrown when Toolkit is not able to resolve a human user.

Parameters:

script_name (str) – firstname field value of the ApiUser that could not be resolved.