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=None, authorizer=None, **kwargs)[source]¶ Bases:
globus_sdk.base.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
ofget
,put
,post
, anddelete
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
-
get_identities
(usernames=None, ids=None, provision=False, **params)[source]¶ GET /v2/api/identities
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.
Examples
>>> ac = globus_sdk.AuthClient(...) >>> # by IDs >>> r = ac.get_identities(ids="46bd0f56-e24f-11e5-a510-131bef46955c") >>> r.data {u'identities': [{u'email': None, u'id': u'46bd0f56-e24f-11e5-a510-131bef46955c', u'identity_provider': u'7daddf46-70c5-45ee-9f0f-7244fe7c8707', u'name': None, u'organization': None, u'status': u'unused', u'username': u'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"]) ...
External Documentation
See Identities Resources in the API documentation for details.
Get the authorization URL to which users should be sent. This method may only be called after
oauth2_start_flow
has been called on thisAuthClient
.- Parameters:
additional_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)[source]¶ Exchange an authorization code for a token or tokens.
- Return type:
- 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, additional_params=None)[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
additional_params (dict, optional) – A dict of extra params to encode in the refresh call.
-
oauth2_validate_token
(token, additional_params=None)[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
succeededat 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
additional_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, additional_params=None)[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
additional_params – 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, response_class=<class 'globus_sdk.auth.token_response.OAuthTokenResponse'>)[source]¶ 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- Return type:
response_class
-
oauth2_userinfo
()[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 External Documentation below.
Examples
>>> ac = AuthClient(...) >>> info = ac.oauth2_userinfo() >>> print('Effective Identity "{}" has Full Name "{}" and Email "{}"' >>> .format(info["sub"], info["name"], info["email"]))
External Documentation
See Userinfo in the API documentation for details.
-
class
globus_sdk.
NativeAppAuthClient
(client_id, **kwargs)[source]¶ Bases:
globus_sdk.auth.client_types.base.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 anauthorizer
.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=None, redirect_uri=None, state='_default', verifier=None, refresh_tokens=False, prefill_named_grant=None)[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 or iterable of str, optional) – The scopes on the token(s) being requested, as a space-separated string or iterable of strings. 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 theGlobusNativeAppFlowManager
)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
instancerefresh_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
Examples
You can see an example of this flow in the usage examples
External Documentation
The Globus Auth specification for Native App grants details the modifications to the Authorization Code grant flow as The PKCE Security Protocol
-
-
class
globus_sdk.
ConfidentialAppAuthClient
(client_id, client_secret, **kwargs)[source]¶ Bases:
globus_sdk.auth.client_types.base.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 aBasicAuthorizer <globus_sdk.authorizers.BasicAuthorizer
for authorization purposes. Additionally, the Client ID is stored for use in various calls.Confidential Applications (i.e. Applications with 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=None)[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, optional) – Space-separated scope names being requested for the access token(s). Defaults to a set of commonly desired scopes for Globus.
- Return type:
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, requested_scopes=None, state='_default', refresh_tokens=False)[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 or iterable of str, optional) – The scopes on the token(s) being requested, as a space-separated string or an iterable of strings. 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
]
Examples
You can see an example of this flow in the usage examples
External Documentation
The Authorization Code Grant flow is described in the Globus Auth Specification
-
oauth2_get_dependent_tokens
(token, additional_params=None)[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:
User has tokens for Service A, but Service A requires access to Service B on behalf of the user
Service B should not see tokens scoped for Service A
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
additional_params (dict, optional) – Additional parameters to include in the request body
- Return type:
-
oauth2_token_introspect
(token, include=None)[source]¶ POST /v2/oauth2/token/introspect
Get information about a Globus Auth token.
>>> 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))
- 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.
External Documentation
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 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, identity_ids=None, id_batch_size=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 Authseed the
IdentityMap
with IDs and Usernames viaadd()
(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 Authidentity_ids (iterable of str) – 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.
Methods
-
__delitem__
(key)[source]¶ IdentityMap
supportsdel map[key]
. Note that this only removes lookup values from the cache and will not impact the set of unresolved/pending IDs.
-
__init__
(auth_client, identity_ids=None, id_batch_size=None)[source]¶ Initialize self. See help(type(self)) for accurate signature.
-
add
(identity_id)[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
Auth Responses¶
-
class
globus_sdk.auth.token_response.
OAuthTokenResponse
(*args, **kwargs)[source]¶ Bases:
globus_sdk.response.GlobusHTTPResponse
Class for responses from the OAuth2 code for tokens exchange used in 3-legged OAuth flows.
-
property
by_resource_server
¶ 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
¶ 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
(auth_client=None)[source]¶ A parsed ID Token (OIDC) as a dict.
- Parameters:
auth_client (
AuthClient
) – Deprecated parameter for providing the AuthClient used to request this token back to the OAuthTokenResponse. The SDK now tracks this internally, so it is no longer necessary.
-
property
-
class
globus_sdk.auth.token_response.
OAuthDependentTokenResponse
(*args, **kwargs)[source]¶ Bases:
globus_sdk.auth.token_response.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
(auth_client)[source]¶ A parsed ID Token (OIDC) as a dict.
- Parameters:
auth_client (
AuthClient
) – Deprecated parameter for providing the AuthClient used to request this token back to the OAuthTokenResponse. The SDK now tracks this internally, so it is no longer necessary.
-