def __init__(self, url: str, ssl_verify: [str, bool], proto: str = 'https://', proxies: Dict[str, str] = None, interactive: bool = False): """Define a base object Args: url (str): opsman url without the protocol. ssl_verify (str, bool): path to certs or False. proto (str, optional): Protocol to use; defaults to https://. proxies (dict, optional): The proxies to use when making oauth calls. Defaults to None. interactive (bool, optional): If the client will be used in an interactive shell. Defaults to False. """ # Setup inital session self.base_url = f'{proto}{url}' self.api_url = f'{self.base_url}/api/v0' self.__session = requests.Session() self.__session.verify = ssl_verify self.__session.headers.update({'Accept': 'application/json'}) if 'OPSMAN_CLIENT_ID' not in os.environ and not interactive: raise NameError('Environment variable, OPSMAN_CLIENT_ID, is not set.') self.client_id = os.getenv('OPSMAN_CLIENT_ID') if not self.client_id: self.client_id = input(f"Opsman Client ID: ") # Get Token authorize_url = f'{self.base_url}/oauth/authorize' login_url = f'{self.base_url}/uaa/oauth/token' if 'OPSMAN_CLIENT_SECRET' not in os.environ: if not interactive: raise NameError('Environment variable, OPSMAN_CLIENT_SECRET, is not set.') else: service_info = ServiceInformation(authorize_url, login_url, self.client_id, getpass.getpass(f"Opsman Client Secret: "), [], ssl_verify) super(OpsmanClient, self).__init__(service_info, proxies=proxies) else: service_info = ServiceInformation(authorize_url, login_url, self.client_id, os.getenv('OPSMAN_CLIENT_SECRET'), [], ssl_verify) super(OpsmanClient, self).__init__(service_info, proxies=proxies) try: self.init_with_client_credentials() self.__session.headers.update({ 'Authorization': f"bearer {self._access_token}" }) except requests.exceptions.ConnectionError as err: raise ValueError(f'Unable to reach the provided url: {login_url}') except OAuthError as err: raise ValueError(err)
def __init__(self, refresh_token, client_id, client_secret, remote_refresh_token, customer_id, realm, proxies=None): self.realm = realm self.service_information = ServiceInformation(authorize_service, oauhth_url[self.realm], client_id, client_secret, scopes, False) self.client_id = client_id self.manager = OpenIdCredentialManager(self.service_information) self.api_config = Oauth2PSACCApiConfig() self.api_config.set_refresh_callback(self.manager._refresh_token) self.manager.refresh_token = refresh_token self.remote_refresh_token = remote_refresh_token self.remote_access_token = None self.vehicles_list = None self.setProxies(proxies) self.customer_id = customer_id self._confighash = None self.api_config.verify_ssl = False self.api_config.api_key['client_id'] = self.client_id self.api_config.api_key['x-introspect-realm'] = self.realm self.headers = { "x-introspect-realm": realm, "accept": "application/hal+json", }
def __init__(self, target_endpoint, client_id='cf', client_secret='', proxy=None, verify=True): self.info = self._get_info(target_endpoint, proxy, verify=verify) if not self.info.api_version.startswith('2.'): raise AssertionError( 'Only version 2 is supported for now. Found %s' % self.info.api_version) service_informations = ServiceInformation( None, '%s/oauth/token' % self.info.authorization_endpoint, client_id, client_secret, [], verify) super(CloudFoundryClient, self).__init__(service_informations, proxy) CredentialManager.__init__(self, service_informations, proxy) self.v2 = V2(target_endpoint, self) self.v3 = V3(target_endpoint, self) if self.info.doppler_endpoint is not None: self._doppler = DopplerClient( self.info.doppler_endpoint, self.proxies['http' if self.info.doppler_endpoint. startswith('ws://') else 'https'], self.service_information.verify, self) if self.info.doppler_endpoint is not None else None
def __init__(self, target_endpoint, client_id='cf', client_secret='', proxy=None, skip_verification=False): info = self.get_info(target_endpoint, proxy, skip_verification) if not info['api_version'].startswith('2.'): raise AssertionError( 'Only version 2 is supported for now. Found %s' % info['api_version']) service_informations = ServiceInformation( None, '%s/oauth/token' % info['authorization_endpoint'], client_id, client_secret, [], skip_verification) super(CloudFoundryClient, self).__init__(service_informations, proxy) self.service_plans = ServicePlanManager(target_endpoint, self) self.service_instances = ServiceInstanceManager(target_endpoint, self) self.service_keys = ServiceKeyManager(target_endpoint, self) self.service_bindings = ServiceBindingManager(target_endpoint, self) self.service_brokers = ServiceBrokerManager(target_endpoint, self) self.apps = AppManager(target_endpoint, self) self.buildpacks = BuildpackManager(target_endpoint, self) self.stacks = StackManager(target_endpoint, self) # Default implementations self.organizations = EntityManager(target_endpoint, self, '/v2/organizations') self.spaces = EntityManager(target_endpoint, self, '/v2/spaces') self.services = EntityManager(target_endpoint, self, '/v2/services') self.routes = EntityManager(target_endpoint, self, '/v2/routes') self._loggregator_endpoint = info['logging_endpoint'] self._loggregator = None
def get_request_to_authorize(): service_information = ServiceInformation(auth_url,token_server,client_id,client_secret,scopes) manager = CredentialManager(service_information,proxies=dict(http='http://localhost:8080', https='https://localhost:8080')) url = manager.init_authorize_code_process(redirect_uri, state) webbrowser.open(auth_url, new=2) #gets the code from the aurthorization server and checks returnedstate is equal to given state code = manager.wait_and_terminate_authorize_code_process() return code
def __init__(self, target_endpoint: str, client_id: str = "cf", client_secret: str = "", **kwargs): """ " :param target_endpoint :the target endpoint :param client_id: the client_id :param client_secret: the client secret :param proxy: a dict object with entries http and https :param verify: parameter directly passed to underlying requests library. (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. :param token_format: string Can be set to opaque to retrieve an opaque and revocable token. See UAA API specifications :param login_hint: string. Indicates the identity provider to be used. The passed string has to be a URL-Encoded JSON Object, containing the field origin with value as origin_key of an identity provider. Note that this identity provider must support the grant type password. See UAA API specifications """ proxy = kwargs.get("proxy", dict(http="", https="")) verify = kwargs.get("verify", True) self.token_format = kwargs.get("token_format") self.login_hint = kwargs.get("login_hint") target_endpoint_trimmed = target_endpoint.rstrip("/") info = self._get_info(target_endpoint_trimmed, proxy, verify=verify) if not info.api_v2_version.startswith("2."): raise AssertionError( "Only version 2 is supported for now. Found %s" % info.api_v2_version) service_information = ServiceInformation( None, "%s/oauth/token" % info.authorization_endpoint, client_id, client_secret, [], verify) super(CloudFoundryClient, self).__init__(service_information, proxies=proxy) self.v2 = V2(target_endpoint_trimmed, self) self.v3 = V3(target_endpoint_trimmed, self) self._doppler = (DopplerClient( info.doppler_endpoint, self.proxies["http" if info.doppler_endpoint. startswith("ws://") else "https"], self.service_information.verify, self, ) if info.doppler_endpoint is not None else None) self._rlpgateway = (RLPGatewayClient( info.log_stream_endpoint, self.proxies["https"], self.service_information.verify, self, ) if info.log_stream_endpoint is not None else None) self.networking_v1_external = NetworkingV1External( target_endpoint_trimmed, self) self.info = info
def __init__(self, client_id, client_secret, scopes): super(NetatmoClient, self).__init__(ServiceInformation(self.AUTHORIZED_URL, self.TOKEN_URL, client_id, client_secret, scopes), self.PROXY) self._common = Common(self) self._public = Public(self) self._weather = Weather(self) self._energy = Energy(self) self._security = Security(self) self._access_token_value = None
def api_request(client_id, client_secret, uri): service_info = ServiceInformation(AUTH_URL, TOKEN_URL, client_id, client_secret, []) manager = CredentialManager(service_info) manager.init_with_client_credentials() response = manager.get(CISCO_BASE + uri) if response.status_code != 200: print("error from server, code = %s, body=\n%s" % (response.status_code, response.text)) return False json_response = json.loads(response.text) return json_response['advisories']
def __init__(self, client_id, client_secret, redirect_uri): proxies = dict(http=environ.get('HTTP_PROXY', ''), https=environ.get('HTTPS_PROXY', '')) # some certificates such as netatmo are invalid super(ApiManager, self).__init__( ServiceInformation('%s/oauth/v2/authorize' % URL_API, '%s/oauth/v2/token' % URL_API, client_id=client_id, client_secret=client_secret, scopes=ApiManager.SCOPES, skip_ssl_verifications=False), proxies) self.folders = Folders(self) self.freespace = Freespace(self) self.files = Files(self) self.redirect_uri = redirect_uri
def __init__(self, target_endpoint, client_id='cf', client_secret='', **kwargs): """" :param target_endpoint :the target endpoint :param client_id: the client_id :param client_secret: the client secret :param proxy: a dict object with entries http and https :param verify: parameter directly passed to underlying requests library. (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. :param token_format: string Can be set to opaque to retrieve an opaque and revocable token. See UAA API specifications :param login_hint: string. Indicates the identity provider to be used. The passed string has to be a URL-Encoded JSON Object, containing the field origin with value as origin_key of an identity provider. Note that this identity provider must support the grant type password. See UAA API specifications """ proxy = kwargs.get('proxy', dict(http='', https='')) verify = kwargs.get('verify', True) self.token_format = kwargs.get('token_format') self.login_hint = kwargs.get('login_hint') info = self._get_info(target_endpoint, proxy, verify=verify) if not info.api_version.startswith('2.'): raise AssertionError( 'Only version 2 is supported for now. Found %s' % info.api_version) service_information = ServiceInformation( None, '%s/oauth/token' % info.authorization_endpoint, client_id, client_secret, [], verify) super(CloudFoundryClient, self).__init__(service_information, proxies=proxy) self.v2 = V2(target_endpoint, self) self.v3 = V3(target_endpoint, self) self._doppler = DopplerClient( info.doppler_endpoint, self.proxies['http' if info.doppler_endpoint. startswith('ws://') else 'https'], self.service_information.verify, self) if info.doppler_endpoint is not None else None self.info = info
def __init__(self, refresh_token, client_id, client_secret, remote_refresh_token, customer_id, realm, country_code, proxies=None, weather_api=None): self.realm = realm self.service_information = ServiceInformation(authorize_service, oauhth_url[self.realm], client_id, client_secret, scopes, False) self.client_id = client_id self.manager = OpenIdCredentialManager(self.service_information) self.api_config = Oauth2PSACCApiConfig() self.api_config.set_refresh_callback(self.manager._refresh_token) self.manager.refresh_token = refresh_token self.remote_refresh_token = remote_refresh_token self.remote_access_token = None self.vehicles_list = Cars.load_cars(CARS_FILE) self.set_proxies(proxies) self.customer_id = customer_id self._config_hash = None self.api_config.verify_ssl = False self.api_config.api_key['client_id'] = self.client_id self.api_config.api_key['x-introspect-realm'] = self.realm self.headers = { "x-introspect-realm": realm, "accept": "application/hal+json", "User-Agent": "okhttp/4.8.0", } self.remote_token_last_update = None self._record_enabled = False self.otp = None self.weather_api = weather_api self.country_code = country_code self.mqtt_client = None self.precond_programs = {} self.info_callback = [] self.info_refresh_rate = 120
def __init__(self, client_id, client_secret, scopes, skip_ssl_verifications=False): super(DatashareClient, self).__init__( ServiceInformation( authorize_service='%s/oauth/authorize' % self.ENDPOINT, token_service='%s/oauth/token' % self.ENDPOINT, client_id=client_id, client_secret=client_secret, scopes=scopes, skip_ssl_verifications=skip_ssl_verifications), self.PROXIES) self._connection = ConnectionApi(self) self._device = DeviceApi(self) self._data = DataApi(self) self._deprecated_data = DataApiV1(self) self._subscription = SubscriptionApi(self) self._command = CommandApi(self)
def __init__(self, refresh_token, client_id, client_secret, remote_refresh_token, customer_id, realm, country_code, proxies=None, weather_api=None, abrp=None, co2_signal_api=None): self.realm = realm self.service_information = ServiceInformation(AUTHORIZE_SERVICE, realm_info[self.realm]['oauth_url'], client_id, client_secret, SCOPE, False) self.client_id = client_id self.manager = OpenIdCredentialManager(self.service_information) self.api_config = Oauth2PSACCApiConfig() self.api_config.set_refresh_callback(self.refresh_token) self.manager.refresh_token = refresh_token self.remote_refresh_token = remote_refresh_token self.remote_access_token = None self.vehicles_list = Cars.load_cars(CARS_FILE) self.customer_id = customer_id self._config_hash = None self.api_config.verify_ssl = False self.api_config.api_key['client_id'] = self.client_id self.api_config.api_key['x-introspect-realm'] = self.realm self.headers = { "x-introspect-realm": realm, "accept": "application/hal+json", "User-Agent": "okhttp/4.8.0", } self.remote_token_last_update = None self._record_enabled = False self.otp = None self.weather_api = weather_api self.country_code = country_code self.mqtt_client = None self.precond_programs = {} self.info_callback = [] self.info_refresh_rate = 120 if abrp is None: self.abrp = Abrp() else: self.abrp: Abrp = Abrp(**abrp) self.set_proxies(proxies) self.config_file = DEFAULT_CONFIG_FILENAME Ecomix.co2_signal_key = co2_signal_api
def __init__(self, refresh_token, client_id, client_secret, remote_refresh_token, customer_id, realm, country_code, proxies=None, weather_api=None, abrp=None, co2_signal_api=None): self.realm = realm self.service_information = ServiceInformation(AUTHORIZE_SERVICE, realm_info[self.realm]['oauth_url'], client_id, client_secret, SCOPE, False) self.client_id = client_id self.manager = OpenIdCredentialManager(self.service_information) self.api_config = Oauth2PSACCApiConfig() self.api_config.set_refresh_callback(self.manager.refresh_token_now) self.manager.refresh_token = refresh_token self.account_info = AccountInformation(client_id, customer_id, realm, country_code) self.remote_access_token = None self.vehicles_list = Cars.load_cars(CARS_FILE) self.customer_id = customer_id self._config_hash = None self.api_config.verify_ssl = False self.api_config.api_key['client_id'] = self.client_id self.api_config.api_key['x-introspect-realm'] = self.realm self.remote_token_last_update = None self._record_enabled = False self.weather_api = weather_api self.country_code = country_code self.info_callback = [] self.info_refresh_rate = 120 if abrp is None: self.abrp = Abrp() else: self.abrp: Abrp = Abrp(**abrp) self.set_proxies(proxies) self.config_file = DEFAULT_CONFIG_FILENAME Ecomix.co2_signal_key = co2_signal_api self.refresh_thread = None remote_credentials = RemoteCredentials(remote_refresh_token) remote_credentials.update_callbacks.append(self.save_config) self.remote_client = RemoteClient(self.account_info, self.vehicles_list, self.manager, remote_credentials)
def detail(request): code = request.GET["code"] try: scopes = ['scope_1', 'scope_2'] service_information = ServiceInformation(settings.AUTHORIZATION_URI, settings.ACCESS_TOKEN_URI, settings.CLIENT_ID, settings.CLIENT_SECRET, scopes) manager = CredentialManager(service_information) redirect_uri = settings.REDIRECT_URI manager.init_with_authorize_code(redirect_uri, code) token = manager._access_token ### call to API with token ### endpoint = "https://api.intra.42.fr/v2/me" data = {"ip": "1.1.2.3"} headers = {"Authorization": "Bearer " + token} me = requests.get(endpoint, data=data, headers=headers).json() except OAuthError: return (redirect('/')) return render(request, 'polls/detail.html', {'me': me})
from oauth2_client.credentials_manager import CredentialManager, ServiceInformation, OAuthError from oauth2_client.http_server import read_request_parameters, _ReuseAddressTcpServer _logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG, format='%(levelname)5s - %(name)s - %(message)s') authorize_server_port = 9090 token_server_port = 9091 api_server_port = 9092 redirect_server_port = 9099 service_information = ServiceInformation( authorize_service='http://localhost:%d/oauth/authorize' % authorize_server_port, token_service='http://localhost:%d/oauth/token' % token_server_port, client_id='client_id_test', client_secret='client_secret_test', scopes=['scope1', 'scope2']) basic_auth = 'Basic Y2xpZW50X2lkX3Rlc3Q6Y2xpZW50X3NlY3JldF90ZXN0' class FakeOAuthHandler(BaseHTTPRequestHandler): CODE = '123' def do_GET(self): """ Handle requests of authorize process :return: """
def authenticate(): while not config.jira.url: part = input(NEED_JIRA_URL) path = Tempo.matching_instances(part) if path: config.jira.url = path if config.tempo.access_token: if validate_access_token(config.tempo.access_token): return logger.info( f'Could not validate access using {config.tempo.access_token}' ) # config.tempo.access_token = None if config.tempo.client_id and config.tempo.client_secret: service_information = ServiceInformation( urljoin( config.jira.url, '/plugins/servlet/ac/io.tempo.jira/oauth-authorize/' ), urljoin( config.tempo.api_url, '/oauth/token/', ), config.tempo.client_id, config.tempo.client_secret, [], ) manager = CredentialManager( service_information, ) if config.tempo.refresh_token: try: manager.init_with_token(config.tempo.refresh_token) if validate_access_token(manager._access_token): config.tempo.access_token = manager._access_token return except OAuthError: pass if input(BAD_ACCESS_TOKEN).lower()[0] != 'y': sys.exit(1) redirect_uri = 'http://localhost:8158/oauth/code' url = manager.init_authorize_code_process( redirect_uri, str(uuid.uuid4()) ) url = f'{url}&access_type=tenant_user' logger.info('Opening this url in your browser: %s', url) webbrowser.open(url) print('Please finish the authorization process in your browser.') code = manager.wait_and_terminate_authorize_code_process() logger.debug('Code got = %s', code) manager.init_with_authorize_code(redirect_uri, code) logger.debug('Access got = %s', manager._access_token) config.tempo.access_token = manager._access_token config.tempo.refresh_token = manager.refresh_token else: webbrowser.open( urljoin( config.jira.url, '/plugins/servlet/ac/io.tempo.jira/tempo-configuration/' ) ) access_token = input( 'I opened a new browser window where you can get an access token. ' 'Paste your access token here:' ) if validate_access_token(access_token): config.tempo.access_token = access_token else: print('Could not communicate with tempo. Check the logs.') sys.exit(1)
##################################################################### ##loginidとパスワードを使ってMisoca(ミソカ) APIを使うサンプル ##################################################################### from logging import getLogger, StreamHandler, Formatter from oauth2_client.credentials_manager import CredentialManager, ServiceInformation import urllib.request scopes = ['read', 'write'] service_information = ServiceInformation( 'https://app.misoca.jp/oauth2/authorize', #authorizeのULR 'https://app.misoca.jp/oauth2/token', #tokenのULR 'アプリケーションIDを設定すること', 'シークレットIDを設定すること', scopes) manager = CredentialManager(service_information) manager.init_with_user_credentials('login idを設定', 'パスワードを設定') print('Access got = %s' % manager._access_token) # Here access and refresh token may be used response = manager.get("https://app.misoca.jp/api/v3/contacts") print(response.text)
def __init__(self, env): self.___manager = CredentialManager( ServiceInformation(env.oauth.authorize, env.oauth.token, env.oauth.clintId, env.oauth.clientSecret, self.___scope))