def internal_auth_client(requires_instance=False, force_new_client=False): """ Looks up the values for this CLI's Instance Client in config If none exists and requires_instance is True or force_new_client is True, registers a new Instance Client with GLobus Auth If none exists and requires_instance is false, defaults to a Native Client for backwards compatibility Returns either a NativeAppAuthClient or a ConfidentialAppAuthClient """ client_id = lookup_option(CLIENT_ID_OPTNAME) client_secret = lookup_option(CLIENT_SECRET_OPTNAME) template_id = lookup_option(TEMPLATE_ID_OPTNAME) or DEFAULT_TEMPLATE_ID template_client = internal_native_client() existing = client_id and client_secret # if we are forcing a new client, delete any existing client if force_new_client and existing: existing_client = globus_sdk.ConfidentialAppAuthClient( client_id, client_secret) try: existing_client.delete("/v2/api/clients/{}".format(client_id)) # if the client secret has been invalidated or the client has # already been removed, we continue on except globus_sdk.exc.AuthAPIError: pass # if we require a new client to be made if force_new_client or (requires_instance and not existing): # register a new instance client with auth body = { "client": { "template_id": template_id, "name": "Globus CLI" } } res = template_client.post("/v2/api/clients", json_body=body) # get values and write to config credential_data = res["included"]["client_credential"] client_id = credential_data["client"] client_secret = credential_data["secret"] write_option(CLIENT_ID_OPTNAME, client_id) write_option(CLIENT_SECRET_OPTNAME, client_secret) return globus_sdk.ConfidentialAppAuthClient( client_id, client_secret, app_name="Globus CLI") # if we already have a client, just return it elif existing: return globus_sdk.ConfidentialAppAuthClient( client_id, client_secret, app_name="Globus CLI") # fall-back to a native client to not break old logins # TOOD: eventually remove this behavior else: return template_client
def _load_funcx_client(): """ Create an AuthClient for the portal """ # TODO: REMOVE THE TRUE if _prod or True: app = globus_sdk.ConfidentialAppAuthClient(GLOBUS_CLIENT, GLOBUS_KEY) else: app = globus_sdk.ConfidentialAppAuthClient('', '') return app
def setUpClass(self): """ Instantiates an ConfidentialAppAuthClient for confidential_app_client1 and for resource_server_client """ client_data = get_client_data()["confidential_app_client1"] self.cac = globus_sdk.ConfidentialAppAuthClient( client_id=client_data["id"], client_secret=client_data["secret"]) client_data = get_client_data()["resource_server_client"] self.rsc = globus_sdk.ConfidentialAppAuthClient( client_id=client_data["id"], client_secret=client_data["secret"])
def _load_dlhub_client(): """Create an AuthClient for the portal No credentials are used if the server is not production Returns: (globus_sdk.ConfidentialAppAuthClient): Client used to perform GlobusAuth actions """ if _prod: app = globus_sdk.ConfidentialAppAuthClient(GLOBUS_CLIENT, GLOBUS_KEY) else: app = globus_sdk.ConfidentialAppAuthClient('', '') return app
def status(source_name): # Make MDFCC try: logger.debug("Creating MDFCC for status") auth_client = globus_sdk.ConfidentialAppAuthClient( app.config['PORTAL_CLIENT_ID'], app.config['PORTAL_CLIENT_SECRET']) mdf_authorizer = globus_sdk.RefreshTokenAuthorizer( session["tokens"]["mdf_dataset_submission"]["refresh_token"], auth_client) mdfcc = mdf_connect_client.MDFConnectClient( service_instance=app.config["MDFCC_SERVICE"], authorizer=mdf_authorizer) except Exception as e: logger.error("Status MDFCC init: {}".format(repr(e))) json_res = {"success": False, "error": "Unable to initialize client."} else: try: logger.debug("Requesting status") json_res = mdfcc.check_status(source_name, raw=True) except Exception as e: logger.error("Status request: {}".format(repr(e))) json_res = {"success": False, "error": "Status request failed."} # return (jsonify(json_res), status_code) return render_template("status.jinja2", status_res=json_res)
def get_globus_client(self, username=None): """ Get Globus SDK RESTful clients Args: username (str): User's GlobusID username Returns: auth_client (Globus SDK Client): Globus Auth RESTful client nexus_client (Globus Nexus Client): Globus Auth-based RESTful Globus Nexus client """ if username is None: username = self.config["globus"]["root_user"]["username"] log.debug("Getting Globus SDK Auth and Nexus client for user %s", username) # Setting up Globus SDK client client_id = self.config["globus"]["app"]["client_id"] client_secret = self.config["globus"]["app"]["client_secret"] confidential_client = globus_sdk.ConfidentialAppAuthClient( client_id, client_secret) # Getting Authorizers auth_token, nexus_token = self.get_tokens(username) auth_authorizer = globus_sdk.RefreshTokenAuthorizer( auth_token, confidential_client) nexus_authorizer = globus_sdk.RefreshTokenAuthorizer( nexus_token, confidential_client) auth_client = globus_sdk.AuthClient(authorizer=auth_authorizer) nexus_client = NexusClient(authorizer=nexus_authorizer) return auth_client, nexus_client
def setUp(self): """ Makes a client_credentials grant to get new tokens for testing Sets up an ConfidentialClient and a ClientCredentialsAuthorizer with a mock on_refresh function for testing their interactions """ super(ClientCredentialsAuthorizerIntegrationTests, self).setUp() self.scopes = "urn:globus:auth:scope:transfer.api.globus.org:all" client_id = get_client_data()["confidential_app_client1"]["id"] client_secret = get_client_data()["confidential_app_client1"]["secret"] self.internal_client = globus_sdk.ConfidentialAppAuthClient( client_id, client_secret) token_res = self.internal_client.oauth2_client_credentials_tokens( requested_scopes=self.scopes) token_data = token_res.by_resource_server["transfer.api.globus.org"] self.access_token = token_data["access_token"] self.expires_at = token_data["expires_at_seconds"] self.on_refresh = mock.Mock() self.authorizer = globus_sdk.ClientCredentialsAuthorizer( self.internal_client, scopes=self.scopes, access_token=self.access_token, expires_at=self.expires_at, on_refresh=self.on_refresh) self.tc = globus_sdk.TransferClient(authorizer=self.authorizer)
def authenticate_credentials(self, key): ac = globus_sdk.ConfidentialAppAuthClient(settings.GLOBUS_KEY, settings.GLOBUS_SECRET) try: info = ac.oauth2_token_introspect(key).data pu = info.get('username') if not pu: token_expired() user = User.objects.filter(username=pu).first() if not user: user = User(username=pu, email=info.get('email')) user.save() log.debug('Created user {}, using concierge for the first time' '!'.format(user)) ts = api.models.TokenStore.objects.filter(user=user).first() if not ts: ts = api.models.TokenStore(user=user) ts.tokens = { t['resource_server']: t for t in ac.oauth2_get_dependent_tokens(key).data } ts.save() log.debug('Concierge service authenticated user: {}, ({})' ''.format(user.username, user.email)) return user, key except globus_sdk.exc.AuthAPIError: self.token_expired()
def logout(): """ - Revoke the tokens with Globus Auth. - Destroy the session state. - Redirect the user to the Globus Auth logout page. """ client = globus_sdk.ConfidentialAppAuthClient( app.config['APP_CLIENT_ID'], app.config['APP_CLIENT_SECRET']) # Revoke the tokens with Globus Auth if 'tokens' in session: for token in (token_info['access_token'] for token_info in session['tokens'].values()): client.oauth2_revoke_token(token) # Destroy the session state session.clear() # the return redirection location to give to Globus AUth redirect_uri = url_for('hello', _external=True) # build the logout URI with query params # there is no tool to help build this (yet!) globus_logout_url = ( 'https://auth.globus.org/v2/web/logout' + '?client={}'.format(app.config['APP_CLIENT_ID']) + #'?client={}'.format(app.config['PORTAL_CLIENT_ID']) + '&redirect_uri={}'.format(redirect_uri) + '&redirect_name=Globus Example App') # Redirect the user to the Globus Auth logout page return redirect(globus_logout_url)
def get_globus_access_token_client_credentials(gconfig): # Get secret if os.path.isfile(gconfig["client_secret"]): fd = open(gconfig["client_secret"], 'r') client_secret = fd.read() fd.close() else: print '"' + gconfig[ "client_secret"] + '"' + ' file does not exist. Exit.' sys.exit(1) client_secret = client_secret.rstrip('\n') # Get auth and transfer tokens client = globus_sdk.ConfidentialAppAuthClient(gconfig["client_id"], client_secret) token_response = client.oauth2_client_credentials_tokens() globus_auth_data = token_response.by_resource_server['auth.globus.org'] globus_transfer_data = token_response.by_resource_server[ 'transfer.api.globus.org'] auth_token = globus_auth_data['access_token'] transfer_token = globus_transfer_data['access_token'] return auth_token, transfer_token
def _load_auth_client(): """Create an AuthClient for the portal No credentials are used if the server is not production Returns ------- globus_sdk.ConfidentialAppAuthClient Client used to perform GlobusAuth actions """ _prod = True if _prod: app = globus_sdk.ConfidentialAppAuthClient(GLOBUS_CLIENT, GLOBUS_KEY) else: app = globus_sdk.ConfidentialAppAuthClient("", "") return app
def load_app_client(): # with open(app.config['SENSITIVE_INFO'], 'r') as fr: # vals = json.loads(fr.read()) # app.config['PENDING_KEY'] = vals['PENDING_KEY'] # app.config['IP_WHITE_LIST'] = vals['IP_WHITE_LIST'] app.config[INITIALIZED] = True return globus_sdk.ConfidentialAppAuthClient( app.config['GLOBUS_WEB_APP_CLIENT_ID'], app.config['GLOBUS_WEB_APP_CLIENT_SECRET'])
def setUp(self): """ Creates a ConfidentialAppAuthClient for testing """ super(ConfidentialAppAuthClientIntegrationTests, self).setUp() client_data = get_client_data()["confidential_app_client1"] self.cac = globus_sdk.ConfidentialAppAuthClient( client_id=client_data["id"], client_secret=client_data["secret"])
def globus_portal_client(self): """ Create an Globus Auth ConfidentialAppAuthClient Need a ConfidentialAppAuthClient because the NativeAppClient would require user input, i.e. c/p the token from the website somewhere, which we wont do... for now. """ return globus_sdk.ConfidentialAppAuthClient(self.client_id, self.client_secret)
def do_client_credentials_app_authentication(client_id, client_secret): """ Does a client credential grant authentication and returns a dict of tokens keyed by service name. """ client = globus_sdk.ConfidentialAppAuthClient(client_id=client_id, client_secret=client_secret) token_response = client.oauth2_client_credentials_tokens() return token_response.by_resource_server
def get_dependent_token(scope): cc_app = globus_sdk.ConfidentialAppAuthClient( CONFIG["GLOBUS_CC_APP"], CONFIG["GLOBUS_SECRET"], ) access_token = globus_sdk.ClientCredentialsAuthorizer( scopes=scope, # Deriva scope confidential_client=cc_app).access_token logger.debug(f"Retrieved dependent token for scope '{scope}'") return access_token
def do_client_authentication(client_id, client_secret): """ Does a client authentication and returns a globus transfer token. """ client = globus_sdk.ConfidentialAppAuthClient( client_id, client_secret, ) token_response = client.oauth2_client_credentials_tokens() return (token_response.by_resource_server['transfer.api.globus.org'] ['access_token'])
def gen_groups_client(client_id, client_secret): auth_client = globus_sdk.ConfidentialAppAuthClient(client_id, client_secret) token_response = auth_client.oauth2_client_credentials_tokens( requested_scopes=GROUPS_SCOPE).by_resource_server['nexus.api.globus.org'] authorizer = globus_sdk.AccessTokenAuthorizer(token_response['access_token']) groups_client = globus_sdk.base.BaseClient( 'groups', base_url=GROUPS_API_URL, authorizer=authorizer) return groups_client
def logout(): ''' Clear all provided tokens Authorization Headers with bearer tokens Query parameter 'code' Sessions for web browsers ''' client = globus_sdk.ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET) access_token = session.get('access_token', request.args.get('code', request.headers.get('Authorization') ) ) if access_token is None: return "Please Provide an Access Token to Logout" globus_login = GlobusLoginNode.nodes.get_or_none(accessToken=access_token) if globus_login is not None: globus_details = globus_login.inspected globus_identities = globus_login.identities for desc in globus_details: desc.delete() for identity in globus_identities: identity.delete() globus_login.delete() # clear all identities client.oauth2_revoke_token(access_token) session.update( access_token = None, refresh_token = None, oidc_token = None ) logout_uri = os.environ.get('ROOT_URL')+'/home' # call globus to invalidate tokens globus_logout_url = ( 'https://auth.globus.org/v2/web/logout' + '?client={}'.format(CLIENT_ID) + '&redirect_uri={}'.format(logout_uri) + '&redirect_name=Object Registration Service' ) return redirect(globus_logout_url)
def get_client_secret_authorizer(self): """ Attempts to get an authorizer object that uses a client secret for authentication. Not normally used. :returns: Globus SDK authorizer object """ client = globus_sdk.ConfidentialAppAuthClient(self.CLIENT_ID, self.CLIENT_SECRET) token_response = client.oauth2_client_credentials_tokens() # the useful values that you want at the end of this globus_transfer_data = token_response.by_resource_server[ 'transfer.api.globus.org'] globus_transfer_token = globus_transfer_data['access_token'] return globus_sdk.AccessTokenAuthorizer(globus_transfer_token)
def login(): redirect_uri = url_for('login', _external=True) client = globus_sdk.ConfidentialAppAuthClient( app.config['APP_CLIENT_ID'], app.config['APP_CLIENT_SECRET']) client.oauth2_start_flow(redirect_uri) # If there's no "code" query string parameter, we're in this route # starting a Globus Auth login flow. # Redirect out to Globus Auth if 'code' not in request.args: #Use this for Nexus API #auth_uri = client.oauth2_get_authorize_url(additional_params={"scope": "openid profile email urn:globus:auth:scope:transfer.api.globus.org:all urn:globus:auth:scope:auth.globus.org:view_identities urn:globus:auth:scope:nexus.api.globus.org:groups" }) #Use this for Groups API auth_uri = client.oauth2_get_authorize_url( additional_params={ "scope": "openid profile email urn:globus:auth:scope:transfer.api.globus.org:all urn:globus:auth:scope:auth.globus.org:view_identities urn:globus:auth:scope:groups.api.globus.org:all" }) #auth_uri = client.oauth2_get_authorize_url(additional_params={"scope": "openid profile email urn:globus:auth:scope:transfer.api.globus.org:all urn:globus:auth:scope:auth.globus.org:view_identities" }) #"urn:globus:auth:scope:transfer.api.globus.org:all zzyyxcdid openid email profile"}) return redirect(auth_uri) # If we do have a "code" param, we're coming back from Globus Auth # and can start the process of exchanging an auth code for a token. else: code = request.args.get('code') tokens = client.oauth2_exchange_code_for_tokens(code) # store the resulting tokens in the session session.update(tokens=tokens.by_resource_server, is_authenticated=True) print('client/app token: ' + str( base64.b64encode( bytes( app.config['APP_CLIENT_ID'] + ':' + app.config['APP_CLIENT_SECRET'], 'utf-8')))) tokes = session['tokens'].items() for key, token in tokes: authorizer = globus_sdk.AccessTokenAuthorizer( token['access_token']) print("=============================================") print("-- info for " + key) pprint(vars(authorizer)) return redirect(url_for('hello'))
def __get_globus_user(token): # Using Auth token, get the globus username and return the username # start globus client client_id = app.config['GLOBUS_CLIENT_ID'] client_secret = app.config['GLOBUS_CLIENT_SECRET'] redirect_uri = app.config['GLOBUS_REDIRECT_URI'] client = globus_sdk.ConfidentialAppAuthClient(client_id, client_secret) client.oauth2_start_flow(redirect_uri) # check whether token is active check_result = client.oauth2_validate_token(token) if not check_result['active']: # ???? how how handle this sys.exit('Token not active.') # get username token_info = client.oauth2_token_introspect(token) username = token_info['username'] if '@' in username: username = username[0:username.find('@')] # get and record auth token and transfer token dependent_token_info = client.oauth2_get_dependent_tokens(token) transfer_data = dependent_token_info.by_resource_server[ 'transfer.api.globus.org'] transfer_token = transfer_data['access_token'] auth_data = dependent_token_info.by_resource_server['auth.globus.org'] auth_token = auth_data['access_token'] identifiers_data = dependent_token_info.by_resource_server[ 'identifiers.globus.org'] identifiers_token = identifiers_data['access_token'] def record_token(dir_type, token): dir_name = os.path.join(app.config['GLOBUS_TOKEN_FILES_DIR'], dir_type) if not os.path.isdir(dir_name): os.mkdir(dir_name, mode=0o700) record_file = os.path.join(dir_name, username) with open(record_file, 'w') as write_file: write_file.write(token) record_token('tokens', transfer_token) record_token('tokens-auth', auth_token) record_token('tokens-identifiers', identifiers_token) return username
def load_auth_client(): """Create a Globus Auth client from config info""" return globus_sdk.ConfidentialAppAuthClient( app.config['TS_CLIENT_ID'], app.config['TS_CLIENT_SECRET']) #ddb59aef-6d04-11e5-ba46-22000b92c6ec||/~/Twitter/ #097b8756-83fd-11e8-9536-0a6d4e044368||/~/Desktop/Testing/Twitter #ddb59af0-6d04-11e5-ba46-22000b92c6ec||/~/Twitter #celery worker -A task_server.celery --loglevel=INFO #celery flower -A task_server.celery #./redis-server ../redis.conf #source tutorial-env/bin/activate
def logout(): """ - Revoke the tokens with Globus Auth. - Destroy the session state. - Redirect the user to the Globus Auth logout page. """ logger.debug("Logging user out") try: auth_client = globus_sdk.ConfidentialAppAuthClient( app.config['PORTAL_CLIENT_ID'], app.config['PORTAL_CLIENT_SECRET']) # Revoke the tokens with Globus Auth for token, token_type in ( (token_info[ty], ty) # get all of the token info dicts for token_info in session['tokens'].values() # cross product with the set of token types for ty in ('access_token', 'refresh_token') # only where the relevant token is actually present if token_info[ty] is not None): auth_client.oauth2_revoke_token( token, additional_params={'token_type_hint': token_type}) # Destroy the session state session.clear() redirect_uri = url_for('home', _external=True) ga_logout_url = [] ga_logout_url.append(app.config['GLOBUS_AUTH_LOGOUT_URI']) ga_logout_url.append('?client={}'.format( app.config['PORTAL_CLIENT_ID'])) ga_logout_url.append('&redirect_uri={}'.format(redirect_uri)) ga_logout_url.append('&redirect_name=Globus Sample Data Portal') except Exception as e: logger.error("Unable to logout user: {}".format(repr(e))) flash("Unable to log you out of Globus.") # Redirect the user to the Globus Auth logout page return redirect(''.join(ga_logout_url))
def init_app(self, flask_app): client_id = get_config_param('APP_CLIENT_ID') client_secret = get_config_param('APP_CLIENT_SECRET') self.flask_app = flask_app self.login_manager.init_app(self.flask_app) self.globus_oauth = globus_sdk.ConfidentialAppAuthClient( get_config_param('APP_CLIENT_ID'), get_config_param('APP_CLIENT_SECRET')) self.login_manager.user_loader(self.load_user) self.flask_app.add_url_rule('/login', 'login', self.login) if not AuthHelper.isInitialized(): self.authHelper = AuthHelper.create(clientId=client_id, clientSecret=client_secret) else: self.authHelper = AuthHelper.instance()
def login(): """ Run Oauth2 flow with globus auth """ client = globus_sdk.ConfidentialAppAuthClient(CLIENT_ID, CLIENT_SECRET) login_uri = os.environ.get('ROOT_URL')+'/login' client.oauth2_start_flow( redirect_uri= login_uri, refresh_tokens=True) if 'code' not in request.args: authorize_url = client.oauth2_get_authorize_url() return redirect(authorize_url) else: auth_code = request.args.get('code') try: tokens = client.oauth2_exchange_code_for_tokens(auth_code) except: return Response( response = "Invalid Credentials: Cannot Grant Tokens for an old Authorization Code", status = 401 ) access_token = tokens.data.get('access_token') refresh_token = tokens.data.get('refresh_token') oidc_token = tokens.decode_id_token() session.update( access_token = access_token, oidc_token = oidc_token, refresh_token = refresh_token ) globus_token = GlobusToken(access_token, refresh_token) globus_token.register_token() return 'ACCESS TOKEN: {}'.format(access_token)
def globus_portal_client(self): return globus_sdk.ConfidentialAppAuthClient( self.client_id, self.client_secret)
def get_client(): '''return client to handle authentication''' return globus_sdk.ConfidentialAppAuthClient( settings.SOCIAL_AUTH_GLOBUS_KEY, settings.SOCIAL_AUTH_GLOBUS_SECRET)
def load_app_client(): return globus_sdk.ConfidentialAppAuthClient( current_app.config['APP_CLIENT_ID'], current_app.config['APP_CLIENT_SECRET'])
def load_portal_client(): """Create an AuthClient""" return globus_sdk.ConfidentialAppAuthClient( app.config['PORTAL_CLIENT_ID'], app.config['PORTAL_CLIENT_SECRET'])