def getAccessToken(param): """Fetch access token from B2ACCESS""" if param.verbose == True: print "\nFetching access token from B2ACCESS" """ Pre-req: Create a user 'argo' with password 'test' in group 'oauth-clients' and 'eudat:b2share' or any other """ try: client = BackendApplicationClient(client_id=username) client.prepare_request_body(scope=['profile','email','GENERATE_USER_CERTIFICATE']) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url=str(param.url)+TOKEN_URI, verify=False,client_id=str(param.username),client_secret=str(param.password),scope=['USER_PROFILE','GENERATE_USER_CERTIFICATE']) j = json.dumps(token, indent=4) k = json.loads(j) if param.verbose: print "Access token: "+k['access_token'] getTokenInfo(str(param.url)+'/oauth2/tokeninfo', str(k['access_token']), param.verbose) getUserInfo(str(param.url)+'/oauth2/userinfo', str(k['access_token']), param.verbose) except ConnectionError as e: print "CRITICAL: Invalid Unity URL: {0}".format(e) sys.exit(2) except MissingTokenError as e: print "CRITICAL: Invalid client Id and/or secret: {0}".format(e.description) sys.exit(2) except TypeError as e: print e sys.exit(2) except: print("CRITICAL: Error fetching OAuth 2.0 access token:", sys.exc_info()[0]) sys.exit(2) raise
def test_parse_token_response(self): client = BackendApplicationClient(self.client_id) # Parse code and state response = client.parse_request_body_response(self.token_json, scope=self.scope) self.assertEqual(response, self.token) self.assertEqual(client.access_token, response.get("access_token")) self.assertEqual(client.refresh_token, response.get("refresh_token")) self.assertEqual(client.token_type, response.get("token_type")) # Mismatching state self.assertRaises(Warning, client.parse_request_body_response, self.token_json, scope="invalid") os.environ["OAUTHLIB_RELAX_TOKEN_SCOPE"] = "3" token = client.parse_request_body_response(self.token_json, scope="invalid") self.assertTrue(token.scope_changed) scope_changes_recorded = [] def record_scope_change(sender, message, old, new): scope_changes_recorded.append((message, old, new)) signals.scope_changed.connect(record_scope_change) try: client.parse_request_body_response(self.token_json, scope="invalid") self.assertEqual(len(scope_changes_recorded), 1) message, old, new = scope_changes_recorded[0] self.assertEqual(message, 'Scope has changed from "invalid" to "/profile".') self.assertEqual(old, ["invalid"]) self.assertEqual(new, ["/profile"]) finally: signals.scope_changed.disconnect(record_scope_change) del os.environ["OAUTHLIB_RELAX_TOKEN_SCOPE"]
def test_parse_token_response(self): client = BackendApplicationClient(self.client_id) # Parse code and state response = client.parse_request_body_response(self.token_json, scope=self.scope) self.assertEqual(response, self.token) self.assertEqual(client.access_token, response.get("access_token")) self.assertEqual(client.refresh_token, response.get("refresh_token")) self.assertEqual(client.token_type, response.get("token_type")) # Mismatching state self.assertRaises(Warning, client.parse_request_body_response, self.token_json, scope="invalid")
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 connect(self): """ Sets up the HTTP session to talk to Twitter. If one is active it is closed and another one is opened. """ if self.last_response: self.last_response.close() if self.client: self.client.close() if self.auth_type == "application" and self.bearer_token: log.info('Creating HTTP session headers for app auth.') self.client = requests.Session() self.client.headers.update( {"Authorization": f"Bearer {self.bearer_token}"}) elif self.auth_type == "application": log.info('Creating app auth client via OAuth2') client = BackendApplicationClient(client_id=self.consumer_key) self.client = OAuth2Session(client=client) self.client.fetch_token( token_url='https://api.twitter.com/oauth2/token', client_id=self.consumer_key, client_secret=self.consumer_secret) else: log.info('creating user auth client') 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)
def get(self, request): """Endpoint for OAuth 2.0 Authorization Code flow Receive redirected response from Authorization Server (Fitbit) with Authorization Code. Then exchange Authorization Code for Access Token. To complete sing-up/sing-in flow make request to convert-token endpoint and returns Django token """ try: authorization_code = request.query_params['code'] except KeyError: error_msg = 'Missing required query parameters' logger.error(error_msg) return response.Response( status=status.HTTP_422_UNPROCESSABLE_ENTITY, data={'message': error_msg}) fitbit_access_token_url = settings.SOCIAL_AUTH_FITBIT_ACCESS_TOKEN_URL fitbit_client_id = settings.SOCIAL_AUTH_FITBIT_KEY fitbit_client_secret = settings.SOCIAL_AUTH_FITBIT_SECRET fitbit_app_client = BackendApplicationClient( client_id=fitbit_client_id) fitbit_oauth_session = OAuth2Session(client=fitbit_app_client) access_token = fitbit_oauth_session.fetch_token( token_url=fitbit_access_token_url, client_id=fitbit_client_id, client_secret=fitbit_client_secret, code=authorization_code) # TODO sign up with access_token and django-rest-framework-social-oauth2 return response.Response(status=status.HTTP_200_OK)
def login(self): if self.client and self.token: return True credentials = { 'client_id': self.client_id or sickrage.app.config.api_client_id, 'client_secret': self.client_secret or sickrage.app.config.api_client_secret } oauth = OAuth2Session(client=BackendApplicationClient( client_id=credentials['client_id'])) try: self.token = oauth.fetch_token(token_url=self.token_url, timeout=30, **credentials) self.client = OAuth2Session(credentials['client_id'], token=self.token, auto_refresh_url=self.token_url, auto_refresh_kwargs=credentials, token_updater=self.token_saver) return True except Exception as e: pass
def buffer_post(profile, content, url): parser = ConfigParser() parser.read("whconfig.ini") client_id = parser.get('BUFFER', 'client_id') buffer_access = parser.get('BUFFER', 'access') buffer_profile = parser.get('BUFFER', profile) client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(token=buffer_access, client=client) auth_code = oauth.token if profile == 'twitter': requests.post( "https://api.bufferapp.com/1/updates/create.json?access_token=" + auth_code, data={ 'profile_ids': buffer_profile, 'text': content + ' ' + url, 'now': 1 }) if profile == 'facebook': requests.post( "https://api.bufferapp.com/1/updates/create.json?access_token=" + auth_code, data={ 'profile_ids': buffer_profile, 'text': content + ' ' + url, 'link': url, 'now': 1 })
def fetch_access_token(self, code=None): """ Retrieves an OAuth2 access token. If `code` is not specified, the client_credentials grant type will be used based on the client_id and client_secret. If `code` is not None, an authorization_code grant type will be used. :param code: optional code value obtained via an authorization grant :return: the client application's token information as a dictionary """ refresh_url = self.token_url if self.auto_refresh else None if code is None: self.api_client = OAuth2Session( self.client_id, client=BackendApplicationClient(self.client_id), auto_refresh_url=refresh_url, token_updater=self.token_refresh_callback, auto_refresh_kwargs={ 'client_id': self.client_id, 'client_secret': self.client_secret }) self.token = self.api_client.fetch_token( self.token_url, client_id=self.client_id, client_secret=self.client_secret) else: self.code = code self.initialize_auth_api_client(refresh_url) self.token = self.api_client.fetch_token( self.token_url, code=code, client_id=self.client_id, client_secret=self.client_secret, scope=self.scope) return self.token
def __init__(self, client_id, secret, **kwargs): super(ServicePrincipalCredentials, self).__init__(client_id, None) self._configure(**kwargs) self.secret = secret self.client = BackendApplicationClient(self.id) self.get_token()
def get_animexx_json(endpoint): try: oauth_client = OAuth2Session(animexx_client_id, token={ 'access_token': animexx_access_token, 'token_type': 'Bearer' }) r = oauth_client.get(endpoint) except TokenExpiredError as e: print("Token expired") client = BackendApplicationClient(client_id=animexx_client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url=animexx_token_url, auth=False, client_id=animexx_client_id, client_secret=animexx_client_secret) config.set('Animexx', 'access_token', token) with open('config.ini', 'wb') as configfile: config.write(configfile) oauth_client = OAuth2Session(animexx_client_id, token={ 'access_token': token, 'token_type': 'Bearer' }) r = oauth_client.get(endpoint) return r.json()
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='asdf345xdf') 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 __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'XXXXXXXXXX' client_secret = r'XXXXXXXXXXX' 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 = "Ultrascan_Production" print self.airavataClient.getAPIVersion(self.authzToken)
def authenticate(self): # Read API credentials api_credentials = ConfigParser() api_credentials.read(API_CREDENTIALS_PATH) api_credentials = api_credentials[self.api_name] # API key authentication if self.authentication_method == "key": # Retrieve API key self.api_key = api_credentials.get("key") # Oauth 2.0 authentication elif self.authentication_method == "oauth2": # Retrieve API credentials client_id = api_credentials.get("client_id") client_secret = api_credentials.get("client_secret") # Initialize OAuth 2.0 session client = BackendApplicationClient(client_id=client_id) session = OAuth2Session(client=client) # Fetch token raw_token = session.fetch_token( token_url=self.token_url, client_id=client_id, client_secret=client_secret, ) access_token = raw_token["access_token"] token_type = raw_token["token_type"] # Update authentication header self.headers["Authorization"] = f"{token_type} {access_token}"
def __init__(self): super().__init__( request_formatter=JsonRequestFormatter, ) oauth = OAuth2Session( client=BackendApplicationClient(settings.HMRC["client_id"]), scope=[ "write:transfer-complete", "write:transfer-ready", ], ) params = dict( token_url="{base_url}{token_url}".format(**settings.HMRC), client_id=settings.HMRC["client_id"], client_secret=settings.HMRC["client_secret"], include_client_id=True, scope=[ "write:transfer-complete", "write:transfer-ready", ], ) oauth.fetch_token(**params) self.set_session(oauth) self.srn = settings.HMRC["service_reference_number"]
def __init__(self, key, secret): client = BackendApplicationClient(client_id=key) self.oauth = OAuth2Session(client=client) # token = oauth.fetch_token(token_url='https://secure.splitwise.com/oauth/token', auth=auth) token = self.oauth.fetch_token( token_url='https://secure.splitwise.com/oauth/token', client_id=key, client_secret=secret) self.user_info = self.oauth.get( "https://secure.splitwise.com/api/v3.0/get_current_user").json() # data.next() # skip the header row # data = [MoneyLoverEntry(d) for d in data if d[7] == "No" and float(d[2]) < 0] # self.by_date = defaultdict(list) # self.by_keyword = defaultdict(list) # self.by_amount = defaultdict(list) # for entry in data: # d = entry.data # self.by_date[entry.date()].append(entry) # self.by_amount[entry.amount_owed()].append(entry) # keywords = map(lambda k: k.lower(), entry.details().split(" ")) # for k in keywords: # if k and k not in MoneyLoverEntry.method_hints and k not in ("and", "the"): # self.by_keyword[k].append(entry) self.loaded = None super(Splitwise, self).__init__([], Source.IOU)
def get_client(): 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 oauth
def sierra_session(client_id, client_secret, base_url): auth = HTTPBasicAuth(client_id, client_secret) client = BackendApplicationClient(client_id=client_id) session = OAuth2Session(client=client) session.fetch_token(token_url=base_url + 'token', auth=auth) return session
def get_token(): client = BackendApplicationClient(client_id=_client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token(token_url='https://provider.com/oauth2/token', client_id=_client_id, client_secret=_client_secret) return token
def main(client_id, client_secret, collection_id): client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token( token_url="https://services.sentinel-hub.com/oauth/token", client_id=client_id, client_secret=client_secret, ) def get_paginated_tiles(url): response = oauth.get(url) response.raise_for_status() paginated_tiles = json.loads(response.text) return paginated_tiles["data"], paginated_tiles["links"].get("next") def get_tile_iterator(collection_id): url = f"{byoc_service_base_url}/collections/{collection_id}/tiles" while url is not None: tiles, url = get_paginated_tiles(url) for tile in tiles: yield tile tiles = get_tile_iterator(collection_id) for tile in tiles: if tile["status"] != "INGESTED": continue print(tile['id'])
def _fetch_access_token(self): """Fetch a new access token from the provider""" client_id = self.provider.api_authentication["client_id"] client_secret = self.provider.api_authentication["client_secret"] client = BackendApplicationClient(client_id=client_id) session = OAuth2Session(client=client) # The URL to fetch the token maybe on another base URL token_url = self.provider.oauth2_url if not token_url: token_url = urllib.parse.urljoin(self.provider.base_api_url, "/oauth2/token") if self.provider.api_configuration.get("trailing_slash"): token_url += "/" # Provider-specific parameters to request the token kwargs = {} try: kwargs.update(self.provider.api_configuration["token_params"]) except KeyError: pass token = session.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret, **kwargs) return token
def get_from_twitch(self, operation): client = BackendApplicationClient(client_id=self.client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token( token_url='https://id.twitch.tv/oauth2/token', client_id=self.client_id, client_secret=self.client_secret, include_client_id=True) url = 'https://api.twitch.tv/helix/' + operation response = oauth.get(url, headers={ 'Accept': 'application/json', 'Client-ID': self.client_id }) info = None if response.status_code != 200: raise ValueError( 'Request to twitch returned an error {}, the response is:\n{}'. format(response.status_code, response.text)) try: info = json.loads(response.content) # print(json.dumps(info, indent=4, sort_keys=True)) except Exception as e: print(e) return info
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 get_authenticated_session(): """ This gets the proper credentials and tokens to query the Spotify API, according to the `Spotify guide`_ and the guide from requests_oauthlib_. .. _Spotify guide: https://developer.spotify.com/documentation/general/guides/authorization-guide/#client-credentials-flow .. _requests_oauthlib: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#backend-application-flow :return: The authenticated OAuth session – use as you would `requests` """ # set up the authentication auth = HTTPBasicAuth(SPOTIFY_CREDENTIALS['client_id'], SPOTIFY_CREDENTIALS['client_secret']) # Define the client based on the credentials client = BackendApplicationClient(**SPOTIFY_CREDENTIALS) # Set up the session session = OAuth2Session(client=client) # Get the token to use in this session session.fetch_token(token_url='https://accounts.spotify.com/api/token', auth=auth, data={'grant_type': 'client_credentials'}) return session
def get_client_cred_oauth_credentials(client_id: str, client_secret: str, configs: Configs) -> OAuthCredentials: """ Run the OAuth workflow to get credentials for a machine user. :param client_id: The client_id of the machine user to authenticate as. :param client_secret: The client_secret of the machine user to authenticate as. :param configs: Configs instance. :return: OAuth credentials for the given machine user. """ client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) token = oauth.fetch_token( token_url=f"https://{configs.AUTH_DOMAIN}/v1/token", client_id=client_id, client_secret=client_secret, scope=configs.CLIENT_CREDENTIALS_SCOPE, ) access_token = token.get("access_token") expires_in = token.get("expires_in") if not access_token or not expires_in: raise ValueError( "Could not get access token or expires_in data about access token") return OAuthCredentials( access_token=access_token, expires_in=expires_in, created_time=datetime.now(), user_name=configs.CLIENT_CREDENTIALS_USER_NAME, )
def _initialize(self): """Initialize/reinitialize client libraries.""" with self._init_lock: self.auth = HTTPBasicAuth(self.consumer_key, self.consumer_secret) self.client = BackendApplicationClient(client_id=self.consumer_key) self.oauth = OAuth2Session(client=self.client) self.update_token()
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 get_access_token(token_url, client_id, client_secret): client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) access_data = oauth.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret) return access_data["access_token"]
def get_access_token(): auth = HTTPBasicAuth(TWITTER_KEY, TWITTER_SECRET) client = BackendApplicationClient(client_id=TWITTER_KEY) oauth = OAuth2Session(client=client) token_response = oauth.fetch_token(token_url=TWITTER_TOKEN_URL, auth=auth) return token_response["access_token"]
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_access_token(self, attempt=0): """ Connects to the TOKEN_URL endpoint to retrieve a token. """ # TODO: add logic to sleep for X seconds if # expires_in < X seconds required to process a batch log.debug('Call get_access_token(attempt={})'.format(attempt)) client_id = self.config.get('CLIENT_ID') client_secret = self.config.get('CLIENT_SECRET') client = BackendApplicationClient(client_id) olass = OAuth2Session(client=client) try: token = olass.fetch_token( token_url=self.config.get('TOKEN_URL'), client_id=client_id, client_secret=client_secret, verify=self.config.get('VERIFY_SSL_CERT', False)) if token.get('expires_in') == 0: if attempt < TOKEN_REQUEST_ATTEMPTS: log.warn("Got an expired token. Re-trying attempt {}..." .format(attempt)) return self.get_access_token(attempt + 1) else: sys.exit("Give up after {} attempts to get a token" .format(TOKEN_REQUEST_ATTEMPTS)) except Exception as exc: log.error("get_access_token() problem due: {}".format(exc)) raise exc return token
def get_token(self): """ If needed fetch a (new) token from the oidc provider. The threshold for fetching a new token is 1 minute before expiration. :return: dict """ if not all([ self.oidc_client_id, self.oidc_client_secret, self.oidc_token_uri ]): logger.warning("Auth disabled due to missing parameters!") return thresh = datetime.now() + timedelta(minutes=1) if self._token is None or self._token["expires_at_dt"] <= thresh: client = BackendApplicationClient(client_id=self.oidc_client_id) oauth = OAuth2Session(client=client) self._token = oauth.fetch_token( token_url=self.oidc_token_uri, client_id=self.oidc_client_id, client_secret=self.oidc_client_secret, ) self._token["expires_at_dt"] = datetime.utcfromtimestamp( int(self._token["expires_at"])) return self._token
def __init__(self, client_id=None, target_user=None): global token cfg = config.Config() self.client_id = cfg["client_id"] logger.debug( f"Creating twitch API client for {self.client_id} {target_user}") self.target_user = target_user self.channel_id = None self.channel_emotes_cache = {} self.global_badges = {} if not token: logger.warning("No token - retriving new token") body = urllib.parse.urlencode({ 'client_id': self.client_id, 'client_secret': cfg["secret"] }) client = BackendApplicationClient(client_id=cfg["client_id"]) oauth = OAuth2Session(client=client) try: token = oauth.fetch_token( token_url='https://id.twitch.tv/oauth2/token', body=body) except Exception: raise ValueError("OAuth: failed to get token") self.oauth = token["access_token"]
def obtain_auth_token(secrets): """ Method to obtain the authorization token as per the OAuth2 authorization flow :param secrets dictionary containing the client_id and client_secret keys and their respective values :type secrets: dict :return: authorization token :rtype: string """ client_id = secrets['client_id'] client_secret = secrets['client_secret'] auth = HTTPBasicAuth(client_id, client_secret) client = BackendApplicationClient(client_id=client_id) oauth = OAuth2Session(client=client) try: token = oauth.fetch_token(token_url=TOKEN_URL, client_id=client_id, client_secret=client_secret, auth=auth) except Exception as exc: complain('Unable to obtain authentication token due to exception: ' + str(exc)) return token