def test_wsse_username_nonce(self): security = Security() token = UsernameToken("username", "password") token.setnonce() token.setcreated() token.setnonceencoding(True) token.setpassworddigest("digest") security.tokens.append(token) assert "<wsu:Created" in str(security.xml())
def test_wsse_username_token(self): security = Security() token = UsernameToken("username", "password") security.tokens.append(token) expected = """<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" mustUnderstand="true"> <wsse:UsernameToken> <wsse:Username>username</wsse:Username> <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">password</wsse:Password> </wsse:UsernameToken> </wsse:Security>""" assert expected == str(security.xml())
def __init__(self, username, password, subscriber_id): """ Parameters: :param username: - Username for accessing the BancBox api. This should be an email address :param password: - Password for access the BancBox api. """ # Initialize the suds Client super(BancboxClient, self).__init__(url=WSDL_LOCATION, location=API_URL, plugins=[PasswordTypePlugin()]) # Set WSSE security headers # Create a new SUDS Security object security = Security() # Create a WSSE UsernameToken with the supplied username and password token = UsernameToken(username, password) # Add the token to the Security object security.tokens.append(token) # Set the security settings on the SUDS Client self.set_options(wsse=security) self.subscriber_id = subscriber_id
def proof_of_delivery(self, shipment_awb, detailed=True): """ Connects to DHL ePOD service, and returns the POD for the requested shipment. :param shipment_awb: shipment waybill or identification number :param detailed: if a detailed POD should be returned, else simple :return: (True, pdf bytes) if successful else (False, [errors]) """ if not self.pod_client: url = self.pod_test_url if self.test_mode else self.pod_url self.pod_client = Client(url, faults=False) security = Security() token = UsernameToken(self.username, self.password) security.tokens.append(token) self.pod_client.set_options(wsse=security) msg = self._create_dhl_shipment_document(shipment_awb, detailed) code, res = self.pod_client.service.ShipmentDocumentRetrieve(msg) if code == 500: return DHLPodResponse(False, errors=[res.detail.detailmessage]) try: img = res.Bd.Shp[0].ShpInDoc[0].SDoc[0].Img[0]._Img return DHLPodResponse(True, img) except: return DHLPodResponse(False, errors=[ error.DatErrMsg.ErrMsgDtl._DtlDsc for error in res.DatTrErr ])
def rate_request(self, shipment, message=None): """ Contacts to DHL Rate Request to obtain carrier rates for this shipment :param shipment: DHLShipment object :param message: optional message :return: DHLResponse """ if not self.shipment_client: url = self.shipment_test_url if self.test_mode else \ self.shipment_url self.shipment_client = Client(url, faults=False) security = Security() token = UsernameToken(self.username, self.password) security.tokens.append(token) self.shipment_client.set_options(wsse=security) dhl_shipment = self._create_dhl_shipment_type2(self.shipment_client, shipment) result_code, reply = self.shipment_client.service.getRateRequest( None, dhl_shipment) if result_code == 500: return DHLPodResponse(False, errors=[reply.detail.detailmessage]) for rate_reply in reply: notif = rate_reply.Notification if notif._code != '0': print('[Code: ' + notif._code + ', ' 'Message: ' + notif.Message + ']') return DHLPodResponse(False, errors=[(notif._code, notif.Message)]) return DHLRateResponse(True, rate_reply.Service)
def _setup_client(self, faults=False, wsse=False): client_args = { 'url': self.service_url, 'faults': faults, 'plugins': [LogPlugin(self.log_name)], 'timeout': 100, } log.info("Setting up SOAP client with WSDL at {wsdl_url}".format( wsdl_url=self.service_url)) if self.location_url: log.info("Overloading default location url with {url}".format( url=self.location_url)) client_args['location'] = self.location_url if wsse: log.info("Using WSSE for authentication.") security = Security() # noinspection PyTypeChecker security.tokens.append(UsernameToken(self.username, self.password)) client_args['wsse'] = security else: log.info("NOT using WSSE for authentication.") try: suds_client = Client(**client_args) except Exception as error: import traceback log.error(traceback.format_exc()) err_prefix = "Could not create SOAP client at {url}. Error message: {err}" err_msg = err_prefix.format(url=self.service_url, err=unicode(error)) raise BrregClientError(err_msg) self._suds_client = suds_client
def add_client(): sec_type = self.config['sec_type'] if sec_type == security_def_type.basic_auth: transport = HttpAuthenticated(**self.suds_auth) elif sec_type == security_def_type.ntlm: transport = WindowsHttpAuthenticated(**self.suds_auth) elif sec_type == security_def_type.wss: security = Security() token = UsernameToken(self.suds_auth['username'], self.suds_auth['password']) security.tokens.append(token) client = Client(url, autoblend=True, wsse=security) if sec_type in (security_def_type.basic_auth, security_def_type.ntlm): client = Client(url, autoblend=True, transport=transport) # Still could be either none at all or WSS if not sec_type: client = Client(url, autoblend=True) self.client.queue.put(client) logger.debug('Adding Suds SOAP client to [%s]', url)
def get_client(self, endpoint): class FixMimeMultipart(MessagePlugin): """ StudySubject.listAllByStudy replies with what looks like part of a multipart MIME message(!?) Fix this. """ def received(self, context): reply = context.reply if reply.startswith('------='): matches = re.search( r'(<SOAP-ENV:Envelope.*</SOAP-ENV:Envelope>)', reply) context.reply = matches.group(1) if endpoint not in self._clients: raise ValueError('Unknown OpenClinica API endpoint') if self._clients[endpoint] is None: client = Client( '{url}OpenClinica-ws/ws/{endpoint}/v1/{endpoint}Wsdl.wsdl'. format(url=self._base_url, endpoint=endpoint), plugins=[FixMimeMultipart()]) security = Security() password = hashlib.sha1(self._password).hexdigest( ) # SHA1, not AES as documentation says token = UsernameToken(self._username, password) security.tokens.append(token) client.set_options(wsse=security) self._clients[endpoint] = client return self._clients[endpoint]
def make(self, authenticator: Authenticator): """Build and configure soap client""" if self._client is None: self._client = SoapClient(self._local_url, faults=False, cachingpolicy=0) if self.debug: logging.basicConfig(level=logging.INFO) logging.getLogger('suds.client').setLevel(logging.DEBUG) logging.getLogger('suds.transport').setLevel(logging.DEBUG) logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG) logging.getLogger('suds.wsdl').setLevel(logging.DEBUG) else: logging.getLogger('suds').setLevel(logging.INFO) # FIXME # Need make copy by suds.client.clone() method, # but now got this issue https://bitbucket.org/jurko/suds/issues/7/recursion-depth-reached # cl = self._client.clone() cl = self._client cl.set_options(location=authenticator.endpoint) security = Security() token = UsernameToken('*', '*') security.tokens.append(token) cl.set_options(wsse=security) element_oauth = Element('oAuth', ns=('etns', 'http://exacttarget.com')) element_oauth_token = Element('oAuthToken').setText(authenticator.auth_legacy_token) element_oauth.append(element_oauth_token) cl.set_options(soapheaders=[element_oauth]) return cl
def add_client(self): logger.info('About to add a client to `%s` (%s)', self.address, self.conn_type) # Lazily-imported here to make sure gevent monkey patches everything well in advance from suds.client import Client from suds.transport.https import HttpAuthenticated from suds.transport.https import WindowsHttpAuthenticated from suds.wsse import Security, UsernameToken sec_type = self.config['sec_type'] if sec_type == SEC_DEF_TYPE.BASIC_AUTH: transport = HttpAuthenticated(**self.suds_auth) elif sec_type == SEC_DEF_TYPE.NTLM: transport = WindowsHttpAuthenticated(**self.suds_auth) elif sec_type == SEC_DEF_TYPE.WSS: security = Security() token = UsernameToken(self.suds_auth['username'], self.suds_auth['password']) security.tokens.append(token) client = Client(self.address, autoblend=True, wsse=security) if sec_type in(SEC_DEF_TYPE.BASIC_AUTH, SEC_DEF_TYPE.NTLM): client = Client(self.address, autoblend=True, transport=transport) # Still could be either none at all or WSS if not sec_type: client = Client(self.address, autoblend=True, timeout=self.config['timeout']) self.client.put_client(client)
def setSoapHeader(client, username, password): security = Security() token = UsernameToken(username, password) token.setcreated() security.tokens.append(token) if debug: print security client.set_options(wsse=security)
def __init__(self): self.username_soa = settings.get("username_soa") self.password_soa = settings.get("password_soa") self.client = Client(self.url) security = Security() security.tokens.append( UsernameToken(self.username_soa, self.password_soa)) self.client.set_options(wsse=security)
def __init__(self, bus_user, bus_pass, wsdl): # Crear client SOA amb Securitiy activat # Obtenim el client amb z3c.suds i no amb suds.Client self.client = get_suds_client(wsdl) security = Security() token = UsernameToken(bus_user, bus_pass) security.tokens.append(token) self.client.set_options(wsse=security)
def _init_client(self, wsdl_definition, endpoint): client = Client(wsdl_definition, location=endpoint) security = Security() token = UsernameDigestToken(settings.MODC_DOI_API_ID, settings.MODC_DOI_API_PASSWORD) security.tokens.append(token) client.set_options(wsse=security) return client
def init_client(self): client = Client(self.config.wsdl_url) # Add wsse security security = Security() token = UsernameToken(username=self.config.merchant_id, password=self.config.api_key) security.tokens.append(token) client.set_options(wsse=security) return client
def __init__(self, user_login, user_passwd): """ Initialize a checker object, with authenticated access """ from suds.cache import ObjectCache from suds.wsse import Security, UsernameToken if not (user_login and user_passwd): raise RuntimeError( "You must specify user AFM and token for authentication") security = Security() security.tokens.append(UsernameToken(user_login, user_passwd)) self._client = self._getClient(wsse=security)
def get_icgc_geoencoder_client(self): if not self.icgc_geoencoder_client: # Configure connection security wsse_security = Security() username_digest_token = UsernameDigestToken('QGIS', 'QGIS') wsse_security.tokens.append(username_digest_token) # SOAP client configuration with Password Digest # Available functions: [localitzaAdreca, obtenirInfoPunt, localitzaToponim, cercaCaixaUnica, localitzaCruilla, localitzaPK, geocodificacioInversa] self.icgc_geoencoder_client = Client( url="http://www.icc.cat/geocodificador/ws/wss_1.0?wsdl", wsse=wsse_security) #, timeout=3) return self.icgc_geoencoder_client
def issue_credit(self, source, amount, currency): order = source.order try: order_request_token = source.reference security = Security() token = UsernameToken(self.merchant_id, self.transaction_key) security.tokens.append(token) client = Client(self.soap_api_url, transport=RequestsTransport()) client.set_options(wsse=security) credit_service = client.factory.create('ns0:CCCreditService') credit_service._run = 'true' # pylint: disable=protected-access credit_service.captureRequestID = source.reference purchase_totals = client.factory.create('ns0:PurchaseTotals') purchase_totals.currency = currency purchase_totals.grandTotalAmount = unicode(amount) response = client.service.runTransaction( merchantID=self.merchant_id, merchantReferenceCode=order.number, orderRequestToken=order_request_token, ccCreditService=credit_service, purchaseTotals=purchase_totals) request_id = response.requestID ppr = self.record_processor_response( suds_response_to_dict(response), transaction_id=request_id, basket=order.basket) except: msg = 'An error occurred while attempting to issue a credit (via CyberSource) for order [{}].'.format( order.number) logger.exception(msg) raise GatewayError(msg) if response.decision == 'ACCEPT': source.refund(amount, reference=request_id) event_type, __ = PaymentEventType.objects.get_or_create( name=PaymentEventTypeName.REFUNDED) PaymentEvent.objects.create(event_type=event_type, order=order, amount=amount, reference=request_id, processor_name=self.NAME) else: raise GatewayError( 'Failed to issue CyberSource credit for order [{order_number}]. ' 'Complete response has been recorded in entry [{response_id}]'. format(order_number=order.number, response_id=ppr.id))
def _build(self): #this is used for performance, wsdl and header will be built on initialization of object to save time and redudancy wsdl_url = 'https://wd2-impl-services1.workday.com/ccx/service/' + self.tenant + '/' + self.wws + '/' + self.version +'?wsdl' print wsdl_url print self.username +'\n' + 'building wsdl for ' + self.wws + ' object' self.client1 = client.Client(wsdl_url) # Wrapping our client call in Security() like this results in submitting # the auth request with PasswordType in headers in the format WD expects. security = Security() token = UsernameToken(self.username, self.password) security.tokens.append(token) self.client1.set_options(wsse=security) print '\n'+ ' wsdl and header has been built'
def create_suds_client(wsdl_url, key_data, cert_data, tbk_cert_data): transport = HttpTransport() wsse = Security() wsse_plugin = WssePlugin.init_from_data( key_data=key_data, cert_data=cert_data, tbk_cert_data=tbk_cert_data, ) return Client( url=wsdl_url, transport=transport, wsse=wsse, plugins=[wsse_plugin], )
def parse_wsdl(self): """ Parses WSDL file to determine available services and objects. Sets WSSE security object as well. """ logger.debug("Parsing WSDL: %s...", self.settings['wsdl_path']) self.jasper_client = Client(self.settings['wsdl_path']) # WSSE security security = Security() token = UsernameToken(self.settings['username'], self.settings['password']) security.tokens.append(token) self.jasper_client.set_options(wsse=security, timeout=600)
def init_client(self): try: # create the SOAP client self.client = Client(self.schema_url) except URLError as e: self.log(e, logging.CRITICAL) return None # add WS-Security token security = Security() token = UsernameToken(self.username, self.password) security.tokens.append(token) self.client.set_options(wsse=security) return self.client
def create_tokens(response): security = Security() token = UsernameToken(AUTHORIZED_NUI) token.setcreated(response.Fecha) token.nonce_has_encoding = True token.setnonce(response.Nonce) token.setpassworddigest(response.Digest) security.tokens.append(token) token_ts = Timestamp() token_ts.created = response.Fecha token_ts.expires = response.FechaF security.tokens.append(token_ts) return security
def __init__(self, prod_environment, username, password): if not prod_environment: wsdl_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '../api/test/server.wsdl') else: wsdl_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), '../api/prod/server.wsdl') self.client = Client('file:///%s' % wsdl_path.lstrip('/')) security = Security() token = UsernameToken(username, password) security.tokens.append(token) self.client.set_options(wsse=security)
def __init__(self, wsdl, merchant_id, transaction_security_key, soap_log_prefix="CYBERSOURCE"): self.merchant_id = merchant_id # Build a SOAP client self.client = soap.get_client(wsdl, soap_log_prefix) # Add WSSE Security Header to client security = Security() token = UsernameToken(self.merchant_id, transaction_security_key) security.tokens.append(token) self.client.set_options(wsse=security)
def get_client(self,): transport=HttpTransport() wsse = Security() return Client( self._get_webpay_urls(), transport=transport, wsse=wsse, plugins=[ WssePlugin( keyfile=self.get_private_key(), certfile=self.get_public_cert(), their_certfile=self.get_WebPay_cert(), ), ], )
def get_client(): """ Obtenemos la informacion de nuestro cliente. """ return Client( settings.WEBPAY_WSDL, transport=HttpTransport(), wsse=Security(), plugins=[ WssePlugin( keyfile=settings.WEBPAY_OUR_PRIVATE_KEY, certfile=settings.WEBPAY_OUR_PUBLIC_CERT, their_certfile=settings.WEBPAY_CERT, ), ], )
def add_tokens(response, student_identity): """ Agregar token de seguridad y de tiempo en header de WS """ security = Security() token = UsernameToken(settings.WS_CONFIG['identity']) token.setcreated(response.Fecha) token.nonce_has_encoding = True token.setnonce(response.Nonce) token.setpassworddigest(response.Digest) security.tokens.append(token) token_ts = Timestamp() token_ts.created = response.Fecha token_ts.expires = response.FechaF security.tokens.append(token_ts) return security
def get_client(wsdl_url, our_keyfile_path, our_certfile_path, their_certfile_path): transport = HttpTransport() wsse = Security() return Client( wsdl_url, transport=transport, wsse=wsse, plugins=[ WssePlugin( keyfile=our_keyfile_path, certfile=our_certfile_path, their_certfile=their_certfile_path, ), ], )
def set_wsse(self, user=None, passwd=None): ''' Basic ws-security auth ''' if user: self.user = user if passwd: self.passwd = passwd security = Security() if self.encrypt: token = UsernameDigestToken(self.user, self.passwd) else: token = UsernameToken(self.user, self.passwd) token.setnonce() token.setcreated() security.tokens.append(token) self.ws_client.set_options(wsse=security)
def __init__(self): Security.__init__(self) self.mustUnderstand = 1 self.nsprefixes = {}
def _get_wsse(self, create=True): wsse = self._client().options.wsse if wsse is None and create: wsse = Security() wsse.mustUnderstand = '1' return wsse