Example #1
0
def gen_wss_token(user, passw, method='Digest', nonce=True, created=True):
    """Method generates WSS token

    Args:   
       user (str): username
       passw (str): password
       method (str): token method Text|Digest
       nonce (bool): include nonce
       created (bool): include created      

    Returns:
       dict

    """

    token = UsernameToken(user, passw)
    if (nonce):
        token.setnonce()
    if (created):
        token.setcreated()

    token = {'username': user, 'password': passw, 'nonce': str(
        token.nonce), 'created': str(token.created)}
    if (method == 'Digest'):
        token['created'] = datetime.utcnow().isoformat()[:-3] + 'Z'
        token['password'] = encodestring(
            sha1(token['nonce'] + token['created'] + passw).digest())[:-1]
        token['nonce'] = encodestring(token['nonce'])[:-1]

    return token
def add_security(client, user, passwd):
    sec = Security()
    token = UsernameToken(user, passwd)
    token.setnonce()
    token.setcreated()
    sec.tokens.append(token)
    client.set_options(wsse=sec)
 def __init__(self, username=None, password=None, setcreated=False,
              setnonce=False, digest=False):
     if digest:
         raise NotImplementedError()
     UsernameToken.__init__(self, username, password)
     self.autosetcreated = setcreated
     self.autosetnonce = setnonce
Example #4
0
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)
Example #5
0
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)
Example #6
0
 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())
Example #7
0
 def __init__(self, username=None, password=None):
     """
     @param username: A username.
     @type username: str
     @param password: A password.
     @type password: str
     """
     UsernameToken.__init__(self, username, password)
     self.nsprefixes = {}
 def __init__(self,
              username=None,
              password=None,
              setcreated=False,
              setnonce=False,
              digest=False):
     UsernameToken.__init__(self, username, password)
     self.autosetcreated = setcreated
     self.autosetnonce = setnonce
     self.digest = digest
Example #9
0
 def __init__(self, username=None, password=None):
     UsernameToken.__init__(self, username, password)
     utc = UsernameToken.utc()
     utc = datetime(utc.year,
                    utc.month,
                    utc.day,
                    utc.hour,
                    utc.minute,
                    utc.second,
                    tzinfo=utc.tzinfo)
     self.setcreated(utc)
     self.setnonce()
Example #10
0
 def __init__(self, username=None, password=None):
     UsernameToken.__init__(
         self,
         username,
         password
     )
     utc = UsernameToken.utc()
     utc = datetime(
         utc.year, utc.month, utc.day,
         utc.hour, utc.minute, utc.second,
         tzinfo=utc.tzinfo
     )
     self.setcreated(utc)
     self.setnonce()
    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
Example #12
0
    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)
Example #13
0
    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
                                  ])
Example #14
0
            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)
Example #15
0
    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]
Example #16
0
    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)
Example #17
0
    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
Example #18
0
    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
Example #19
0
 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)
Example #20
0
 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)
Example #21
0
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
Example #22
0
    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
Example #23
0
 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)
Example #24
0
    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())
Example #25
0
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
Example #26
0
    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))
Example #27
0
	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'
Example #28
0
    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)
Example #29
0
    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
Example #30
0
    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)
Example #32
0
 def xml(self):
     usernametoken = UsernameToken.xml(self)
     password = usernametoken.getChild('Password')
     nonce = usernametoken.getChild('Nonce')
     created = usernametoken.getChild('Created')
     password.set('Type', 'http://docs.oasis-open.org/wss/2004/01/'
                          'oasis-200401-wss-username-token-profile-1.0'
                          '#PasswordDigest')
     s = sha1()
     s.update(self.raw_nonce)
     s.update(created.getText())
     s.update(password.getText())
     password.setText(b64encode(s.digest()))
     nonce.set('EncodingType', 'http://docs.oasis-open.org/wss/2004'
         '/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary')
     return usernametoken
Example #33
0
    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)
Example #34
0
def getDate(wl):
    import datetime
    from suds.client import Client
    url = "http://10.31.70.153:7049/LoadTrafficRecordsScript/LoadTrafficRecordsScript?WSDL"
    client = Client(url)
    from suds.wsse import Security
    from suds.wsse import UsernameToken
    security = Security()
    token = UsernameToken(wl[0], wl[1])
    security.tokens.append(token)
    client.set_options(wsse=security)
    client.set_options(soapheaders=wl[2])
    response = client.service.getCurrentBillingPeriod()
    if response.results.result[
            0].billingPeriodDate.month == datetime.date.today().month:
        return None
    else:
        return response.results.result[0].billingPeriodDate.strftime('%Y%m')
Example #35
0
    def __init__(self, webservice_type, host, port, ssl, username, password):
        url = ''
        if (ssl):
            url = 'https://' + host + ':' + port
        else:
            url = 'http://' + host + ':' + port
        if webservice_type == 'configuration':
            self.wsdlFile = url + '/ws/v9/configurationservice?wsdl'
        elif webservice_type == 'defect':
            self.wsdlFile = url + '/ws/v9/defectservice?wsdl'
        else:
            raise "unknown web service type: " + webservice_type

        self.client = Client(self.wsdlFile)
        self.security = Security()
        self.token = UsernameToken(username, password)
        self.security.tokens.append(self.token)
        self.client.set_options(wsse=self.security)
Example #36
0
 def pass_security_cert(self):
     """
     https接口需要安全验证
     :return: 通过返回true,没有连接信息或者验证失败返回false
     """
     if not self.client:
         return False
     else:
         security = Security()
         token = UsernameToken(self.user, self.password)
         security.tokens.append(token)
         try:
             self.client.set_options(wsse=security)
         except AttributeError as e:
             # print('need a log')
             self.error_logger.error('%s: %s' % (self.app_name, e.args[0]))
             MailHandler().send_mail(e.args[0], self.url)
             return False
         else:
             return True
Example #37
0
def workday_client_login(*args, **kwargs):
    wsdl_url = kwargs['wsdl_url']
    username = kwargs['username']
    password = kwargs['password']
    proxy = kwargs['proxy']
    client_return = None
    print "Connecting to wsdl_url ..."
    try:
        if (proxy.strip() != ""):
            client_return = client.Client(wsdl_url, proxy={'https': proxy})
        else:
            client_return = client.Client(wsdl_url)
        security = Security()
        token = UsernameToken(username, password)
        security.tokens.append(token)
        client_return.set_options(wsse=security)
    except Exception as e:
        print(e)
        return client_return

    print("Logged In to: " + wsdl_url)
    return client_return
 def __init__(self, username=None, password=None):
     UsernameToken.__init__(self, username, password)
     self.setcreated()
     self.setnonce()
Example #39
0
 def setcreated(self, *args, **kwargs):
     UsernameToken.setcreated(self, *args, **kwargs)
     self.created = str(UTC(self.created))
Example #40
0
 def setcreated(self, *args, **kwargs):
     dt_adjusted = None
     if self.dt_diff :
         dt_adjusted = (self.dt_diff + dt.datetime.utcnow())
     UsernameToken.setcreated(self, dt=dt_adjusted, *args, **kwargs)
     self.created = str(UTC(self.created))
Example #41
0
	def setcreated(self, *args, **kwargs):
		UsernameToken.setcreated(self, *args, **kwargs)
		if self.created is None :
			self.created = dt.datetime.utcnow()
		self.created = str(DateTime(self.created))
Example #42
0
 def __init__(self, username=None, password=None, setcreated=False,
              setnonce=False, digest=False):
     UsernameToken.__init__(self, username, password)
     self.autosetcreated = setcreated
     self.autosetnonce = setnonce
     self.digest = digest
Example #43
0
 def setcreated(self, *args, **kwargs):
     UsernameToken.setcreated(self, *args, **kwargs)
     if is_debian_based:
         self.created = str(self.created.replace(tzinfo=UtcTimezone()))
     else:
         self.created = str(UTC(self.created))