def test_request_body(self): client = BackendApplicationClient(self.client_id) # Basic, no extra arguments body = client.prepare_request_body(body=self.body) self.assertFormBodyEqual(body, self.body_up) rclient = BackendApplicationClient(self.client_id) body = rclient.prepare_request_body(body=self.body) self.assertFormBodyEqual(body, self.body_up) # With extra parameters body = client.prepare_request_body(body=self.body, **self.kwargs) self.assertFormBodyEqual(body, self.body_kwargs)
def fetch_token(url, client_id, client_secret): client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url=url, client_id=client_id, client_secret=client_secret) return token
def __init__(self, hostName, port): # Create a socket to the Airavata Server transport = TSocket.TSocket(hostName,port) # Use Buffered Protocol to speedup over raw sockets transport = TTransport.TBufferedTransport(transport) # Airavata currently uses Binary Protocol protocol = TBinaryProtocol.TBinaryProtocol(transport) # Create a Airavata client to use the protocol encoder self.airavataClient = Airavata.Client(protocol) transport.open() client_id = r'XXXXXXXXX' client_secret = r'XXXXXXXXX' client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url='https://idp.scigap.org:9443/oauth2/token', client_id=client_id, client_secret=client_secret) self.authzToken = AuthzToken(token["access_token"]) claimsMap = {"userName":"******","gatewayID": "Ultrascan_Production"} self.authzToken.claimsMap = claimsMap self.gateWayId = "default" print (self.airavataClient.getAPIVersion(self.authzToken))
def get_access_token(base_url, client_id, client_secret): client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url=base_url + '/api/oauth/token', client_id=client_id, client_secret=client_secret) return token['access_token']
def oauth2_backend(token_url, client_id, client_secret): oauthclient = BackendApplicationClient(client_id=client_id) oauthsession = OAuth2Session(client=oauthclient) token = oauthsession.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret) return OAuth2Session(client_id=client_id, token=token)
def fetch_access_token(self, client_id, client_secret, access_token_path): """ """ print("Generating new access token...") access_token_url = f'{self.base_url}/oauth/access_token' auth = requests.auth.HTTPBasicAuth(client_id, client_secret) client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) access_token_dict = oauth.fetch_token(token_url=access_token_url, auth=auth) # calculate expiration datetime expires_in = int(access_token_dict['expires_in']) created_datetime = datetime.datetime.utcnow() expiration_datetime = created_datetime + datetime.timedelta( seconds=expires_in) expiration_timestamp = expiration_datetime.strftime( '%Y-%m-%d %H:%M:%S.%f') access_token_dict['expiration_timestamp'] = expiration_timestamp # save access token for future use if not os.path.exists(access_token_path): print(f"Creating folder {access_token_path}") os.makedirs(access_token_path) access_token_file = f'{access_token_path}/access_token.json' with open(access_token_file, 'w+') as f: json.dump(access_token_dict, f) return access_token_dict
def _getAccessToken(client_id, client_secret, token_url): client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token_res = oauth.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret) return token_res
def __init__(self, client_id=None, client_secret=None): if client_id is None: client_id = os.environ.get("SH_CLIENT_ID") if client_id is None: raise Exception("client id missing") if client_secret is None: client_secret = os.environ.get("SH_CLIENT_SECRET") if client_secret is None: raise Exception("client secret missing") shub_dir = os.path.join(os.path.expanduser("~"), ".sentinelhub") token_file = os.path.join(shub_dir, f"{client_id}.json") cached_token = None if not os.path.exists(shub_dir): os.mkdir(shub_dir) elif os.path.exists(token_file): with open(token_file) as fhandle: cached_token = json.load(fhandle) self.oauth = OAuth2Session(client=BackendApplicationClient( client_id=client_id, token=cached_token)) token = self.oauth.fetch_token(token_url=TOKEN_URL, client_id=client_id, client_secret=client_secret) if (cached_token is None or cached_token["access_token"] != token["access_token"]): with open(token_file, "w") as fhandle: json.dump(token, fhandle)
def _fetch_token(self, force=False): if (not self.access_token is None) and (not force): return auth = HTTPBasicAuth(self.app_id, self.app_key) app_client = BackendApplicationClient(client_id=self.app_id) oauth = OAuth2Session(client=app_client) try: token = oauth.fetch_token(token_url=self.endpoint + "/oauth/token", auth=auth) except Exception as err: self.access_token = None self.logger.error("OAuth failed: " + str(err)) raise ArgesError("OAuth failed: " + str(err)) else: self.access_token = token["access_token"] if self.access_token is None: raise ArgesError("Unauthorized") self.ses.headers.update( {"Authorization": "Bearer " + self.access_token}) self.expires_in = datetime.timedelta(seconds=token["expires_in"]) self.expires_at = datetime.datetime.fromtimestamp( token["expires_at"]) self.logger.debug("OAuth success: " + self.access_token) self.logger.debug(" expires in %d seconds" % self.expires_in.total_seconds()) self.logger.debug(" expires at %s" % self.expires_at.strftime("%Y-%m-%d %H:%M:%S"))
def create_client(self, type_client='app'): """ Create the client http://arxiv.org/pdf/1304.6257.pdfwith the auth keys. Works differently if it is app_only or user_auth Params: *type_client: app, user """ client_key = self.twitter_keys['CONSUMER_KEY'] client_secret = self.twitter_keys['CONSUMER_SECRET'] try: if type_client == 'user': token_access = self.twitter_keys['ACCESS_TOKEN'] token_secret = self.twitter_keys['ACCESS_TOKEN_SECRET'] client = OAuth1Session(client_key, client_secret=client_secret, resource_owner_key=token_access, resource_owner_secret=token_secret) return client elif type_client == 'app': TOKEN_URL = 'https://api.twitter.com/oauth2/token' client = BackendApplicationClient(client_id=client_key) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url=TOKEN_URL, client_id=client_key, client_secret=client_secret) return oauth except AttributeError: logger.critical('No Keys to connect, check the file') raise "No Keys to connect, check the file"
def test_scopes(): resp = requests.get(base_url + "/okapi/dummy/v1/direct") assert resp.text == 'success' resp = manage_client.get(base_url + "/okapi/account/v1/client_id") client_id = resp.json()["client_id"] api_client = OAuth2Session(client=BackendApplicationClient( client_id=client_id)) api_client.fetch_token(token_url, client_id=client_id) assert requests.get(base_url + "/okapi/dummy/v1/api").status_code == 401 assert api_client.get(base_url + "/okapi/dummy/v1/api").text == 'success' assert manage_client.get(base_url + "/okapi/dummy/v1/api").status_code == 401 assert admin_client.get(base_url + "/okapi/dummy/v1/api").status_code == 401 assert api_client.get(base_url + "/okapi/dummy/v1/manage").status_code == 401 assert manage_client.get(base_url + "/okapi/dummy/v1/manage").text == "success" assert admin_client.get(base_url + "/okapi/dummy/v1/manage").status_code == 401 assert api_client.get(base_url + "/okapi/dummy/v1/admin").status_code == 401 assert manage_client.get(base_url + "/okapi/dummy/v1/admin").status_code == 401 assert admin_client.get(base_url + "/okapi/dummy/v1/admin").text == "success" assert admin_client.get(base_url + "/okapi/dummy/v1/register").text == "success" assert admin_client.get(base_url + "/okapi/account/v1/client_id").status_code == 401
def retrieve_token(self): # Checks cache for OAuth token; if none, request new one self.client = BackendApplicationClient(client_id=self.clientid) self.basic_auth = HTTPBasicAuth(self.clientid, self.clientpass) self.oauth = OAuth2Session(client=self.client) self.cached_token = cache.get('cached_token') if not self.cached_token: print("Get new token") token = self.oauth.post(self.token_url, auth=self.basic_auth, data=self.token_url_params) try: token_content = json.loads(token.content) self.auth_token = token_content["access_token"] except json.JSONDecodeError as e: raise ValueError(e) try: token_expires_in = token_content['expires_in'] print(str(token_expires_in)) except Exception as e: raise e try: cache.set('cached_token', self.auth_token, timeout=(token_expires_in - 500)) except Exception as e: raise e else: print("Use cached token") self.auth_token = self.cached_token
def get_access_token(self): client_id="C30ifzyuaWQ3HLycDk1eN5meqoUi7M6YIy3eKiW6" client = BackendApplicationClient(client_id=client_id) client_secret = "gf8zNeFDb275uxN9c7Vzsyh9hq3ATgVVL0lGbziVAqAS72DHZtMEPxNrkGRpMm6ZBrEGZasep8d51TzqxPzdHtQTVZF4AsYwB24U4WCfwQpDgE3heOV5KFKnSN63ulAm" oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url="https://dt.vnct.xyz/api/token/", client_id=client_id, client_secret=client_secret) return token["access_token"]
def acquire_token(self): token_url = 'https://' + self.host + '/oauth2/token' client = BackendApplicationClient(client_id=self.clientId) oauth = OAuth2Session(client=client) self.token = oauth.fetch_token(token_url=token_url, client_id=self.clientId, client_secret=self.clientSecret)
def get_oauth_session(self): known_state = session.get(AUTH_STATE_KEY) redirect_url = urljoin(request.url_root, self.redirect_path) if self.grant_type and self.grant_type == CLIENT_CREDENTIALS_GRANT_TYPE: client = BackendApplicationClient(client_id=self.client_id) oauth_session = OAuth2Session(client=client, token=session.get(AUTH_TOKEN_KEY)) elif self.grant_type and self.grant_type == IMPLICIT_GRANT_TYPE: client = MobileApplicationClient(self.client_id) client.response_type = self.config.get(RESPONSE_TYPE_CONFIG) oauth_session = OAuth2Session( client_id=self.client_id, state=known_state, scope=self.config.get(SCOPE_CONFIG).split(), redirect_uri=redirect_url, client=client, token=session.get(AUTH_TOKEN_KEY)) else: client = WebApplicationClient(self.client_id) oauth_session = OAuth2Session( client_id=self.client_id, state=known_state, scope=self.config.get(SCOPE_CONFIG).split(), redirect_uri=redirect_url, client=client, token=session.get(AUTH_TOKEN_KEY)) return oauth_session
def fetch_token(self): oauth = OAuth2Session(client=BackendApplicationClient( client_id=self.key)) token = oauth.fetch_token(token_url='https://api.awhere.com/oauth/token',\ client_id=self.key, client_secret=self.secret) client = OAuth2Session(self.key, token=token) return client
def setUp(self): self.token = { "token_type": "Bearer", "access_token": "asdfoiw37850234lkjsdfsdf", "refresh_token": "sldvafkjw34509s8dfsdf", "expires_in": 3600, "expires_at": fake_time + 3600, } # use someclientid:someclientsecret to easily differentiate between client and user credentials # these are the values used in oauthlib tests self.client_id = "someclientid" self.client_secret = "someclientsecret" self.user_username = "******" self.user_password = "******" self.client_WebApplication = WebApplicationClient(self.client_id, code=CODE) self.client_LegacyApplication = LegacyApplicationClient(self.client_id) self.client_BackendApplication = BackendApplicationClient( self.client_id) self.client_MobileApplication = MobileApplicationClient(self.client_id) self.clients = [ self.client_WebApplication, self.client_LegacyApplication, self.client_BackendApplication, ] self.all_clients = self.clients + [self.client_MobileApplication]
def get_tiles_data(munic=261): TOKEN_URL = 'https://consent.swisscom.com/o/oauth2/token' client_id = 'IIq31EHYARZAqE4ur4ndbRGsVZTKGv5v' client_secret = 'WsmE3OAyjOd75d7Y' # See https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow. client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) # Fetch an access token. oauth.fetch_token(token_url=TOKEN_URL, client_id=client_id, client_secret=client_secret) # To print token, uncomment the following line #print(oauth.access_token) # Use the access token to query an endpoint. resp = oauth.get( 'https://api.swisscom.com/layer/heatmaps/demo/grids/municipalities/{0}' .format(munic), headers={'scs-version': '2'}) return (resp)
def make_session(self): token = self._get_token() client = BackendApplicationClient(client_id=self._config["oauth2"]["client_id"]) session = OAuth2Session(client=client, token=token) session.headers = self._config["headers"] session.verify = do_verify_ssl return session
def get_density_data(date, formatted_ids): # formatted_ids needs to be a list (output of format_ids) data = [] for i in range(len(formatted_ids)): TOKEN_URL = 'https://consent.swisscom.com/o/oauth2/token' client_id = 'uFdtRJaDao6ATC2kW4WPLCkm2Ywb3Cjg' client_secret = '98wsTlX4ou7n1CrD' # See https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow. client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) # Fetch an access token. oauth.fetch_token(token_url=TOKEN_URL, client_id=client_id, client_secret=client_secret) # To print token, uncomment the following line #print(oauth.access_token) # Use the access token to query an endpoint. resp = oauth.get( 'https://api.swisscom.com/layer/heatmaps/demo/heatmaps/dwell-density/hourly/{0}{1}' .format(date, formatted_ids[i]), headers={'scs-version': '2'}) output = resp.json()['tiles'] for key_val in output: key_val['time'] = date data.append(output) print(i) return (data)
def get_session(self, *, state=None, redirect_uri=None, load_token=False, scopes=None): """ Create a requests Session object :param str state: session-state identifier to rebuild OAuth session (CSRF protection) :param str redirect_uri: callback URL specified in previous requests :param list(str) scopes: list of scopes we require access to :param bool load_token: load and ensure token is present :return: A ready to use requests session, or a rebuilt in-flow session :rtype: OAuth2Session """ redirect_uri = redirect_uri or self.oauth_redirect_url client_id = self.auth[0] if self.auth_flow_type in ('authorization', 'public'): oauth_client = WebApplicationClient(client_id=client_id) elif self.auth_flow_type == 'credentials': oauth_client = BackendApplicationClient(client_id=client_id) else: raise ValueError('"auth_flow_type" must be "authorization", "credentials" or "public"') requested_scopes = scopes or self.scopes if load_token: # gets a fresh token from the store token = self.token_backend.get_token() if token is None: raise RuntimeError('No auth token found. Authentication Flow needed') oauth_client.token = token if self.auth_flow_type in ('authorization', 'public'): requested_scopes = None # the scopes are already in the token (Not if type is backend) session = OAuth2Session(client_id=client_id, client=oauth_client, token=token, scope=requested_scopes) else: session = OAuth2Session(client_id=client_id, client=oauth_client, state=state, redirect_uri=redirect_uri, scope=requested_scopes) session.verify = self.verify_ssl session.proxies = self.proxy if self.request_retries: retry = Retry(total=self.request_retries, read=self.request_retries, connect=self.request_retries, backoff_factor=RETRIES_BACKOFF_FACTOR, status_forcelist=RETRIES_STATUS_LIST) adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter) session.mount('https://', adapter) return session
def _get_token(self): """Get an API token. Raises: AuthenticationError: if getting token fails. """ client = BackendApplicationClient(client_id=CLIENT_ID) oauth = OAuth2Session(client=client) # Retry auth if error (to get around intermittent failures) latest_exception = None for i in range(3): try: token = oauth.fetch_token(token_url=AUTH_URL, client_id=CLIENT_ID, client_secret=CLIENT_SECRET) self.__token = token["access_token"] self.__session = oauth self._me = None return except (AccessDeniedError, InvalidClientError, MissingTokenError) as e: latest_exception = e continue raise AuthenticationError( "Failed to get authentication token: {0}".format(latest_exception))
def __init__(self, studio_url, config): self.studio_url = studio_url self.client_oauth_key = config['oauth_key'] self.client_oauth_secret = config['oauth_secret'] self.client = BackendApplicationClient(client_id=self.client_oauth_key) self.session = OAuth2Session(client=self.client) self.token_url = config['lms_oauth2_url'] + '/access_token'
def oauth2NotAuthorizedSession(self): if self.consumer_key == None or\ self.consumer_secret == None or\ self.bearer_token == None: raise RuntimeError('Not Avaliable Consumer!') client = BackendApplicationClient(client_id=self.consumer_key) return OAuth2Session(client=client)
def get_request_headers(self): """ Return a dict containing common request headers. It obtains a bearer token using the client_id and client_secret key pair and then it will return this token to make authenticated requests. Returns: Dict that contains common request HTTP headers. """ client_id = self.settings.get('OPEN_EDX_OAUTH_CLIENT_ID', '') client_secret = self.settings.get('OPEN_EDX_OAUTH_CLIENT_SECRET', '') token_url = '{lms_url}{token_url}'.format( lms_url=self.settings.get('LMS_URL', ''), token_url=self.settings.get('OPEN_EDX_OAUTH_TOKEN_URL', ''), ) if not self.token: oauth = OAuth2Session( client=BackendApplicationClient(client_id=client_id), ) self.token = oauth.fetch_token( token_url=token_url, client_id=client_id, client_secret=client_secret, ) return { 'Authorization': '{token_type} {token}'.format( token_type=self.token.get('token_type', ''), token=self.token.get('access_token', ''), ), 'Content-Type': 'application/json', }
def get_authorization_token(self, client_credentials, tenant_id, username=None): """ This method created a authorization token for the user or a service account In case of a service account username will be null :param client_credentials: object of class client_credentials :param tenant_id: gateway id of the client :param username: username of the user for which authorization token is being created :return: AuthzToken """ client = BackendApplicationClient( client_id=client_credentials.client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token( token_url=self.keycloak_settings.KEYCLOAK_TOKEN_URL, client_id=client_credentials.client_id, client_secret=client_credentials.client_secret, verify=client_credentials.verify_ssl) access_token = token.get('access_token') return AuthzToken(accessToken=access_token, claimsMap={ 'gatewayID': tenant_id, 'userName': username })
def connect(self): """ Sets up the HTTP session to talk to Twitter. If one is active it is closed and another one is opened. """ if not (self.consumer_key and self.consumer_secret and self.access_token and self.access_token_secret): raise RuntimeError("MissingKeys") if self.client: log.info("closing existing http session") self.client.close() if self.last_response: log.info("closing last response") self.last_response.close() log.info("creating http session") if not self.app_auth: logging.info('creating OAuth1 user authentication') self.client = OAuth1Session( client_key=self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.access_token, resource_owner_secret=self.access_token_secret) else: logging.info('creating OAuth2 app authentication') client = BackendApplicationClient(client_id=self.consumer_key) oauth = OAuth2Session(client=client) token = oauth.fetch_token( token_url='https://api.twitter.com/oauth2/token', client_id=self.consumer_key, client_secret=self.consumer_secret) self.client = oauth
def _login(self) -> None: """ Checks to see if a Oauth2 Session exists, if not builds a session and retrieves the token from the config file, if no token in config file, fetch a new one. :return: None """ # Does session exist? if not hasattr(self, 'OAuth2Session'): client = BackendApplicationClient(client_id=self._client_id) self.OAuth2Session = OAuth2Session(client=client, client_id=self._client_id) self.OAuth2Session.headers.update({ "User-Agent": self._headers, 'Content-Type': 'application/json' }) with open('AccessToken.txt', 'w+') as file: token = file.read() if token == '': self._refresh_token() else: self.OAuth2Session.token = token else: self._refresh_token() # Logout on exit if self._logout_on_exit: atexit.register(self._logout)
def _obtain_oauth_token(url, client_id, client_secret): logger.debug('Getting OAuth token from {}'.format(url)) client = BackendApplicationClient(client_id) oauth_session = OAuth2Session(client=client) token_url = '{}/oauth2/token/'.format(url) try: res = oauth_session.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret) except InvalidClientError: logger.error( "Cannot obtain the token from {}. Invalid client".format(url)) return None except requests.exceptions.ConnectionError as e: logger.error(traceback.format_exc()) logger.error( "Cannot obtain the token from {}. Connection error".format( url)) return None if 'access_token' in res: logger.debug('Token obtained') return oauth_session else: logger.debug('Error obtaining token') return None
def start_api (): UID = os.environ['CUID'] SECRET = os.environ['SECRET'] cliente = BackendApplicationClient(client_id = UID) api = OAuth2Session(client=cliente) token = api.fetch_token(token_url='https://api.intra.42.fr/oauth/token', client_id=UID, client_secret=SECRET) return (token)