Globus Auth#

There are several types of client object for communicating with the Globus Auth service. A client object may represent your application (as the driver of authentication and authorization flows), in which case the NativeAppAuthClient or ConfidentialAppAuthClient classes should generally be used.

class globus_sdk.AuthClient(client_id: UUID | str | None = None, **kwargs: Any)[source]#

Bases: BaseClient

Client for the Globus Auth API

This class provides helper methods for most common resources in the Auth API, and the common low-level interface from BaseClient of get, put, post, and delete methods, which can be used to access any API resource.

There are generally two types of resources, distinguished by the type of authentication which they use. Resources available to end users of Globus are authenticated with a Globus Auth Token (“Authentication: Bearer …”), while resources available to OAuth Clients are authenticated using Basic Auth with the Client’s ID and Secret. Some resources may be available with either authentication type.

Examples

Initializing an AuthClient to authenticate a user making calls to the Globus Auth service with an access token takes the form

>>> from globus_sdk import AuthClient, AccessTokenAuthorizer
>>> ac = AuthClient(authorizer=AccessTokenAuthorizer('<token_string>'))

You can, of course, use other kinds of Authorizers (notably the RefreshTokenAuthorizer).

Methods

scopes: ScopeBuilder | None = <globus_sdk.scopes.data._AuthScopesBuilder object>#

the scopes for this client may be present as a ScopeBuilder

get_identities(*, usernames: Iterable[str] | str | None = None, ids: Iterable[UUID | str] | UUID | str | None = None, provision: bool = False, query_params: dict[str, Any] | None = None) GetIdentitiesResponse[source]#

Given usernames=<U> or (exclusive) ids=<I> as keyword arguments, looks up identity information for the set of identities provided. <U> and <I> in this case are comma-delimited strings listing multiple Identity Usernames or Identity IDs, or iterables of strings, each of which is an Identity Username or Identity ID.

If Globus Auth’s identity auto-provisioning behavior is desired, provision=True may be specified.

Available with any authentication/client type.

Parameters:
  • usernames (str or iterable of str, optional) – A username or list of usernames to lookup. Mutually exclusive with ids

  • ids (str, UUID, or iterable of str or UUID, optional) – An identity ID or list of IDs to lookup. Mutually exclusive with usernames

  • provision (bool) – Create identities if they do not exist, allowing clients to get username-to-identity mappings prior to the identity being used

  • query_params (dict, optional) – Any additional parameters to be passed through as query params.

>>> ac = globus_sdk.AuthClient(...)
>>> # get by ID
>>> r = ac.get_identities(ids="46bd0f56-e24f-11e5-a510-131bef46955c")
>>> r.data
{
  'identities': [
    {
      'email': None,
      'id': '46bd0f56-e24f-11e5-a510-131bef46955c',
      'identity_provider': '7daddf46-70c5-45ee-9f0f-7244fe7c8707',
      'name': None,
      'organization': None,
      'status': 'unused',
      'username': 'globus@globus.org'
    }
  ]
}
>>> ac.get_identities(
...     ids=",".join(
...         ("46bd0f56-e24f-11e5-a510-131bef46955c", "168edc3d-c6ba-478c-9cf8-541ff5ebdc1c")
...     )
... )
>>> # or by usernames
>>> ac.get_identities(usernames="globus@globus.org")
>>> ac.get_identities(usernames="globus@globus.org,auth@globus.org")

You could also use iterables:

ac.get_identities(usernames=["globus@globus.org", "auth@globus.org"])

ac.get_identities(
    ids=["46bd0f56-e24f-11e5-a510-131bef46955c", "168edc3d-c6ba-478c-9cf8-541ff5ebdc1c"]
)

The result itself is iterable, so you can use it like so:

for identity in ac.get_identities(usernames=["globus@globus.org", "auth@globus.org"]):
    print(identity["id"])

GET /v2/api/identities

See Get Identities in the API documentation for details.

oauth2_get_authorize_url(*, query_params: dict[str, Any] | None = None) str[source]#

Get the authorization URL to which users should be sent. This method may only be called after oauth2_start_flow has been called on this AuthClient.

Parameters:

query_params (dict, optional) – Additional query parameters to include in the authorize URL. Primarily for internal use

Return type:

string

oauth2_exchange_code_for_tokens(auth_code: str) OAuthTokenResponse[source]#

Exchange an authorization code for a token or tokens.

Return type:

OAuthTokenResponse

Parameters:

auth_code (str) – An auth code typically obtained by sending the user to the authorize URL. The code is a very short-lived credential which this method is exchanging for tokens. Tokens are the credentials used to authenticate against Globus APIs.

oauth2_refresh_token(refresh_token: str, *, body_params: dict[str, Any] | None = None) OAuthTokenResponse[source]#

Exchange a refresh token for a OAuthTokenResponse, containing an access token.

Does a token call of the form

refresh_token=<refresh_token>
grant_type=refresh_token

plus any additional parameters you may specify.

Parameters:
  • refresh_token (str) – A Globus Refresh Token as a string

  • body_params (dict, optional) – A dict of extra params to encode in the refresh call.

oauth2_validate_token(token: str, *, body_params: dict[str, Any] | None = None) GlobusHTTPResponse[source]#

Validate a token. It can be an Access Token or a Refresh token.

This call can be used to check tokens issued to your client, confirming that they are or are not still valid. The resulting response has the form {"active": True} when the token is valid, and {"active": False} when it is not.

It is not necessary to validate tokens immediately after receiving them from the service – any tokens which you are issued will be valid at that time. This is more for the purpose of doing checks like

  • confirm that oauth2_revoke_token succeeded

  • at application boot, confirm no need to do fresh login

Parameters:
  • token (str) – The token which should be validated. Can be a refresh token or an access token

  • body_params (dict, optional) – Additional parameters to include in the validation body. Primarily for internal use

Examples

Revoke a token and confirm that it is no longer active:

>>> from globus_sdk import ConfidentialAppAuthClient
>>> ac = ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET)
>>> ac.oauth2_revoke_token('<token_string>')
>>> data = ac.oauth2_validate_token('<token_string>')
>>> assert not data['active']

During application boot, check if the user needs to do a login, even if a token is present:

>>> from globus_sdk import ConfidentialAppAuthClient
>>> ac = ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET)
>>> # this is not an SDK function, but a hypothetical function which
>>> # you use to load a token out of configuration data
>>> tok = load_token_from_config(...)
>>>
>>> if not tok or not ac.oauth2_validate_token(tok)['active']:
>>>     # do_new_login() is another hypothetical helper
>>>     tok = do_new_login()
>>> # at this point, tok is expected to be a valid token
oauth2_revoke_token(token: str, *, body_params: dict[str, Any] | None = None) GlobusHTTPResponse[source]#

Revoke a token. It can be an Access Token or a Refresh token.

This call should be used to revoke tokens issued to your client, rendering them inert and not further usable. Typically, this is incorporated into “logout” functionality, but it should also be used if the client detects that its tokens are in an unsafe location (e.x. found in a world-readable logfile).

You can check the “active” status of the token after revocation if you want to confirm that it was revoked.

Parameters:
  • token (str) – The token which should be revoked

  • body_params (dict, optional) – Additional parameters to include in the revocation body, which can help speed the revocation process. Primarily for internal use

Examples

>>> from globus_sdk import ConfidentialAppAuthClient
>>> ac = ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET)
>>> ac.oauth2_revoke_token('<token_string>')
oauth2_token(form_data: dict[str, Any] | PayloadWrapper) OAuthTokenResponse[source]#
oauth2_token(form_data: dict[str, Any] | PayloadWrapper, *, body_params: dict[str, Any] | None) OAuthTokenResponse
oauth2_token(form_data: dict[str, Any] | PayloadWrapper, *, response_class: type[RT]) RT
oauth2_token(form_data: dict[str, Any] | PayloadWrapper, *, body_params: dict[str, Any] | None, response_class: type[RT]) RT

This is the generic form of calling the OAuth2 Token endpoint. It takes form_data, a dict which will be encoded in a form POST body on the request.

Generally, users of the SDK should not call this method unless they are implementing OAuth2 flows.

Parameters:
  • response_class (class, optional) – This is used by calls to the oauth2_token endpoint which need to specialize their responses. For example, oauth2_get_dependent_tokens requires a specialize response class to handle the dramatically different format of the Dependent Token Grant response

  • form_data (dict or utils.PayloadWrapper) – The main body of the request

  • body_params (dict, optional) – Any additional parameters to be passed through as body parameters.

Return type:

response_class

oauth2_userinfo() GlobusHTTPResponse[source]#

Call the Userinfo endpoint of Globus Auth. Userinfo is specified as part of the OpenID Connect (OIDC) standard, and Globus Auth’s Userinfo is OIDC-compliant.

The exact data returned will depend upon the set of OIDC-related scopes which were used to acquire the token being used for this call. For details, see the API Info below.

ac = AuthClient(...)
info = ac.oauth2_userinfo()
print(
    'Effective Identity "{info["sub"]}" has '
    f'Full Name "{info["name"]}" and '
    f'Email "{info["email"]}"'
)

GET /v2/oauth2/userinfo

See Get Userinfo in the API documentation for details.

get_openid_configuration() GlobusHTTPResponse[source]#

Fetch the OpenID Connect configuration data from the well-known URI for Globus Auth.

get_jwk(openid_configuration: None | GlobusHTTPResponse | dict[str, Any], *, as_pem: Literal[True]) RSAPublicKey[source]#
get_jwk(openid_configuration: None | GlobusHTTPResponse | dict[str, Any], *, as_pem: Literal[False]) dict[str, Any]

Fetch the Globus Auth JWK.

Returns either a dict or an RSA Public Key object depending on as_pem.

Parameters:
  • openid_configuration (dict or GlobusHTTPResponse) – The OIDC config as a GlobusHTTPResponse or dict. When not provided, it will be fetched automatically.

  • as_pem (bool) – Decode the JWK to an RSA PEM key, typically for JWT decoding

class globus_sdk.NativeAppAuthClient(client_id: UUID | str, **kwargs: Any)[source]#

Bases: AuthClient

This type of AuthClient is used to represent a Native App’s communications with Globus Auth. It requires a Client ID, and cannot take an authorizer.

Native Apps are applications, like the Globus CLI, which are run client-side and therefore cannot keep secrets. Unable to possess client credentials, several Globus Auth interactions have to be specialized to accommodate the absence of a secret.

Any keyword arguments given are passed through to the AuthClient constructor.

Methods

oauth2_start_flow(requested_scopes: ScopeCollectionType | None = None, *, redirect_uri: str | None = None, state: str = '_default', verifier: str | None = None, refresh_tokens: bool = False, prefill_named_grant: str | None = None) GlobusNativeAppFlowManager[source]#

Starts a Native App OAuth2 flow.

This is done internally by instantiating a GlobusNativeAppFlowManager

While the flow is in progress, the NativeAppAuthClient becomes non thread-safe as temporary state is stored during the flow.

Parameters:
  • requested_scopes (str, MutableScope, or iterable of str or MutableScope, optional) – The scopes on the token(s) being requested. Defaults to openid profile email urn:globus:auth:scope:transfer.api.globus.org:all

  • redirect_uri – The page that users should be directed to after authenticating at the authorize URL. Defaults to ‘https://auth.globus.org/v2/web/auth-code’, which displays the resulting auth_code for users to copy-paste back into your application (and thereby be passed back to the GlobusNativeAppFlowManager)

  • state (str, optional) – The redirect_uri page will have this included in a query parameter, so you can use it to pass information to that page if you use a custom page. It defaults to the string ‘_default’

  • verifier (str, optional) – A secret used for the Native App flow. It will by default be a freshly generated random string, known only to this GlobusNativeAppFlowManager instance

  • refresh_tokens (bool, optional) – When True, request refresh tokens in addition to access tokens. [Default: False]

  • prefill_named_grant (str, optional) – Prefill the named grant label on the consent page

You can see an example of this flow in the usage examples.

The Globus Auth specification for Native App grants details modifications to the Authorization Code grant flow as The PKCE Security Protocol.

oauth2_refresh_token(refresh_token: str, *, body_params: dict[str, Any] | None = None) OAuthTokenResponse[source]#

NativeAppAuthClient specializes the refresh token grant to include its client ID as a parameter in the POST body. It needs this specialization because it cannot authenticate the refresh grant call with client credentials, as is normal.

class globus_sdk.ConfidentialAppAuthClient(client_id: UUID | str, client_secret: str, **kwargs: Any)[source]#

Bases: AuthClient

This is a specialized type of AuthClient used to represent an App with a Client ID and Client Secret wishing to communicate with Globus Auth. It must be given a Client ID and a Client Secret, and furthermore, these will be used to establish a BasicAuthorizer for authorization purposes. Additionally, the Client ID is stored for use in various calls.

Confidential Applications (i.e. Applications which are not Native Apps) are those like the Sample Data Portal, which have their own credentials for authenticating against Globus Auth.

Any keyword arguments given are passed through to the AuthClient constructor.

Methods

oauth2_client_credentials_tokens(requested_scopes: ScopeCollectionType | None = None) OAuthTokenResponse[source]#

Perform an OAuth2 Client Credentials Grant to get access tokens which directly represent your client and allow it to act on its own (independent of any user authorization). This method does not use a GlobusOAuthFlowManager because it is not at all necessary to do so.

Parameters:

requested_scopes (str, MutableScope, or iterable of str or MutableScope, optional) – The scopes on the token(s) being requested. Defaults to openid profile email urn:globus:auth:scope:transfer.api.globus.org:all

Return type:

OAuthTokenResponse

For example, with a Client ID of “CID1001” and a Client Secret of “RAND2002”, you could use this grant type like so:

>>> client = ConfidentialAppAuthClient("CID1001", "RAND2002")
>>> tokens = client.oauth2_client_credentials_tokens()
>>> transfer_token_info = (
...     tokens.by_resource_server["transfer.api.globus.org"])
>>> transfer_token = transfer_token_info["access_token"]
oauth2_start_flow(redirect_uri: str, requested_scopes: ScopeCollectionType | None = None, *, state: str = '_default', refresh_tokens: bool = False) GlobusAuthorizationCodeFlowManager[source]#

Starts or resumes an Authorization Code OAuth2 flow.

Under the hood, this is done by instantiating a GlobusAuthorizationCodeFlowManager

Parameters:
  • redirect_uri (str redirect_uri (string)) – The page that users should be directed to after authenticating at the authorize URL.

  • requested_scopes (str, MutableScope, or iterable of str or MutableScope, optional) – The scopes on the token(s) being requested. Defaults to openid profile email urn:globus:auth:scope:transfer.api.globus.org:all

  • state (str, optional) – This string allows an application to pass information back to itself in the course of the OAuth flow. Because the user will navigate away from the application to complete the flow, this parameter lets the app pass an arbitrary string from the starting page to the redirect_uri

  • refresh_tokens (bool, optional) – When True, request refresh tokens in addition to access tokens. [Default: False]

You can see an example of this flow in the usage examples.

The Authorization Code Grant flow is described in the Globus Auth Specification.

oauth2_get_dependent_tokens(token: str, *, refresh_tokens: bool = False, additional_params: dict[str, Any] | None = None) OAuthDependentTokenResponse[source]#

Does a Dependent Token Grant against Globus Auth. This exchanges a token given to this client for a new set of tokens which give it access to resource servers on which it depends. This grant type is intended for use by Resource Servers playing out the following scenario:

  1. User has tokens for Service A, but Service A requires access to Service B on behalf of the user

  2. Service B should not see tokens scoped for Service A

  3. Service A therefore requests tokens scoped only for Service B, based on tokens which were originally scoped for Service A…

In order to do this exchange, the tokens for Service A must have scopes which depend on scopes for Service B (the services’ scopes must encode their relationship). As long as that is the case, Service A can use this Grant to get those “Dependent” or “Downstream” tokens for Service B.

Parameters:
  • token (str) – A Globus Access Token as a string

  • refresh_tokens (bool, optional) – When True, request dependent refresh tokens in addition to access tokens. [Default: False]

  • additional_params (dict, optional) – Additional parameters to include in the request body

Return type:

OAuthDependentTokenResponse

oauth2_token_introspect(token: str, *, include: str | None = None) GlobusHTTPResponse[source]#

Get information about a Globus Auth token.

Parameters:
  • token (str) – An Access Token as a raw string, being evaluated

  • include (str, optional) – A value for the include parameter in the request body. Default is to omit the parameter.

ac = globus_sdk.ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET)
ac.oauth2_token_introspect("<token_string>")

Get information about a Globus Auth token including the full identity set of the user to whom it belongs

ac = globus_sdk.ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET)
data = ac.oauth2_token_introspect("<token_string>", include="identity_set")
for identity in data["identity_set"]:
    print('token authenticates for "{}"'.format(identity))

POST /v2/oauth2/token/introspect

See Token Introspection in the API documentation for details.

Helper Objects#

The IdentityMap is a specialized object which aids in the particular use-case in which the Globus Auth AuthClient.get_identities() API is being used to resolve large numbers of usernames or IDs. It combines caching, request batching, and other functionality.

class globus_sdk.IdentityMap(auth_client: AuthClient, identity_ids: Iterable[str] | None = None, *, id_batch_size: int | None = None, cache: None | MutableMapping[str, dict[str, Any]] = None)[source]#

Bases: object

There’s a common pattern of having a large batch of Globus Auth Identities which you want to inspect. For example, you may have a list of identity IDs fetched from Access Control Lists on Globus Endpoints. In order to display these identities to an end user, you may want to resolve them to usernames.

However, naively looking up the identities one-by-one is very inefficient. It’s best to do batched lookups with multiple identities at once. In these cases, an IdentityMap can be used to do those batched lookups for you.

An IdentityMap is a mapping-like type which converts Identity IDs and Identity Names to Identity records (dictionaries) using the Globus Auth API.

Note

IdentityMap objects are not full Mappings in the same sense as python dicts and similar objects. By design, they only implement a small part of the Mapping protocol.

The basic usage pattern is

  • create an IdentityMap with an AuthClient which will be used to call out to Globus Auth

  • seed the IdentityMap with IDs and Usernames via add() (you can also do this during initialization)

  • retrieve identity IDs or Usernames from the map

Because the map can be populated with a collection of identity IDs and Usernames prior to lookups being performed, it can improve the efficiency of these operations up to 100x over individual lookups.

If you attempt to retrieve an identity which has not been previously added to the map, it will be immediately added. But adding many identities beforehand will improve performance.

The IdentityMap will cache its results so that repeated lookups of the same Identity will not repeat work. It will also map identities both by ID and by Username, regardless of how they’re initially looked up.

Warning

If an Identity is not found in Globus Auth, it will trigger a KeyError when looked up. Your code must be ready to handle KeyErrors when doing a lookup.

Correct usage looks something like so:

ac = globus_sdk.AuthClient(...)
idmap = globus_sdk.IdentityMap(
    ac, ["foo@globusid.org", "bar@uchicago.edu"]
)
idmap.add("baz@xsede.org")
# adding by ID is also valid
idmap.add("c699d42e-d274-11e5-bf75-1fc5bf53bb24")
# map ID to username
assert (
    idmap["c699d42e-d274-11e5-bf75-1fc5bf53bb24"]["username"]
    == "go@globusid.org"
)
# map username to ID
assert (
    idmap["go@globusid.org"]["id"]
    == "c699d42e-d274-11e5-bf75-1fc5bf53bb24"
)

And simple handling of errors:

try:
    record = idmap["no-such-valid-id@example.org"]
except KeyError:
    username = "NO_SUCH_IDENTITY"
else:
    username = record["username"]

or you may achieve this by using the get() method:

# internally handles the KeyError and returns the default value
record = idmap.get("no-such-valid-id@example.org", None)
username = record["username"] if record is not None else "NO_SUCH_IDENTITY"
Parameters:
  • auth_client (AuthClient) – The client object which will be used for lookups against Globus Auth

  • identity_ids (iterable of str, optional) – A list or other iterable of usernames or identity IDs (potentially mixed together) which will be used to seed the IdentityMap ‘s tracking of unresolved Identities.

  • id_batch_size (int, optional) – A non-default batch size to use when communicating with Globus Auth. Leaving this set to the default is strongly recommended.

  • cache (MutableMapping, optional) – A dict or other mapping object which will be used to cache results. The default is that results are cached once per IdentityMap object. If you want multiple IdentityMaps to share data, explicitly pass the same cache to both.

Methods

__delitem__(key: str) None[source]#

IdentityMap supports del map[key]. Note that this only removes lookup values from the cache and will not impact the set of unresolved/pending IDs.

__getitem__(key: str) Any[source]#

IdentityMap supports dict-like lookups with map[key]

__init__(auth_client: AuthClient, identity_ids: Iterable[str] | None = None, *, id_batch_size: int | None = None, cache: None | MutableMapping[str, dict[str, Any]] = None)[source]#
add(identity_id: str) bool[source]#

Add a username or ID to the IdentityMap for batch lookups later.

Returns True if the ID was added for lookup. Returns False if it was rejected as a duplicate of an already known name.

Parameters:

identity_id (str) – A string Identity ID or Identity Name (a.k.a. “username”) to add

get(key: str, default: Any | None = None) Any[source]#

A dict-like get() method which accepts a default value.

Auth Responses#

class globus_sdk.OAuthTokenResponse(*args: Any, **kwargs: Any)[source]#

Bases: GlobusHTTPResponse

Class for responses from the OAuth2 code for tokens exchange used in 3-legged OAuth flows.

property by_resource_server: dict[str, dict[str, Any]]#

Representation of the token response in a dict indexed by resource server.

Although OAuthTokenResponse.data is still available and valid, this representation is typically more desirable for applications doing inspection of access tokens and refresh tokens.

property by_scopes: _ByScopesGetter#

Representation of the token response in a dict-like object indexed by scope name (or even space delimited scope names, so long as they match the same token).

If you request scopes scope1 scope2 scope3, where scope1 and scope2 are for the same service (and therefore map to the same token), but scope3 is for a different service, the following forms of access are valid:

>>> tokens = ...
>>> # single scope
>>> token_data = tokens.by_scopes['scope1']
>>> token_data = tokens.by_scopes['scope2']
>>> token_data = tokens.by_scopes['scope3']
>>> # matching scopes
>>> token_data = tokens.by_scopes['scope1 scope2']
>>> token_data = tokens.by_scopes['scope2 scope1']
decode_id_token(openid_configuration: None | GlobusHTTPResponse | dict[str, Any] = None, jwk: RSAPublicKey | None = None, jwt_params: dict[str, Any] | None = None) dict[str, Any][source]#

Parse the included ID Token (OIDC) as a dict and return it.

If you provide the jwk, you must also provide openid_configuration.

Parameters:
  • openid_configuration (dict or GlobusHTTPResponse) – The OIDC config as a GlobusHTTPResponse or dict. When not provided, it will be fetched automatically.

  • jwk (RSAPublicKey) – The JWK as a cryptography public key object. When not provided, it will be fetched and parsed automatically.

  • jwt_params (dict) – An optional dict of parameters to pass to the jwt decode step. These are passed verbatim to the jwt library.

class globus_sdk.OAuthDependentTokenResponse(*args: Any, **kwargs: Any)[source]#

Bases: OAuthTokenResponse

Class for responses from the OAuth2 code for tokens retrieved by the OAuth2 Dependent Token Extension Grant. For more complete docs, see oauth2_get_dependent_tokens

decode_id_token(openid_configuration: None | GlobusHTTPResponse | dict[str, Any] = None, jwk: RSAPublicKey | None = None, jwt_params: dict[str, Any] | None = None) dict[str, Any][source]#

Parse the included ID Token (OIDC) as a dict and return it.

If you provide the jwk, you must also provide openid_configuration.

Parameters:
  • openid_configuration (dict or GlobusHTTPResponse) – The OIDC config as a GlobusHTTPResponse or dict. When not provided, it will be fetched automatically.

  • jwk (RSAPublicKey) – The JWK as a cryptography public key object. When not provided, it will be fetched and parsed automatically.

  • jwt_params (dict) – An optional dict of parameters to pass to the jwt decode step. These are passed verbatim to the jwt library.

OAuth2 Flow Managers#

These objects represent in-progress OAuth2 authentication flows. Most typically, you should not use these objects, but rather rely on the AuthClient object to manage one of these for you through its oauth2_* methods.

All Flow Managers inherit from the GlobusOAuthFlowManager abstract class. They are a combination of a store for OAuth2 parameters specific to the authentication method you are using and methods which act upon those parameters.

class globus_sdk.services.auth.GlobusNativeAppFlowManager(auth_client: globus_sdk.AuthClient, requested_scopes: ScopeCollectionType | None = None, redirect_uri: str | None = None, state: str = '_default', verifier: str | None = None, refresh_tokens: bool = False, prefill_named_grant: str | None = None)[source]#

Bases: GlobusOAuthFlowManager

This is the OAuth flow designated for use by clients wishing to authenticate users in the absence of a Client Secret. Because these applications run “natively” in the user’s environment, they cannot protect a secret. Instead, a temporary secret is generated solely for this authentication attempt.

Parameters:
  • auth_client (NativeAppAuthClient) – The NativeAppAuthClient object on which this flow is based. It is used to extract default values for the flow, and also to make calls to the Auth service.

  • requested_scopes (str, MutableScope, or iterable of str or MutableScope, optional) – The scopes on the token(s) being requested. Defaults to openid profile email urn:globus:auth:scope:transfer.api.globus.org:all

  • redirect_uri (str, optional) – The page that users should be directed to after authenticating at the authorize URL. Defaults to ‘https://auth.globus.org/v2/web/auth-code’, which displays the resulting auth_code for users to copy-paste back into your application (and thereby be passed back to the GlobusNativeAppFlowManager)

  • state (str, optional) – The redirect_uri page will have this included in a query parameter, so you can use it to pass information to that page if you use a custom page. It defaults to the string ‘_default’

  • verifier (str, optional) – A secret used for the Native App flow. It will by default be a freshly generated random string, known only to this GlobusNativeAppFlowManager instance

  • refresh_tokens (bool, optional) – When True, request refresh tokens in addition to access tokens. [Default: False]

  • prefill_named_grant (str, optional) – Prefill the named grant label on the consent page

exchange_code_for_tokens(auth_code: str) OAuthTokenResponse[source]#

The second step of the Native App flow, exchange an authorization code for access tokens (and refresh tokens if specified).

Return type:

OAuthTokenResponse

get_authorize_url(query_params: dict[str, Any] | None = None) str[source]#

Start a Native App flow by getting the authorization URL to which users should be sent.

Parameters:

query_params (dict, optional) – Additional query parameters to include in the authorize URL. Primarily for internal use

Return type:

string

The returned URL string is encoded to be suitable to display to users in a link or to copy into their browser. Users will be redirected either to your provided redirect_uri or to the default location, with the auth_code embedded in a query parameter.

class globus_sdk.services.auth.GlobusAuthorizationCodeFlowManager(auth_client: globus_sdk.AuthClient, redirect_uri: str, requested_scopes: ScopeCollectionType | None = None, state: str = '_default', refresh_tokens: bool = False)[source]#

Bases: GlobusOAuthFlowManager

This is the OAuth flow designated for use by Clients wishing to authenticate users in a web application backed by a server-side component (e.g. an API). The key constraint is that there is a server-side system that can keep a Client Secret without exposing it to the web client. For example, a Django application can rely on the webserver to own the secret, so long as it doesn’t embed it in any of the pages it generates.

The application sends the user to get a temporary credential (an auth_code) associated with its Client ID. It then exchanges that temporary credential for a token, protecting the exchange with its Client Secret (to prove that it really is the application that the user just authorized).

Parameters:
  • auth_client (ConfidentialAppAuthClient) – The AuthClient used to extract default values for the flow, and also to make calls to the Auth service.

  • redirect_uri (str) – The page that users should be directed to after authenticating at the authorize URL.

  • requested_scopes (str, MutableScope, or iterable of str or MutableScope, optional) – The scopes on the token(s) being requested. Defaults to openid profile email urn:globus:auth:scope:transfer.api.globus.org:all

  • state (str, optional) – This string allows an application to pass information back to itself in the course of the OAuth flow. Because the user will navigate away from the application to complete the flow, this parameter lets the app pass an arbitrary string from the starting page to the redirect_uri

  • refresh_tokens (bool, optional) – When True, request refresh tokens in addition to access tokens. [Default: False]

exchange_code_for_tokens(auth_code: str) OAuthTokenResponse[source]#

The second step of the Authorization Code flow, exchange an authorization code for access tokens (and refresh tokens if specified)

Return type:

OAuthTokenResponse

get_authorize_url(query_params: dict[str, Any] | None = None) str[source]#

Start a Authorization Code flow by getting the authorization URL to which users should be sent.

Parameters:

query_params (dict, optional) – Additional parameters to include in the authorize URL. Primarily for internal use

Return type:

string

The returned URL string is encoded to be suitable to display to users in a link or to copy into their browser. Users will be redirected either to your provided redirect_uri or to the default location, with the auth_code embedded in a query parameter.

Abstract Flow Manager#

class globus_sdk.services.auth.flow_managers.GlobusOAuthFlowManager[source]#

Bases: ABC

An abstract class definition that defines the interface for the Flow Managers for Globus Auth. Flow Managers are really just bundles of parameters to Globus Auth’s OAuth2 mechanisms, along with some useful utility methods. Primarily they can be used as a simple way of tracking small amounts of state in your application as it leverages Globus Auth for authentication.

For sophisticated use cases, the provided Flow Managers will NOT be sufficient, but you should consider the provided objects a model.

This way of managing OAuth2 flows is inspired by oauth2client. However, because oauth2client has an uncertain future (as of 2016-08-31), and we would have to wrap it in order to provide a clean API surface anyway, we implement our own set of Flow objects.

abstract exchange_code_for_tokens(auth_code: str) OAuthTokenResponse[source]#

This method takes an auth_code and produces a response object containing one or more tokens. Most typically, this is the second step of the flow, and consumes the auth_code that was sent to a redirect URI used in the authorize step.

The exchange process may be parameterized over attributes of the specific flow manager instance which is generating it.

Parameters:

auth_code (str) – The authorization code which was produced from the authorization flow

Return type:

OAuthTokenResponse

abstract get_authorize_url(query_params: dict[str, Any] | None = None) str[source]#

This method consumes no arguments or keyword arguments, and produces a string URL for the Authorize Step of a 3-legged OAuth2 flow. Most typically, this is the first step of the flow, and the user may be redirected to the URL or provided with a link.

The authorize_url may be (usually is) parameterized over attributes of the specific flow manager instance which is generating it.

Return type:

string